<commit_before>#ifndef __MODEL_PARAMETER_TRAINER
#define __MODEL_PARAMETER_TRAINER

#include <array>
#include <vector>
#include <map>

#include "Pore_Model.hpp"
#include "State_Transitions.hpp"
#include "Forward_Backward.hpp"
#include "logsumset.hpp"
#include "logger.hpp"

#if defined(USE_LOGDIFF)
#include "logdiff.hpp"
#endif

template < typename Float_Type = float, unsigned Kmer_Size = 6 >
struct Model_Parameter_Trainer
{
    typedef Kmer< Kmer_Size > Kmer_Type;
    typedef Pore_Model< Float_Type, Kmer_Size > Pore_Model_Type;
    typedef State_Transitions< Float_Type, Kmer_Size > State_Transitions_Type;
    typedef Event< Float_Type > Event_Type;
    typedef Event_Sequence< Float_Type > Event_Sequence_Type;
    typedef Forward_Backward< Float_Type, Kmer_Size > Forward_Backward_Type;
    typedef logsum::logsumset< Float_Type > LogSumSet_Type;

    static void train_one_round(
        const std::vector< const Event_Sequence_Type* >& event_seq_ptrs,
        const std::vector< const Pore_Model_Type* >& model_ptrs,
        const State_Transitions_Type& transitions,
        const Pore_Model_Parameters_Type& crt_pm_params,
        Pore_Model_Parameters_Type& new_pm_params,
        Float_Type& new_fit,
        bool& done)
    {
        // accept either 1 model per sequence, or just 1 model
        assert(model_ptrs.size() == event_seq_ptrs.size() or model_ptrs.size() == 1);
        bool single_model = model_ptrs.size() == 1;
        unsigned n_event_seqs = event_seq_ptrs.size();
        unsigned total_num_events = alg::accumulate(
            event_seq_ptrs, 0u,
            [] (unsigned s, const Event_Sequence_Type* events_ptr) { return s + events_ptr->size(); });
        done = false;
        // apply current scaling parameters, drift correction, and run fwbw
        std::map< const Pore_Model_Type*, Pore_Model_Type > scaled_pm_map;
        for (const auto pm_p : model_ptrs)
        {
            if (scaled_pm_map.count(pm_p)) continue;
            scaled_pm_map.emplace(std::make_pair(pm_p, *pm_p));
            scaled_pm_map[pm_p].scale(crt_pm_params);
        }
        std::vector< Event_Sequence_Type > corrected_event_seqs(n_event_seqs);
        std::vector< Forward_Backward_Type > fwbw(n_event_seqs);
        new_fit = 0;
        for (unsigned k = 0; k < n_event_seqs; ++k)
        {
            const Pore_Model_Type& scaled_pm = scaled_pm_map.at(model_ptrs[single_model? 0 : k]);
            Event_Sequence_Type& corrected_events = corrected_event_seqs[k];
            corrected_events = *event_seq_ptrs[k];
            corrected_events.apply_drift_correction(crt_pm_params.drift);
            fwbw[k].fill(scaled_pm, transitions, corrected_events);
            new_fit += fwbw[k].log_pr_data();
        }
        // compute the scaling matrices (first in logspace)
        // against unscaled pm & uncorrected events
        std::array< std::array< LogSumSet_Type, 3 >, 3 > A_lss =
            {{ {{ false, false, false }},
               {{ false, false, false }},
               {{ false, false, false }} }};
        std::array< LogSumSet_Type, 3 > B_lss = {{ false, false, false }};
        for (unsigned k = 0; k < n_event_seqs; ++k)
        {
            const Event_Sequence_Type& events = *event_seq_ptrs[k];
            const Pore_Model_Type& pm = *model_ptrs[single_model? 0 : k];
            unsigned n_events = events.size();
            for (unsigned i = 0; i < n_events; ++i)
            {
                Float_Type log_x_i = events[i].log_mean;
                Float_Type log_t_i = events[i].log_start;
                LOG(debug1)
                    << "outter_loop k=" << k << " i=" << i
                    << " log_x_i=" << log_x_i
                    << " log_t_i=" << log_t_i << std::endl;
                std::array< LogSumSet_Type, 3 > s_lss = {{ false, false, false }};
                for (unsigned j = 0; j < Pore_Model_Type::n_states; ++j)
                {
                    Float_Type x0 = fwbw[k].log_posterior(i, j) - 2 * pm.state(j).log_level_stdv;
                    Float_Type x1 = x0 + pm.state(j).log_level_mean;
                    Float_Type x2 = x1 + pm.state(j).log_level_mean;
                    LOG(debug2)
                        << "inner_loop k=" << k << " i=" << i << " j=" << j
                        << " x0=" << x0 << " x1=" << x1 << " x2=" << x2 << std::endl;
                    s_lss[0].add(x0);
                    s_lss[1].add(x1);
                    s_lss[2].add(x2);
                }
                A_lss[0][0].add(s_lss[0].val());
                A_lss[0][1].add(s_lss[1].val());
                A_lss[0][2].add(s_lss[0].val() + log_t_i);
                A_lss[1][1].add(s_lss[2].val());
                A_lss[1][2].add(s_lss[1].val() + log_t_i);
                A_lss[2][2].add(s_lss[0].val() + 2 * log_t_i);
                B_lss[0].add(s_lss[0].val() + log_x_i);
                B_lss[1].add(s_lss[1].val() + log_x_i);
                B_lss[2].add(s_lss[0].val() + log_x_i + log_t_i);
            }
        }
        // now compute matrices in normal space
        std::array< std::array< Float_Type, 3 >, 3 > A =
            {{ {{ std::exp(A_lss[0][0].val()), std::exp(A_lss[0][1].val()), std::exp(A_lss[0][2].val()) }},
               {{ std::exp(A_lss[0][1].val()), std::exp(A_lss[1][1].val()), std::exp(A_lss[1][2].val()) }},
               {{ std::exp(A_lss[0][2].val()), std::exp(A_lss[1][2].val()), std::exp(A_lss[2][2].val()) }} }};
        std::array< Float_Type, 3 > B =
            {{ std::exp(B_lss[0].val()), std::exp(B_lss[1].val()), std::exp(B_lss[2].val()) }};
#ifndef NDEBUG
        auto A_copy = A;
        auto B_copy = B;
#endif
        // compute scaling vector used for scaled partial pivoting
        std::array< Float_Type, 3 > C;
        for (unsigned i = 0; i < 3; ++i)
        {
            C[i] = alg::max_value_of(A[i]); // no need for abs(), as A>0
        }
        LOG(debug1)
            << "A={{" << A[0][0] << ", " << A[0][1] << ", " << A[0][2]
            << "}, {" << A[1][0] << ", " << A[1][1] << ", " << A[1][2]
            << "}, {" << A[2][0] << ", " << A[2][1] << ", " << A[2][2]
            << "}} B={" << B[0] << ", " << B[1] << ", " << B[2]
            << "} C={" << C[0] << ", " << C[1] << ", " << C[2] << "}" << std::endl;
        //
        // solve A * X = B using Gaussian elimination with partial pivoting
        //
        for (unsigned i = 0; i < 3; ++i)
        {
            unsigned p = i;
            float p_val = std::abs(A[i][i]) / C[p];
            for (unsigned i2 = i + 1; i2 < 3; ++i2)
            {
                float i2_val = std::abs(A[i2][i]) / C[i2];
                if (i2_val > p_val)
                {
                    p = i2;
                    p_val = i2_val;
                }
            }
            LOG(debug1)
                << "gaussian_elimination i=" << i << " p=" << p << " p_val=" << p_val << std::endl;
            // if the pivot is too small, consider matrix singular, and give up
            if (p_val < 1e-7)
            {
                done = true;
                new_pm_params = crt_pm_params;
                return;
            }
            // if necessary, interchange rows i & p
            if (p > i)
            {
                std::swap(A[i], A[p]);
                std::swap(B[i], B[p]);
                std::swap(C[i], C[p]);
            }
            // eliminate variable i from the last i-1 equations
            for (p = i + 1; p < 3; ++p)
            {
                float m = A[p][i] / A[i][i];
                A[p][i] = 0;
                for (unsigned j = i + 1; j < 3; ++j)
                {
                    A[p][j] -= m * A[i][j];
                }
                B[p] -= m * B[i];
            }
            LOG(debug1)
                << "gaussian_elimination i=" << i
                << " A={{" << A[0][0] << ", " << A[0][1] << ", " << A[0][2]
                << "}, {" << A[1][0] << ", " << A[1][1] << ", " << A[1][2]
                << "}, {" << A[2][0] << ", " << A[2][1] << ", " << A[2][2]
                << "}} B={" << B[0] << ", " << B[1] << ", " << B[2]
                << "} C={" << C[0] << ", " << C[1] << ", " << C[2] << "}" << std::endl;
        }
        // solve the upper triangular system by hand, storing the solutions as the new parameters
        new_pm_params.drift = B[2] / A[2][2];
        new_pm_params.scale = (B[1] - A[1][2] * new_pm_params.drift) / A[1][1];
        new_pm_params.shift = (B[0] - A[0][1] * new_pm_params.scale - A[0][2] * new_pm_params.drift) / A[0][0];
        LOG(debug1)
            << "system_solutions {" << new_pm_params.shift
            << ", " << new_pm_params.scale
            << ", " << new_pm_params.drift << "}" << std::endl;
#ifndef NDEBUG
        // sanity check
        for (unsigned i = 0; i < 3; ++i)
        {
            float x = A_copy[i][0] * new_pm_params.shift
                + A_copy[i][1] * new_pm_params.scale
                + A_copy[i][2] * new_pm_params.drift;
            assert((x - B_copy[i])/std::max(x, B_copy[i]) < 1e-5);
        }
#endif
        // finally, solve for var
        LogSumSet_Type s{false};
#if defined(USE_LOGDIFF)
        float new_pm_params_log_abs_shift = std::log(std::abs(new_pm_params.shift));
        float new_pm_params_log_scale = std::log(new_pm_params.scale);
        float new_pm_params_log_abs_drift = std::log(std::abs(new_pm_params.drift));
#if defined(CHECK_LOGDIFF)
        LogSumSet_Type s2{false};
#endif
#endif
        for (unsigned k = 0; k < n_event_seqs; ++k)
        {
            const Event_Sequence_Type& events = *event_seq_ptrs[k];
            const Pore_Model_Type& pm = *model_ptrs[single_model? 0 : k];
            unsigned n_events = events.size();
            for (unsigned i = 0; i < n_events; ++i)
            {
                for (unsigned j = 0; j < Pore_Model_Type::n_states; ++j)
                {
                    float x = fwbw[k].log_posterior(i, j) - 2 * pm.state(j).log_level_stdv;
#if !defined(USE_LOGDIFF) || defined(CHECK_LOGDIFF)
                    float y =
                        std::log(std::abs(events[i].mean
                                          - new_pm_params.shift
                                          - new_pm_params.scale * pm.state(j).level_mean
                                          - new_pm_params.drift * events[i].start));
#endif
#if defined(USE_LOGDIFF)
                    float a = events[i].log_mean;
                    float b = new_pm_params_log_scale + pm.state(j).log_level_mean;
                    float& shift_contrib = (new_pm_params.shift > 0? b : a);
                    shift_contrib = logsum::p7_FLogsum(shift_contrib, new_pm_params_log_abs_shift);
                    float& drift_contrib = (new_pm_params.drift > 0? b : a);
                    drift_contrib = logsum::p7_FLogsum(drift_contrib, new_pm_params_log_abs_drift + events[i].log_start);
                    float y2 = logdiff::LogDiff(a, b);
                    s.add(x + 2 * y2);
#if defined(CHECK_LOGDIFF)
                    s2.add(x + 2 * y);
#endif
#else
                    s.add(x + 2 * y);
#endif
                }
            }
        }
#if defined(CHECK_LOGDIFF)
        LOG(debug)
            << "logdiff:"
            << " var=" << std::sqrt(std::exp(s.val()) / total_num_events)
            << " var2=" << std::sqrt(std::exp(s2.val()) / total_num_events) << std::endl;
#endif
        new_pm_params.var = std::sqrt(std::exp(s.val()) / total_num_events);
        LOG(debug1)
            << "var_solution " << new_pm_params.var << std::endl;
    } // train_one_round

}; // class Model_Parameter_Trainer

typedef Model_Parameter_Trainer<> Model_Parameter_Trainer_Type;

#endif
<commit_msg>be more lenient when checking matrix system solution<commit_after>#ifndef __MODEL_PARAMETER_TRAINER
#define __MODEL_PARAMETER_TRAINER

#include <array>
#include <vector>
#include <map>

#include "Pore_Model.hpp"
#include "State_Transitions.hpp"
#include "Forward_Backward.hpp"
#include "logsumset.hpp"
#include "logger.hpp"

#if defined(USE_LOGDIFF)
#include "logdiff.hpp"
#endif

template < typename Float_Type = float, unsigned Kmer_Size = 6 >
struct Model_Parameter_Trainer
{
    typedef Kmer< Kmer_Size > Kmer_Type;
    typedef Pore_Model< Float_Type, Kmer_Size > Pore_Model_Type;
    typedef State_Transitions< Float_Type, Kmer_Size > State_Transitions_Type;
    typedef Event< Float_Type > Event_Type;
    typedef Event_Sequence< Float_Type > Event_Sequence_Type;
    typedef Forward_Backward< Float_Type, Kmer_Size > Forward_Backward_Type;
    typedef logsum::logsumset< Float_Type > LogSumSet_Type;

    static void train_one_round(
        const std::vector< const Event_Sequence_Type* >& event_seq_ptrs,
        const std::vector< const Pore_Model_Type* >& model_ptrs,
        const State_Transitions_Type& transitions,
        const Pore_Model_Parameters_Type& crt_pm_params,
        Pore_Model_Parameters_Type& new_pm_params,
        Float_Type& new_fit,
        bool& done)
    {
        // accept either 1 model per sequence, or just 1 model
        assert(model_ptrs.size() == event_seq_ptrs.size() or model_ptrs.size() == 1);
        bool single_model = model_ptrs.size() == 1;
        unsigned n_event_seqs = event_seq_ptrs.size();
        unsigned total_num_events = alg::accumulate(
            event_seq_ptrs, 0u,
            [] (unsigned s, const Event_Sequence_Type* events_ptr) { return s + events_ptr->size(); });
        done = false;
        // apply current scaling parameters, drift correction, and run fwbw
        std::map< const Pore_Model_Type*, Pore_Model_Type > scaled_pm_map;
        for (const auto pm_p : model_ptrs)
        {
            if (scaled_pm_map.count(pm_p)) continue;
            scaled_pm_map.emplace(std::make_pair(pm_p, *pm_p));
            scaled_pm_map[pm_p].scale(crt_pm_params);
        }
        std::vector< Event_Sequence_Type > corrected_event_seqs(n_event_seqs);
        std::vector< Forward_Backward_Type > fwbw(n_event_seqs);
        new_fit = 0;
        for (unsigned k = 0; k < n_event_seqs; ++k)
        {
            const Pore_Model_Type& scaled_pm = scaled_pm_map.at(model_ptrs[single_model? 0 : k]);
            Event_Sequence_Type& corrected_events = corrected_event_seqs[k];
            corrected_events = *event_seq_ptrs[k];
            corrected_events.apply_drift_correction(crt_pm_params.drift);
            fwbw[k].fill(scaled_pm, transitions, corrected_events);
            new_fit += fwbw[k].log_pr_data();
        }
        // compute the scaling matrices (first in logspace)
        // against unscaled pm & uncorrected events
        std::array< std::array< LogSumSet_Type, 3 >, 3 > A_lss =
            {{ {{ false, false, false }},
               {{ false, false, false }},
               {{ false, false, false }} }};
        std::array< LogSumSet_Type, 3 > B_lss = {{ false, false, false }};
        for (unsigned k = 0; k < n_event_seqs; ++k)
        {
            const Event_Sequence_Type& events = *event_seq_ptrs[k];
            const Pore_Model_Type& pm = *model_ptrs[single_model? 0 : k];
            unsigned n_events = events.size();
            for (unsigned i = 0; i < n_events; ++i)
            {
                Float_Type log_x_i = events[i].log_mean;
                Float_Type log_t_i = events[i].log_start;
                LOG(debug1)
                    << "outter_loop k=" << k << " i=" << i
                    << " log_x_i=" << log_x_i
                    << " log_t_i=" << log_t_i << std::endl;
                std::array< LogSumSet_Type, 3 > s_lss = {{ false, false, false }};
                for (unsigned j = 0; j < Pore_Model_Type::n_states; ++j)
                {
                    Float_Type x0 = fwbw[k].log_posterior(i, j) - 2 * pm.state(j).log_level_stdv;
                    Float_Type x1 = x0 + pm.state(j).log_level_mean;
                    Float_Type x2 = x1 + pm.state(j).log_level_mean;
                    LOG(debug2)
                        << "inner_loop k=" << k << " i=" << i << " j=" << j
                        << " x0=" << x0 << " x1=" << x1 << " x2=" << x2 << std::endl;
                    s_lss[0].add(x0);
                    s_lss[1].add(x1);
                    s_lss[2].add(x2);
                }
                A_lss[0][0].add(s_lss[0].val());
                A_lss[0][1].add(s_lss[1].val());
                A_lss[0][2].add(s_lss[0].val() + log_t_i);
                A_lss[1][1].add(s_lss[2].val());
                A_lss[1][2].add(s_lss[1].val() + log_t_i);
                A_lss[2][2].add(s_lss[0].val() + 2 * log_t_i);
                B_lss[0].add(s_lss[0].val() + log_x_i);
                B_lss[1].add(s_lss[1].val() + log_x_i);
                B_lss[2].add(s_lss[0].val() + log_x_i + log_t_i);
            }
        }
        // now compute matrices in normal space
        std::array< std::array< Float_Type, 3 >, 3 > A =
            {{ {{ std::exp(A_lss[0][0].val()), std::exp(A_lss[0][1].val()), std::exp(A_lss[0][2].val()) }},
               {{ std::exp(A_lss[0][1].val()), std::exp(A_lss[1][1].val()), std::exp(A_lss[1][2].val()) }},
               {{ std::exp(A_lss[0][2].val()), std::exp(A_lss[1][2].val()), std::exp(A_lss[2][2].val()) }} }};
        std::array< Float_Type, 3 > B =
            {{ std::exp(B_lss[0].val()), std::exp(B_lss[1].val()), std::exp(B_lss[2].val()) }};
#ifndef NDEBUG
        auto A_copy = A;
        auto B_copy = B;
#endif
        // compute scaling vector used for scaled partial pivoting
        std::array< Float_Type, 3 > C;
        for (unsigned i = 0; i < 3; ++i)
        {
            C[i] = alg::max_value_of(A[i]); // no need for abs(), as A>0
        }
        LOG(debug1)
            << "A={{" << A[0][0] << ", " << A[0][1] << ", " << A[0][2]
            << "}, {" << A[1][0] << ", " << A[1][1] << ", " << A[1][2]
            << "}, {" << A[2][0] << ", " << A[2][1] << ", " << A[2][2]
            << "}} B={" << B[0] << ", " << B[1] << ", " << B[2]
            << "} C={" << C[0] << ", " << C[1] << ", " << C[2] << "}" << std::endl;
        //
        // solve A * X = B using Gaussian elimination with partial pivoting
        //
        for (unsigned i = 0; i < 3; ++i)
        {
            unsigned p = i;
            float p_val = std::abs(A[i][i]) / C[p];
            for (unsigned i2 = i + 1; i2 < 3; ++i2)
            {
                float i2_val = std::abs(A[i2][i]) / C[i2];
                if (i2_val > p_val)
                {
                    p = i2;
                    p_val = i2_val;
                }
            }
            LOG(debug1)
                << "gaussian_elimination i=" << i << " p=" << p << " p_val=" << p_val << std::endl;
            // if the pivot is too small, consider matrix singular, and give up
            if (p_val < 1e-7)
            {
                done = true;
                new_pm_params = crt_pm_params;
                return;
            }
            // if necessary, interchange rows i & p
            if (p > i)
            {
                std::swap(A[i], A[p]);
                std::swap(B[i], B[p]);
                std::swap(C[i], C[p]);
            }
            // eliminate variable i from the last i-1 equations
            for (p = i + 1; p < 3; ++p)
            {
                float m = A[p][i] / A[i][i];
                A[p][i] = 0;
                for (unsigned j = i + 1; j < 3; ++j)
                {
                    A[p][j] -= m * A[i][j];
                }
                B[p] -= m * B[i];
            }
            LOG(debug1)
                << "gaussian_elimination i=" << i
                << " A={{" << A[0][0] << ", " << A[0][1] << ", " << A[0][2]
                << "}, {" << A[1][0] << ", " << A[1][1] << ", " << A[1][2]
                << "}, {" << A[2][0] << ", " << A[2][1] << ", " << A[2][2]
                << "}} B={" << B[0] << ", " << B[1] << ", " << B[2]
                << "} C={" << C[0] << ", " << C[1] << ", " << C[2] << "}" << std::endl;
        }
        // solve the upper triangular system by hand, storing the solutions as the new parameters
        new_pm_params.drift = B[2] / A[2][2];
        new_pm_params.scale = (B[1] - A[1][2] * new_pm_params.drift) / A[1][1];
        new_pm_params.shift = (B[0] - A[0][1] * new_pm_params.scale - A[0][2] * new_pm_params.drift) / A[0][0];
        LOG(debug1)
            << "system_solutions {" << new_pm_params.shift
            << ", " << new_pm_params.scale
            << ", " << new_pm_params.drift << "}" << std::endl;
#ifndef NDEBUG
        // sanity check
        for (unsigned i = 0; i < 3; ++i)
        {
            float x = A_copy[i][0] * new_pm_params.shift
                + A_copy[i][1] * new_pm_params.scale
                + A_copy[i][2] * new_pm_params.drift;
            assert((x - B_copy[i])/std::max(x, B_copy[i]) < 1e-3);
        }
#endif
        // finally, solve for var
        LogSumSet_Type s{false};
#if defined(USE_LOGDIFF)
        float new_pm_params_log_abs_shift = std::log(std::abs(new_pm_params.shift));
        float new_pm_params_log_scale = std::log(new_pm_params.scale);
        float new_pm_params_log_abs_drift = std::log(std::abs(new_pm_params.drift));
#if defined(CHECK_LOGDIFF)
        LogSumSet_Type s2{false};
#endif
#endif
        for (unsigned k = 0; k < n_event_seqs; ++k)
        {
            const Event_Sequence_Type& events = *event_seq_ptrs[k];
            const Pore_Model_Type& pm = *model_ptrs[single_model? 0 : k];
            unsigned n_events = events.size();
            for (unsigned i = 0; i < n_events; ++i)
            {
                for (unsigned j = 0; j < Pore_Model_Type::n_states; ++j)
                {
                    float x = fwbw[k].log_posterior(i, j) - 2 * pm.state(j).log_level_stdv;
#if !defined(USE_LOGDIFF) || defined(CHECK_LOGDIFF)
                    float y =
                        std::log(std::abs(events[i].mean
                                          - new_pm_params.shift
                                          - new_pm_params.scale * pm.state(j).level_mean
                                          - new_pm_params.drift * events[i].start));
#endif
#if defined(USE_LOGDIFF)
                    float a = events[i].log_mean;
                    float b = new_pm_params_log_scale + pm.state(j).log_level_mean;
                    float& shift_contrib = (new_pm_params.shift > 0? b : a);
                    shift_contrib = logsum::p7_FLogsum(shift_contrib, new_pm_params_log_abs_shift);
                    float& drift_contrib = (new_pm_params.drift > 0? b : a);
                    drift_contrib = logsum::p7_FLogsum(drift_contrib, new_pm_params_log_abs_drift + events[i].log_start);
                    float y2 = logdiff::LogDiff(a, b);
                    s.add(x + 2 * y2);
#if defined(CHECK_LOGDIFF)
                    s2.add(x + 2 * y);
#endif
#else
                    s.add(x + 2 * y);
#endif
                }
            }
        }
#if defined(CHECK_LOGDIFF)
        LOG(debug)
            << "logdiff:"
            << " var=" << std::sqrt(std::exp(s.val()) / total_num_events)
            << " var2=" << std::sqrt(std::exp(s2.val()) / total_num_events) << std::endl;
#endif
        new_pm_params.var = std::sqrt(std::exp(s.val()) / total_num_events);
        LOG(debug1)
            << "var_solution " << new_pm_params.var << std::endl;
    } // train_one_round

}; // class Model_Parameter_Trainer

typedef Model_Parameter_Trainer<> Model_Parameter_Trainer_Type;

#endif
<|endoftext|>


<commit_before>/*
 * DISTRHO Plugin Framework (DPF)
 * Copyright (C) 2012-2019 Filipe Coelho <falktx@falktx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with
 * or without fee is hereby granted, provided that the above copyright notice and this
 * permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
 * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "../Base.hpp"

START_NAMESPACE_DGL

// -----------------------------------------------------------------------

// nothing here yet

// -----------------------------------------------------------------------

END_NAMESPACE_DGL
<commit_msg>cairo: define geometry functions, fixes debug link<commit_after>/*
 * DISTRHO Plugin Framework (DPF)
 * Copyright (C) 2012-2019 Filipe Coelho <falktx@falktx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with
 * or without fee is hereby granted, provided that the above copyright notice and this
 * permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
 * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "../Geometry.hpp"
#include "../Cairo.hpp"

START_NAMESPACE_DGL

// -----------------------------------------------------------------------

static void notImplemented(const char *name)
{
    d_stderr2("cairo function not implemented: %s", name);
}

// -----------------------------------------------------------------------
// Line

template<typename T>
void Line<T>::draw()
{
    notImplemented("Line::draw");
}

// -----------------------------------------------------------------------
// Circle

template<typename T>
void Circle<T>::_draw(const bool outline)
{
    notImplemented("Circle::draw");
}

// -----------------------------------------------------------------------
// Triangle

template<typename T>
void Triangle<T>::_draw(const bool outline)
{
    notImplemented("Triangle::draw");
}

// -----------------------------------------------------------------------
// Rectangle

template<typename T>
void Rectangle<T>::_draw(const bool outline)
{
    notImplemented("Rectangle::draw");
}

// -----------------------------------------------------------------------
// Possible template data types

template class Point<double>;
template class Point<float>;
template class Point<int>;
template class Point<uint>;
template class Point<short>;
template class Point<ushort>;

template class Size<double>;
template class Size<float>;
template class Size<int>;
template class Size<uint>;
template class Size<short>;
template class Size<ushort>;

template class Line<double>;
template class Line<float>;
template class Line<int>;
template class Line<uint>;
template class Line<short>;
template class Line<ushort>;

template class Circle<double>;
template class Circle<float>;
template class Circle<int>;
template class Circle<uint>;
template class Circle<short>;
template class Circle<ushort>;

template class Triangle<double>;
template class Triangle<float>;
template class Triangle<int>;
template class Triangle<uint>;
template class Triangle<short>;
template class Triangle<ushort>;

template class Rectangle<double>;
template class Rectangle<float>;
template class Rectangle<int>;
template class Rectangle<uint>;
template class Rectangle<short>;
template class Rectangle<ushort>;

// -----------------------------------------------------------------------

END_NAMESPACE_DGL
<|endoftext|>


<commit_before>// This file is part of the HörTech Open Master Hearing Aid (openMHA)
// Copyright © 2005 2006 2007 2009 2010 2013 2014 2015 2017 2018 HörTech gGmbH
//
// openMHA is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// openMHA is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License, version 3 for more details.
//
// You should have received a copy of the GNU Affero General Public License,
// version 3 along with openMHA.  If not, see <http://www.gnu.org/licenses/>.

#include "mha_plugin.hh"

class save_wave_t : public MHAPlugin::plugin_t<MHA_AC::waveform_t> {
public:
    save_wave_t(const algo_comm_t& iac,
                const std::string& ith,
                const std::string& ial)
        : MHAPlugin::plugin_t<MHA_AC::waveform_t>("Save signal waveform to AC variable",iac),
          basename(ial){};
    mha_wave_t* process(mha_wave_t* s)
    {
        cfg->copy(*s);
        return s;
    };
    void prepare(mhaconfig_t& tf)
    {
        if( tf.domain != MHA_WAVEFORM )
            throw MHA_ErrorMsg("save_wave: Only waveform processing is supported.");
        push_config(new MHA_AC::waveform_t(ac,basename,tf.fragsize,tf.channels,false));
        poll_config();
        cfg->insert();
    }
private:
    std::string basename;
};

MHAPLUGIN_CALLBACKS(save_wave,save_wave_t,wave,wave)
MHAPLUGIN_DOCUMENTATION\
(save_wave,
 "data-flow algorithm-communication",
 "This plugin saves the waveform signal to an AC variable. The name of the variable is the same as the name of the plugin\n"
 "and can be changed by assigning an alias to the plugin with the usual plugin_name:alias_name syntax.")

// Local Variables:
// compile-command: "make"
// c-basic-offset: 4
// indent-tabs-mode: nil
// coding: utf-8-unix
// End:
<commit_msg>Revert "ac_wave: Improve save_wave documentation. Closes T84."<commit_after>// This file is part of the HörTech Open Master Hearing Aid (openMHA)
// Copyright © 2005 2006 2007 2009 2010 2013 2014 2015 2017 2018 HörTech gGmbH
//
// openMHA is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// openMHA is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License, version 3 for more details.
//
// You should have received a copy of the GNU Affero General Public License,
// version 3 along with openMHA.  If not, see <http://www.gnu.org/licenses/>.

#include "mha_plugin.hh"

class save_wave_t : public MHAPlugin::plugin_t<MHA_AC::waveform_t> {
public:
    save_wave_t(const algo_comm_t& iac,
                const std::string& ith,
                const std::string& ial)
        : MHAPlugin::plugin_t<MHA_AC::waveform_t>("Save signal waveform to AC variable",iac),
          basename(ial){};
    mha_wave_t* process(mha_wave_t* s)
    {
        cfg->copy(*s);
        return s;
    };
    void prepare(mhaconfig_t& tf)
    {
        if( tf.domain != MHA_WAVEFORM )
            throw MHA_ErrorMsg("save_wave: Only waveform processing is supported.");
        push_config(new MHA_AC::waveform_t(ac,basename,tf.fragsize,tf.channels,false));
        poll_config();
        cfg->insert();
    }
private:
    std::string basename;
};

MHAPLUGIN_CALLBACKS(save_wave,save_wave_t,wave,wave)
MHAPLUGIN_DOCUMENTATION\
(save_wave,
 "data-flow algorithm-communication",
 "")

// Local Variables:
// compile-command: "make"
// c-basic-offset: 4
// indent-tabs-mode: nil
// coding: utf-8-unix
// End:
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -std=c++11 -debug-info-kind=limited -S -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -std=c++11 -debug-info-kind=line-tables-only -S -emit-llvm %s -o - | FileCheck -check-prefix=CHECK-GMLT %s
// RUN: %clang_cc1 -std=c++11 -debug-info-kind=standalone -S -emit-llvm %s -o - | FileCheck -check-prefix=CHECK-NOLIMIT %s

namespace A {
#line 1 "foo.cpp"
namespace B {
extern int i;
int f1() { return 0; }
void f1(int) { }
struct foo;
struct bar { };
typedef bar baz;
extern int var_decl;
void func_decl(void);
extern int var_fwd;
void func_fwd(void);
}
}
namespace A {
using namespace B;
}

using namespace A;
namespace E = A;
int B::i = f1();
int func(bool b) {
  if (b) {
    using namespace A::B;
    return i;
  }
  using namespace A;
  using B::foo;
  using B::bar;
  using B::f1;
  using B::i;
  using B::baz;
  namespace X = A;
  namespace Y = X;
  using B::var_decl;
  using B::func_decl;
  using B::var_fwd;
  using B::func_fwd;
  return i + X::B::i + Y::B::i;
}

namespace A {
using B::i;
namespace B {
int var_fwd = i;
}
inline namespace I {
int var_i;
}
}
namespace {
int anonymous;
}
void B::func_fwd() {
  anonymous = 0;
}

// This should work even if 'i' and 'func' were declarations & not definitions,
// but it doesn't yet.

// CHECK: [[I:![0-9]+]] = distinct !DIGlobalVariable(name: "i",{{.*}} scope: [[NS:![0-9]+]],
// CHECK: [[NS]] = !DINamespace(name: "B", scope: [[CTXT:![0-9]+]])
// CHECK: [[CTXT]] = !DINamespace(name: "A", scope: null)
// CHECK: [[FOOCPP:.*]] = !DIFile(filename: "foo.cpp"
// CHECK: [[VAR_FWD:![0-9]+]] = distinct !DIGlobalVariable(name: "var_fwd",{{.*}} scope: [[NS]],
// CHECK-SAME:                                             line: 44
// CHECK-SAME:                                             isDefinition: true
// CHECK: distinct !DIGlobalVariable(name: "var_i",{{.*}} scope: [[INLINE:![0-9]+]],
// CHECK: [[INLINE]] = !DINamespace(name: "I", scope: [[CTXT]], exportSymbols: true)
// CHECK: !DINamespace(scope: null)
// CHECK: [[CU:![0-9]+]] = distinct !DICompileUnit(
// CHECK-SAME:                            imports: [[MODULES:![0-9]*]]
// CHECK: [[MODULES]] = !{[[M1:![0-9]+]], [[M2:![0-9]+]], [[M3:![0-9]+]], [[M4:![0-9]+]], [[M5:![0-9]+]], [[M6:![0-9]+]], [[M7:![0-9]+]], [[M8:![0-9]+]], [[M9:![0-9]+]], [[M10:![0-9]+]], [[M11:![0-9]+]], [[M12:![0-9]+]], [[M13:![0-9]+]], [[M14:![0-9]+]], [[M15:![0-9]+]], [[M16:![0-9]+]], [[M17:![0-9]+]]}
// CHECK: [[M1]] = !DIImportedEntity(tag: DW_TAG_imported_module, scope: [[CTXT]], entity: [[NS]], line: 15)

// CHECK: [[M2]] = !DIImportedEntity(tag: DW_TAG_imported_module, scope: [[CU]], entity: [[CTXT]],
// CHECK: [[M3]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, name: "E", scope: [[CU]], entity: [[CTXT]], line: 19)
// CHECK: [[M4]] = !DIImportedEntity(tag: DW_TAG_imported_module, scope: [[LEX2:![0-9]+]], entity: [[NS]], line: 23)
// CHECK: [[LEX2]] = distinct !DILexicalBlock(scope: [[LEX1:![0-9]+]], file: [[FOOCPP]],
// CHECK: [[LEX1]] = distinct !DILexicalBlock(scope: [[FUNC:![0-9]+]], file: [[FOOCPP]],

// CHECK: [[FUNC:![0-9]+]] = distinct !DISubprogram(name: "func",{{.*}} isDefinition: true
// CHECK: [[M5]] = !DIImportedEntity(tag: DW_TAG_imported_module, scope: [[FUNC]], entity: [[CTXT:![0-9]+]],
// CHECK: [[M6]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[FOO:![0-9]+]], line: 27)
// CHECK: [[FOO]] = !DICompositeType(tag: DW_TAG_structure_type, name: "foo",
// CHECK-SAME:                               line: 5
// CHECK-SAME:                               DIFlagFwdDecl
// CHECK: [[M7]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[BAR:![0-9]+]]
// CHECK: [[BAR]] = !DICompositeType(tag: DW_TAG_structure_type, name: "bar",
// CHECK-SAME:                               line: 6
// CHECK-SAME:                               DIFlagFwdDecl

// CHECK: [[M8]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[F1:![0-9]+]]
// CHECK: [[F1:![0-9]+]] = distinct !DISubprogram(name: "f1",{{.*}} line: 4
// CHECK-SAME:                           isDefinition: true
// CHECK: [[M9]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[I]]
// CHECK: [[M10]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[BAZ:![0-9]+]]
// CHECK: [[BAZ]] = !DIDerivedType(tag: DW_TAG_typedef, name: "baz", scope: [[NS]], file: [[FOOCPP]],
// CHECK-SAME:                     baseType: [[BAR]]
// CHECK: [[M11]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, name: "X", scope: [[FUNC]], entity: [[CTXT]]
// CHECK: [[M12]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, name: "Y", scope: [[FUNC]], entity: [[M11]]
// CHECK: [[M13]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[VAR_DECL:![0-9]+]]
// CHECK: [[VAR_DECL]] = !DIGlobalVariable(name: "var_decl", linkageName: "{{[^"]*var_decl[^"]*}}", scope: [[NS]],{{.*}} line: 8,
// CHECK: [[M14]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[FUNC_DECL:![0-9]+]]
// CHECK: [[FUNC_DECL]] = !DISubprogram(name: "func_decl",
// CHECK-SAME:                          scope: [[NS]], file: [[FOOCPP]], line: 9
// CHECK: [[M15]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[VAR_FWD:![0-9]+]]
// CHECK: [[M16]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[FUNC_FWD:![0-9]+]]
// CHECK: [[FUNC_FWD]] = distinct !DISubprogram(name: "func_fwd",{{.*}} line: 53,{{.*}} isDefinition: true
// CHECK: [[M17]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[CTXT]], entity: [[I]]

// CHECK-GMLT: [[CU:![0-9]+]] = distinct !DICompileUnit(
// CHECK-GMLT-SAME:                            emissionKind: LineTablesOnly,
// CHECK-GMLT-NOT:                             imports:

// CHECK-NOLIMIT: !DICompositeType(tag: DW_TAG_structure_type, name: "bar",{{.*}} line: 6,
// CHECK-NOLIMIT-NOT:              DIFlagFwdDecl
// CHECK-NOLIMIT-SAME:             ){{$}}
<commit_msg>Relax testcase to fix a PS4 buildbot failure.<commit_after>// RUN: %clang_cc1 -std=c++11 -debug-info-kind=limited -S -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -std=c++11 -debug-info-kind=line-tables-only -S -emit-llvm %s -o - | FileCheck -check-prefix=CHECK-GMLT %s
// RUN: %clang_cc1 -std=c++11 -debug-info-kind=standalone -S -emit-llvm %s -o - | FileCheck -check-prefix=CHECK-NOLIMIT %s

namespace A {
#line 1 "foo.cpp"
namespace B {
extern int i;
int f1() { return 0; }
void f1(int) { }
struct foo;
struct bar { };
typedef bar baz;
extern int var_decl;
void func_decl(void);
extern int var_fwd;
void func_fwd(void);
}
}
namespace A {
using namespace B;
}

using namespace A;
namespace E = A;
int B::i = f1();
int func(bool b) {
  if (b) {
    using namespace A::B;
    return i;
  }
  using namespace A;
  using B::foo;
  using B::bar;
  using B::f1;
  using B::i;
  using B::baz;
  namespace X = A;
  namespace Y = X;
  using B::var_decl;
  using B::func_decl;
  using B::var_fwd;
  using B::func_fwd;
  return i + X::B::i + Y::B::i;
}

namespace A {
using B::i;
namespace B {
int var_fwd = i;
}
inline namespace I {
int var_i;
}
}
namespace {
int anonymous;
}
void B::func_fwd() {
  anonymous = 0;
}

// This should work even if 'i' and 'func' were declarations & not definitions,
// but it doesn't yet.

// CHECK: [[I:![0-9]+]] = distinct !DIGlobalVariable(name: "i",{{.*}} scope: [[NS:![0-9]+]],
// CHECK: [[NS]] = !DINamespace(name: "B", scope: [[CTXT:![0-9]+]])
// CHECK: [[CTXT]] = !DINamespace(name: "A", scope: null)
// CHECK: [[FOOCPP:.*]] = !DIFile(filename: "foo.cpp"
// CHECK: [[VAR_FWD:![0-9]+]] = distinct !DIGlobalVariable(name: "var_fwd",{{.*}} scope: [[NS]],
// CHECK-SAME:                                             line: 44
// CHECK-SAME:                                             isDefinition: true
// CHECK: distinct !DIGlobalVariable(name: "var_i",{{.*}} scope: [[INLINE:![0-9]+]],
// CHECK: [[INLINE]] = !DINamespace(name: "I", scope: [[CTXT]], exportSymbols: true)
// CHECK: !DINamespace(scope: null)
// CHECK: [[CU:![0-9]+]] = distinct !DICompileUnit(
// CHECK-SAME:                            imports: [[MODULES:![0-9]*]]
// CHECK: [[MODULES]] = !{[[M1:![0-9]+]], [[M2:![0-9]+]], [[M3:![0-9]+]], [[M4:![0-9]+]], [[M5:![0-9]+]], [[M6:![0-9]+]], [[M7:![0-9]+]], [[M8:![0-9]+]], [[M9:![0-9]+]], [[M10:![0-9]+]], [[M11:![0-9]+]], [[M12:![0-9]+]], [[M13:![0-9]+]], [[M14:![0-9]+]], [[M15:![0-9]+]], [[M16:![0-9]+]], [[M17:![0-9]+]]
// CHECK: [[M1]] = !DIImportedEntity(tag: DW_TAG_imported_module, scope: [[CTXT]], entity: [[NS]], line: 15)

// CHECK: [[M2]] = !DIImportedEntity(tag: DW_TAG_imported_module, scope: [[CU]], entity: [[CTXT]],
// CHECK: [[M3]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, name: "E", scope: [[CU]], entity: [[CTXT]], line: 19)
// CHECK: [[M4]] = !DIImportedEntity(tag: DW_TAG_imported_module, scope: [[LEX2:![0-9]+]], entity: [[NS]], line: 23)
// CHECK: [[LEX2]] = distinct !DILexicalBlock(scope: [[LEX1:![0-9]+]], file: [[FOOCPP]],
// CHECK: [[LEX1]] = distinct !DILexicalBlock(scope: [[FUNC:![0-9]+]], file: [[FOOCPP]],

// CHECK: [[FUNC:![0-9]+]] = distinct !DISubprogram(name: "func",{{.*}} isDefinition: true
// CHECK: [[M5]] = !DIImportedEntity(tag: DW_TAG_imported_module, scope: [[FUNC]], entity: [[CTXT:![0-9]+]],
// CHECK: [[M6]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[FOO:![0-9]+]], line: 27)
// CHECK: [[FOO]] = !DICompositeType(tag: DW_TAG_structure_type, name: "foo",
// CHECK-SAME:                               line: 5
// CHECK-SAME:                               DIFlagFwdDecl
// CHECK: [[M7]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[BAR:![0-9]+]]
// CHECK: [[BAR]] = !DICompositeType(tag: DW_TAG_structure_type, name: "bar",
// CHECK-SAME:                               line: 6
// CHECK-SAME:                               DIFlagFwdDecl

// CHECK: [[M8]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[F1:![0-9]+]]
// CHECK: [[F1:![0-9]+]] = distinct !DISubprogram(name: "f1",{{.*}} line: 4
// CHECK-SAME:                           isDefinition: true
// CHECK: [[M9]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[I]]
// CHECK: [[M10]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[BAZ:![0-9]+]]
// CHECK: [[BAZ]] = !DIDerivedType(tag: DW_TAG_typedef, name: "baz", scope: [[NS]], file: [[FOOCPP]],
// CHECK-SAME:                     baseType: [[BAR]]
// CHECK: [[M11]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, name: "X", scope: [[FUNC]], entity: [[CTXT]]
// CHECK: [[M12]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, name: "Y", scope: [[FUNC]], entity: [[M11]]
// CHECK: [[M13]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[VAR_DECL:![0-9]+]]
// CHECK: [[VAR_DECL]] = !DIGlobalVariable(name: "var_decl", linkageName: "{{[^"]*var_decl[^"]*}}", scope: [[NS]],{{.*}} line: 8,
// CHECK: [[M14]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[FUNC_DECL:![0-9]+]]
// CHECK: [[FUNC_DECL]] = !DISubprogram(name: "func_decl",
// CHECK-SAME:                          scope: [[NS]], file: [[FOOCPP]], line: 9
// CHECK: [[M15]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[VAR_FWD:![0-9]+]]
// CHECK: [[M16]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[FUNC]], entity: [[FUNC_FWD:![0-9]+]]
// CHECK: [[FUNC_FWD]] = distinct !DISubprogram(name: "func_fwd",{{.*}} line: 53,{{.*}} isDefinition: true
// CHECK: [[M17]] = !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: [[CTXT]], entity: [[I]]

// CHECK-GMLT: [[CU:![0-9]+]] = distinct !DICompileUnit(
// CHECK-GMLT-SAME:                            emissionKind: LineTablesOnly,
// CHECK-GMLT-NOT:                             imports:

// CHECK-NOLIMIT: !DICompositeType(tag: DW_TAG_structure_type, name: "bar",{{.*}} line: 6,
// CHECK-NOLIMIT-NOT:              DIFlagFwdDecl
// CHECK-NOLIMIT-SAME:             ){{$}}
<|endoftext|>


<commit_before>/* -*- C++ -*- */
/*************************************************************************
 * Copyright(c) 1995~2005  Masaharu Goto (cint@pcroot.cern.ch)
 *
 * For the licensing terms see the file COPYING
 *
 ************************************************************************/
//
// cint test of global function template
//
#include <stdio.h>

#if (defined(G__MSC_VER)&&(G__MSC_VER<=1200)) || (defined(_MSC_VER)&&(_MSC_VER<=1200))
#else
#define TEST
#endif

///////////////////////////////////////////////////////////////////////
// test3
///////////////////////////////////////////////////////////////////////
template<class T> class B {
 public:
  B(T in=0) { b = in; }
  T b;
};

template<class T> int compare3(B<T> a,B<T> b) {
  return(a.b==b.b);
}

void test3()
{
  int i;
  B<float> b1,b2(0.02);
  for(i=0;i<5;i++) {
    b1.b = i/100.0;
    printf("%d=compare3(%g,%g)\n",compare3(b1,b2),b1.b,b2.b);
  }
}

///////////////////////////////////////////////////////////////////////
// test1
///////////////////////////////////////////////////////////////////////
template<class T> int compare(T a,T b) {
  if(a==b) return(1);
  else     return(0);
}

class A {
 public:
  A(int in=0) { a = in ; }
  int a;
};

int operator==(A a,A b) {
  return(a.a==b.a);
}

void test1()
{
  int i;
  int i1,i2=2;
  double d1,d2=0.2;
  A a1,a2(20);

  for(i=0;i<5;i++) {
    i1=i;
    d1 = i/10.0;
    a1.a=i*10;
    //printf("%d=compare(%d,%d)  %d=compare(%g,%g)\n"
	   //,compare(i1,i2),i1,i2 ,compare(d1,d2),d1,d2);
    printf("%d=compare(%d,%d)  %d=compare(%g,%g) %d=compare(%d,%d)\n"
	   ,compare(i1,i2),i1,i2 ,compare(d1,d2),d1,d2
	   ,compare(a1,a2),a1.a,a2.a);
  }
}

///////////////////////////////////////////////////////////////////////
// test2
///////////////////////////////////////////////////////////////////////
template<class T,class E> int compare2(T a,E b) {
  if(a==b) return(1);
  else     return(0);
}

void test2()
{
  int i;
  A a(2);
  for(i=0;i<5;i++) {
    printf("%d=compare2(%d,%d)\n",compare2(i,a),i,a.a);
  }
  for(i=0;i<5;i++) {
    printf("%d=compare2(%d,%d)\n",compare2(a,i),a.a,i);
  }
}

///////////////////////////////////////////////////////////////////////
// test4
///////////////////////////////////////////////////////////////////////
#ifdef TEST
template<class T,template<class U> class E> int cmp(E<T> a,E<T> b) {
  return(a.b==b.b);
}
#endif

void test4()
{
#ifdef TEST
  int i;
  B<short> b1,b2(200);
  for(i=0;i<5;i++) {
    b1.b = i*100;
    printf("%d=cmp(%d,%d)\n",cmp(b1,b2),b1.b,b2.b);
  }
#endif
}

///////////////////////////////////////////////////////////////////////
// test5
///////////////////////////////////////////////////////////////////////
template<size_t SIZE,class T> class ary {
 public:
  ary() { size = SIZE; }
  T a[SIZE];
  size_t size;
};

const size_t sz=5;

void test5()
{
  ary<sz,B<int> > a;
  printf("a.size=%d\n",a.size);
}

///////////////////////////////////////////////////////////////////////
// main
///////////////////////////////////////////////////////////////////////
int main()
{
  test5();
  test4();
  test3();
  test2();
  test1();
  return 0;
}
<commit_msg>improve platform independence of test<commit_after>/* -*- C++ -*- */
/*************************************************************************
 * Copyright(c) 1995~2005  Masaharu Goto (cint@pcroot.cern.ch)
 *
 * For the licensing terms see the file COPYING
 *
 ************************************************************************/
//
// cint test of global function template
//
#include <stdio.h>

#if (defined(G__MSC_VER)&&(G__MSC_VER<=1200)) || (defined(_MSC_VER)&&(_MSC_VER<=1200))
#else
#define TEST
#endif

///////////////////////////////////////////////////////////////////////
// test3
///////////////////////////////////////////////////////////////////////
template<class T> class B {
 public:
  B(T in=0) { b = in; }
  T b;
};

template<class T> int compare3(B<T> a,B<T> b) {
   return( a.b==0 ? a.b==b.b : (((a.b-b.b)/a.b) < 1e-4) );
}

void test3()
{
  int i;
  B<float> b1,b2(0.02);
  for(i=0;i<5;i++) {
    b1.b = i/100.0;
    printf("%d=compare3(%g,%g)\n",compare3(b1,b2),b1.b,b2.b);
  }
}

///////////////////////////////////////////////////////////////////////
// test1
///////////////////////////////////////////////////////////////////////
template<class T> int compare(T a,T b) {
  if(a==b) return(1);
  else     return(0);
}

class A {
 public:
  A(int in=0) { a = in ; }
  int a;
};

int operator==(A a,A b) {
   return( a.a==0 ? a.a==b.a : (((a.a-b.a)/a.a)<1e-4));
}

void test1()
{
  int i;
  int i1,i2=2;
  double d1,d2=0.2;
  A a1,a2(20);

  for(i=0;i<5;i++) {
    i1=i;
    d1 = i/10.0;
    a1.a=i*10;
    //printf("%d=compare(%d,%d)  %d=compare(%g,%g)\n"
	   //,compare(i1,i2),i1,i2 ,compare(d1,d2),d1,d2);
    printf("%d=compare(%d,%d)  %d=compare(%g,%g) %d=compare(%d,%d)\n"
	   ,compare(i1,i2),i1,i2 ,compare(d1,d2),d1,d2
	   ,compare(a1,a2),a1.a,a2.a);
  }
}

///////////////////////////////////////////////////////////////////////
// test2
///////////////////////////////////////////////////////////////////////
template<class T,class E> int compare2(T a,E b) {
  if(a==b) return(1);
  else     return(0);
}

void test2()
{
  int i;
  A a(2);
  for(i=0;i<5;i++) {
    printf("%d=compare2(%d,%d)\n",compare2(i,a),i,a.a);
  }
  for(i=0;i<5;i++) {
    printf("%d=compare2(%d,%d)\n",compare2(a,i),a.a,i);
  }
}

///////////////////////////////////////////////////////////////////////
// test4
///////////////////////////////////////////////////////////////////////
#ifdef TEST
template<class T,template<class U> class E> int cmp(E<T> a,E<T> b) {
  return(a.b==b.b);
}
#endif

void test4()
{
#ifdef TEST
  int i;
  B<short> b1,b2(200);
  for(i=0;i<5;i++) {
    b1.b = i*100;
    printf("%d=cmp(%d,%d)\n",cmp(b1,b2),b1.b,b2.b);
  }
#endif
}

///////////////////////////////////////////////////////////////////////
// test5
///////////////////////////////////////////////////////////////////////
template<size_t SIZE,class T> class ary {
 public:
  ary() { size = SIZE; }
  T a[SIZE];
  size_t size;
};

const size_t sz=5;

void test5()
{
  ary<sz,B<int> > a;
  printf("a.size=%d\n",a.size);
}

///////////////////////////////////////////////////////////////////////
// main
///////////////////////////////////////////////////////////////////////
int main()
{
  test5();
  test4();
  test3();
  test2();
  test1();
  return 0;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace cv;

int main(int argc, char **argv){
	printf("Lege template voor labo beeldverwerking: %s\n",argv[0]);

	return 0;
}
<commit_msg>Oef 13!<commit_after>#include <cstdio>
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/features2d/features2d.hpp"

using namespace cv;

const int min_feat = 32;
const int max_feat = 48;

void fast_feat(Mat img, std::vector<KeyPoint>& keypoints)
{
    int nrfound = 0;
    int threshold = 50;

    while(nrfound<min_feat || nrfound>max_feat)
    {
      FastFeatureDetector detector(threshold, true);
      detector.detect(img, keypoints);
      nrfound = keypoints.size();
      if (nrfound < min_feat)
          threshold -= 5;
      else if (nrfound > max_feat)
          threshold += 5;
    }
    //std::cout << "# FAST features:" << nrfound << std::endl;
}

void labo13(const char* file1, const char* file2)
{
    Mat img1 = imread(file1);
    Mat img2 = imread(file2);
    Mat grey1;
    Mat grey2;
    cvtColor(img1, grey1, CV_RGB2GRAY);
    cvtColor(img2, grey2, CV_RGB2GRAY);

    //find FAST features
    std::vector<KeyPoint> keypoints1;
    fast_feat(grey1, keypoints1);
    std::vector<KeyPoint> keypoints2;
    fast_feat(grey2, keypoints2);

    // make BRIEF descriptors
    BriefDescriptorExtractor extractor(32);
    Mat descriptors1, descriptors2;
    extractor.compute(grey1, keypoints1, descriptors1);
    extractor.compute(grey2, keypoints2, descriptors2);

    // find closest matches between descriptors
    BFMatcher matcher(NORM_HAMMING, false);
    vector<DMatch> matches;
    matcher.match(descriptors1, descriptors2, matches);

    // draw matches
    Mat out;
    cv::drawMatches(img1, keypoints1, img2, keypoints2, matches, out);

    imshow("matches", out);
    waitKey();
}

int main(int argc, char **argv)
{
    printf("labo beeldverwerking - opdracht 13\n");

    if (argc == 3)
    {
        printf("Opening:\n file1: %s\n file2: %s\n", argv[1], argv[2]);

        try
        {
            labo13(argv[1], argv[2]);
        }
        catch (...)
        {
            printf("Something fucked up\n");
            return 1;
        }
    }
    else
    {
        printf("usage: %s <image>\n",argv[0]);
    }

    return 0;
}
<|endoftext|>


<commit_before>//MIT License
//Copyright(c) 2017 Patrick Laughrea
#include "parser.h"

#include "containerSwitcher.h"
#include "errors.h"
#include "paramDocumentIncluder.h"
#include "patternsContainers.h"
#include "utils/utilsWebss.h"

using namespace std;
using namespace webss;

const char ERROR_NO_DEFAULT[] = "no default value, so value must be implemented";

void setDefaultValue(Webss& value, const ParamStandard& defaultValue);

template <class Parameters>
Tuple makeDefaultTuple(const Parameters& params)
{
	Tuple tuple(params.getSharedKeys());
	for (Tuple::size_type i = 0; i < params.size(); ++i)
		setDefaultValue(tuple[i], params[i]);
	return tuple;
}

void setDefaultValue(Webss& value, const ParamStandard& defaultValue)
{
	if (defaultValue.hasTemplateHead())
		value = makeDefaultTuple(defaultValue.getTemplateHeadStandard().getParameters());
	else if (!defaultValue.hasDefaultValue())
		throw runtime_error(ERROR_NO_DEFAULT);
	else
		value = Webss(defaultValue.getDefaultPointer());
}

template <class Parameters>
void checkDefaultValues(Tuple& tuple, const Parameters& params)
{
	for (Tuple::size_type index = 0; index < tuple.size(); ++index)
		if (tuple.at(index).getType() == WebssType::NONE)
			setDefaultValue(tuple[index], params[index]);
}

template <>
void checkDefaultValues<TemplateHeadBinary::Parameters>(Tuple& tuple, const TemplateHeadBinary::Parameters& params) {} //already checked while parsing binary

class ParserTemplates : public Parser
{
private:
	using ParametersStandard = TemplateHeadStandard::Parameters;
	using ParametersBinary = TemplateHeadBinary::Parameters;
public:
	Webss parseTemplateBodyStandard(const ParametersStandard& params)
	{
		return parseTemplateBodyStandard(params, [&](const ParametersStandard& params) { return Webss(parseTemplateTupleStandard(params)); }, [&](const ParametersStandard& params) { return Webss(parseTemplateTupleText(params), true); });
	}

	Webss parseTemplateBodyText(const ParametersStandard& params)
	{
		return parseTemplateBodyStandard(params, [&](const ParametersStandard& params) { return Webss(parseTemplateTupleText(params), true); }, [&](const ParametersStandard& params) { return Webss(parseTemplateTupleText(params), true); });
	}

	Webss parseTemplateBodyStandard(const ParametersStandard& params, function<Webss(const ParametersStandard& params)>&& funcTemplTupleRegular, function<Webss(const ParametersStandard& params)>&& funcTemplTupleText)
	{
		switch (nextTag = getTag(it))
		{
		case Tag::START_DICTIONARY:
			return parseTemplateDictionary<ParametersStandard>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
		case Tag::START_LIST:
			return parseTemplateList<ParametersStandard>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
		case Tag::START_TUPLE:
			return funcTemplTupleRegular(params);
		case Tag::TEXT_TUPLE:
			return funcTemplTupleText(params);
		case Tag::NAME_START:
			return checkTemplateBodyEntity(params, WebssType::DICTIONARY);
		default:
			throw runtime_error(ERROR_UNEXPECTED);
		}
	}

	Webss parseTemplateBodyBinary(const ParametersBinary& params, function<Webss(const ParametersBinary& params)>&& funcTemplTupleRegular, function<Webss(const ParametersBinary& params)>&& funcTemplTupleText)
	{
		switch (nextTag = getTag(it))
		{
		case Tag::START_DICTIONARY:
			return parseTemplateDictionary<ParametersBinary>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
		case Tag::START_LIST:
			return parseTemplateList<ParametersBinary>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
		case Tag::START_TUPLE:
			return funcTemplTupleRegular(params);
		case Tag::TEXT_TUPLE:
			return funcTemplTupleText(params);
		default:
			throw runtime_error(ERROR_UNEXPECTED);
		}
	}

private:
	template <class Parameters>
	Webss checkTemplateBodyEntity(const Parameters& params, WebssType filter)
	{
		auto value = parseValueOnly();
		switch (value.getTypeSafe())
		{
		case WebssType::DICTIONARY:
			if (filter != WebssType::DICTIONARY)
				throw runtime_error(ERROR_UNEXPECTED);
			return checkTemplateBodyEntityDict(params, value.getDictionarySafe());
		case WebssType::LIST:
			if (filter == WebssType::TUPLE)
				throw runtime_error(ERROR_UNEXPECTED);
			return checkTemplateBodyEntityList(params, value.getListSafe());
		case WebssType::TUPLE: case WebssType::TUPLE_TEXT:
			return checkTemplateBodyEntityTuple(params, value.getTupleSafe());
		default:
			throw runtime_error("expected entity with template body structure");
		}
	}

	template <class Parameters>
	Dictionary checkTemplateBodyEntityDict(const Parameters& params, const Dictionary& entityDict)
	{
		Dictionary dict;
		for (const auto& keyValue : entityDict)
		{
			if (keyValue.second.isList())
				dict.add(keyValue.first, checkTemplateBodyEntityList(params, keyValue.second.getListSafe()));
			else
				dict.add(keyValue.first, checkTemplateBodyEntityTuple(params, keyValue.second.getTupleSafe()));
		}
		return dict;
	}

	template <class Parameters>
	List checkTemplateBodyEntityList(const Parameters& params, const List& entityList)
	{
		List list;
		for (const auto& elem : entityList)
			list.add(checkTemplateBodyEntityTuple(params, elem.getTupleSafe()));
		return list;
	}

	template <class Parameters>
	Tuple checkTemplateBodyEntityTuple(const Parameters& params, const Tuple& entityTuple)
	{
		Tuple tuple(params.getSharedKeys(), entityTuple.getData());
		checkDefaultValues(tuple, params);
		return tuple;
	}

	template <class Parameters>
	Dictionary parseTemplateDictionary(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText)
	{
		return parseContainer<Dictionary, ConType::DICTIONARY>(Dictionary(), [&](Dictionary& dict)
		{
			string name;
			if (nextTag == Tag::NAME_START)
				name = parseName(it);
			else if (nextTag == Tag::EXPLICIT_NAME)
				name = parseNameExplicit();
			else
				throw runtime_error(ERROR_UNEXPECTED);

			switch (nextTag = getTag(it))
			{
			case Tag::START_LIST:
				dict.addSafe(move(name), parseTemplateList<Parameters>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)));
				break;
			case Tag::START_TUPLE:
				dict.addSafe(move(name), funcTemplTupleRegular(params));
				break;
			case Tag::TEXT_TUPLE:
				dict.addSafe(move(name), funcTemplTupleText(params));
				break;
			case Tag::NAME_START:
				dict.addSafe(move(name), checkTemplateBodyEntity(params, WebssType::LIST));
				break;
			default:
				throw runtime_error(ERROR_UNEXPECTED);
			}
		});
	}

	template <class Parameters>
	List parseTemplateList(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText)
	{
		return parseContainer<List, ConType::LIST>(List(), [&](List& list)
		{
			if (nextTag == Tag::START_TUPLE)
				list.add(funcTemplTupleRegular(params));
			else if (nextTag == Tag::TEXT_TUPLE)
				list.add(funcTemplTupleText(params));
			else if (nextTag == Tag::NAME_START)
				list.add(checkTemplateBodyEntity(params, WebssType::TUPLE));
			else
				throw runtime_error(ERROR_UNEXPECTED);
		});
	}
};

Webss Parser::parseTemplate()
{
	auto headWebss = parseTemplateHead();
	switch (headWebss.getType())
	{
	case WebssType::BLOCK_HEAD:
		nextTag = getTag(it);
		return Block(move(headWebss.getBlockHead()), parseValueOnly());
	case WebssType::TEMPLATE_HEAD_BINARY:
	{
		auto head = move(headWebss.getTemplateHeadBinary());
		auto body = parseTemplateBodyBinary(head.getParameters());
		return{ move(head), move(body) };
	}
	case WebssType::TEMPLATE_HEAD_SCOPED:
	{
		auto head = move(headWebss.getTemplateHeadScoped());
		auto body = parseTemplateBodyScoped(head.getParameters());
		return TemplateScoped(move(head), move(body));
	}
	case WebssType::TEMPLATE_HEAD_SELF:
		throw runtime_error("self in a thead must be within a non-empty thead");
	case WebssType::TEMPLATE_HEAD_STANDARD:
	{
		auto head = move(headWebss.getTemplateHeadStandard());
		auto body = parseTemplateBodyStandard(head.getParameters());
		return{ move(head), move(body) };
	}
	case WebssType::TEMPLATE_HEAD_TEXT:
	{
		auto head = move(headWebss.getTemplateHeadStandard());
		auto body = parseTemplateBodyText(head.getParameters());
		return{ move(head), move(body), true };
	}
#ifdef assert
	default:
		assert(false);
		throw domain_error("");
#endif
	}
}

Webss Parser::parseTemplateText()
{
	auto head = parseTemplateHeadText();
	auto body = parseTemplateBodyText(head.getParameters());
	return{ move(head), move(body), true };
}

Webss Parser::parseTemplateBodyBinary(const TemplateHeadBinary::Parameters& params)
{
	return static_cast<ParserTemplates*>(this)->parseTemplateBodyBinary(params, [&](const TemplateHeadBinary::Parameters& params) { return parseTemplateTupleBinary(params); }, [&](const TemplateHeadBinary::Parameters& params) -> Webss { throw runtime_error(ERROR_UNEXPECTED); });
}

Webss Parser::parseTemplateBodyScoped(const TemplateHeadScoped::Parameters& params)
{
	ParamDocumentIncluder includer(ents, params);
	nextTag = getTag(it);
	return parseValueOnly();
}

Webss Parser::parseTemplateBodyStandard(const TemplateHeadStandard::Parameters& params)
{
	return static_cast<ParserTemplates*>(this)->parseTemplateBodyStandard(params);
}

Webss Parser::parseTemplateBodyText(const TemplateHeadStandard::Parameters& params)
{
	return static_cast<ParserTemplates*>(this)->parseTemplateBodyText(params);
}

Webss Parser::parseTemplateContainer(const TemplateHeadStandard::Parameters& params, const ParamStandard& defaultValue)
{
	switch (defaultValue.getTypeThead())
	{
	case WebssType::TEMPLATE_HEAD_BINARY:
		return parseTemplateBodyBinary(defaultValue.getTemplateHeadBinary().getParameters());
	case WebssType::TEMPLATE_HEAD_SCOPED:
		return parseTemplateBodyScoped(defaultValue.getTemplateHeadScoped().getParameters());
	case WebssType::TEMPLATE_HEAD_SELF:
		return parseTemplateBodyStandard(params);
	case WebssType::TEMPLATE_HEAD_STANDARD:
		return parseTemplateBodyStandard(defaultValue.getTemplateHeadStandard().getParameters());
	case WebssType::TEMPLATE_HEAD_TEXT:
		return parseTemplateBodyText(defaultValue.getTemplateHeadStandard().getParameters());
	default:
		return parseValueOnly();
	}
}

Tuple Parser::parseTemplateTupleStandard(const TemplateHeadStandard::Parameters& params)
{
	Tuple tuple(params.getSharedKeys());
	Tuple::size_type index = 0;
	ContainerSwitcher switcher(*this, ConType::TUPLE, true);
	if (!containerEmpty())
	{
		do
		{
			switch (nextTag)
			{
			case Tag::SEPARATOR: //void
				break;
			case Tag::EXPLICIT_NAME:
			{
				auto name = parseNameExplicit();
				nextTag = getTag(it);
				tuple.at(name) = parseTemplateContainer(params, params.at(name));
				break;
			}
			default:
				tuple.at(index) = parseTemplateContainer(params, params.at(index));
				break;
			}
			++index;
		} while (checkNextElement());
	}
	checkDefaultValues(tuple, params);
	return tuple;
}

Tuple Parser::parseTemplateTupleText(const TemplateHeadStandard::Parameters& params)
{
	Tuple tuple(params.getSharedKeys());
	Tuple::size_type index = 0;
	ContainerSwitcher switcher(*this, ConType::TUPLE, true);
	if (!containerEmpty())
		do
			tuple.at(index++) = parseLineString();
	while (checkNextElement());
	checkDefaultValues(tuple, params);
	return tuple;
}<commit_msg>Text Template Tuple bugfix and improvement<commit_after>//MIT License
//Copyright(c) 2017 Patrick Laughrea
#include "parser.h"

#include "containerSwitcher.h"
#include "errors.h"
#include "paramDocumentIncluder.h"
#include "patternsContainers.h"
#include "utils/utilsWebss.h"

using namespace std;
using namespace webss;

const char ERROR_NO_DEFAULT[] = "no default value, so value must be implemented";

void setDefaultValue(Webss& value, const ParamStandard& defaultValue);

template <class Parameters>
Tuple makeDefaultTuple(const Parameters& params)
{
	Tuple tuple(params.getSharedKeys());
	for (Tuple::size_type i = 0; i < params.size(); ++i)
		setDefaultValue(tuple[i], params[i]);
	return tuple;
}

void setDefaultValue(Webss& value, const ParamStandard& defaultValue)
{
	if (defaultValue.hasTemplateHead())
		value = makeDefaultTuple(defaultValue.getTemplateHeadStandard().getParameters());
	else if (!defaultValue.hasDefaultValue())
		throw runtime_error(ERROR_NO_DEFAULT);
	else
		value = Webss(defaultValue.getDefaultPointer());
}

template <class Parameters>
void checkDefaultValues(Tuple& tuple, const Parameters& params)
{
	for (Tuple::size_type index = 0; index < tuple.size(); ++index)
		if (tuple.at(index).getType() == WebssType::NONE)
			setDefaultValue(tuple[index], params[index]);
}

template <>
void checkDefaultValues<TemplateHeadBinary::Parameters>(Tuple& tuple, const TemplateHeadBinary::Parameters& params) {} //already checked while parsing binary

class ParserTemplates : public Parser
{
private:
	using ParametersStandard = TemplateHeadStandard::Parameters;
	using ParametersBinary = TemplateHeadBinary::Parameters;
public:
	Webss parseTemplateBodyStandard(const ParametersStandard& params)
	{
		return parseTemplateBodyStandard(params, [&](const ParametersStandard& params) { return Webss(parseTemplateTupleStandard(params)); }, [&](const ParametersStandard& params) { return Webss(parseTemplateTupleText(params), true); });
	}

	Webss parseTemplateBodyText(const ParametersStandard& params)
	{
		return parseTemplateBodyStandard(params, [&](const ParametersStandard& params) { return Webss(parseTemplateTupleText(params), true); }, [&](const ParametersStandard& params) { return Webss(parseTemplateTupleText(params), true); });
	}

	Webss parseTemplateBodyStandard(const ParametersStandard& params, function<Webss(const ParametersStandard& params)>&& funcTemplTupleRegular, function<Webss(const ParametersStandard& params)>&& funcTemplTupleText)
	{
		switch (nextTag = getTag(it))
		{
		case Tag::START_DICTIONARY:
			return parseTemplateDictionary<ParametersStandard>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
		case Tag::START_LIST:
			return parseTemplateList<ParametersStandard>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
		case Tag::START_TUPLE:
			return funcTemplTupleRegular(params);
		case Tag::TEXT_TUPLE:
			return funcTemplTupleText(params);
		case Tag::NAME_START:
			return checkTemplateBodyEntity(params, WebssType::DICTIONARY);
		default:
			throw runtime_error(ERROR_UNEXPECTED);
		}
	}

	Webss parseTemplateBodyBinary(const ParametersBinary& params, function<Webss(const ParametersBinary& params)>&& funcTemplTupleRegular, function<Webss(const ParametersBinary& params)>&& funcTemplTupleText)
	{
		switch (nextTag = getTag(it))
		{
		case Tag::START_DICTIONARY:
			return parseTemplateDictionary<ParametersBinary>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
		case Tag::START_LIST:
			return parseTemplateList<ParametersBinary>(params, move(funcTemplTupleRegular), move(funcTemplTupleText));
		case Tag::START_TUPLE:
			return funcTemplTupleRegular(params);
		case Tag::TEXT_TUPLE:
			return funcTemplTupleText(params);
		default:
			throw runtime_error(ERROR_UNEXPECTED);
		}
	}

private:
	template <class Parameters>
	Webss checkTemplateBodyEntity(const Parameters& params, WebssType filter)
	{
		auto value = parseValueOnly();
		switch (value.getTypeSafe())
		{
		case WebssType::DICTIONARY:
			if (filter != WebssType::DICTIONARY)
				throw runtime_error(ERROR_UNEXPECTED);
			return checkTemplateBodyEntityDict(params, value.getDictionarySafe());
		case WebssType::LIST:
			if (filter == WebssType::TUPLE)
				throw runtime_error(ERROR_UNEXPECTED);
			return checkTemplateBodyEntityList(params, value.getListSafe());
		case WebssType::TUPLE: case WebssType::TUPLE_TEXT:
			return checkTemplateBodyEntityTuple(params, value.getTupleSafe());
		default:
			throw runtime_error("expected entity with template body structure");
		}
	}

	template <class Parameters>
	Dictionary checkTemplateBodyEntityDict(const Parameters& params, const Dictionary& entityDict)
	{
		Dictionary dict;
		for (const auto& keyValue : entityDict)
		{
			if (keyValue.second.isList())
				dict.add(keyValue.first, checkTemplateBodyEntityList(params, keyValue.second.getListSafe()));
			else
				dict.add(keyValue.first, checkTemplateBodyEntityTuple(params, keyValue.second.getTupleSafe()));
		}
		return dict;
	}

	template <class Parameters>
	List checkTemplateBodyEntityList(const Parameters& params, const List& entityList)
	{
		List list;
		for (const auto& elem : entityList)
			list.add(checkTemplateBodyEntityTuple(params, elem.getTupleSafe()));
		return list;
	}

	template <class Parameters>
	Tuple checkTemplateBodyEntityTuple(const Parameters& params, const Tuple& entityTuple)
	{
		Tuple tuple(params.getSharedKeys(), entityTuple.getData());
		checkDefaultValues(tuple, params);
		return tuple;
	}

	template <class Parameters>
	Dictionary parseTemplateDictionary(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText)
	{
		return parseContainer<Dictionary, ConType::DICTIONARY>(Dictionary(), [&](Dictionary& dict)
		{
			string name;
			if (nextTag == Tag::NAME_START)
				name = parseName(it);
			else if (nextTag == Tag::EXPLICIT_NAME)
				name = parseNameExplicit();
			else
				throw runtime_error(ERROR_UNEXPECTED);

			switch (nextTag = getTag(it))
			{
			case Tag::START_LIST:
				dict.addSafe(move(name), parseTemplateList<Parameters>(params, move(funcTemplTupleRegular), move(funcTemplTupleText)));
				break;
			case Tag::START_TUPLE:
				dict.addSafe(move(name), funcTemplTupleRegular(params));
				break;
			case Tag::TEXT_TUPLE:
				dict.addSafe(move(name), funcTemplTupleText(params));
				break;
			case Tag::NAME_START:
				dict.addSafe(move(name), checkTemplateBodyEntity(params, WebssType::LIST));
				break;
			default:
				throw runtime_error(ERROR_UNEXPECTED);
			}
		});
	}

	template <class Parameters>
	List parseTemplateList(const Parameters& params, function<Webss(const Parameters& params)>&& funcTemplTupleRegular, function<Webss(const Parameters& params)>&& funcTemplTupleText)
	{
		return parseContainer<List, ConType::LIST>(List(), [&](List& list)
		{
			if (nextTag == Tag::START_TUPLE)
				list.add(funcTemplTupleRegular(params));
			else if (nextTag == Tag::TEXT_TUPLE)
				list.add(funcTemplTupleText(params));
			else if (nextTag == Tag::NAME_START)
				list.add(checkTemplateBodyEntity(params, WebssType::TUPLE));
			else
				throw runtime_error(ERROR_UNEXPECTED);
		});
	}
};

Webss Parser::parseTemplate()
{
	auto headWebss = parseTemplateHead();
	switch (headWebss.getType())
	{
	case WebssType::BLOCK_HEAD:
		nextTag = getTag(it);
		return Block(move(headWebss.getBlockHead()), parseValueOnly());
	case WebssType::TEMPLATE_HEAD_BINARY:
	{
		auto head = move(headWebss.getTemplateHeadBinary());
		auto body = parseTemplateBodyBinary(head.getParameters());
		return{ move(head), move(body) };
	}
	case WebssType::TEMPLATE_HEAD_SCOPED:
	{
		auto head = move(headWebss.getTemplateHeadScoped());
		auto body = parseTemplateBodyScoped(head.getParameters());
		return TemplateScoped(move(head), move(body));
	}
	case WebssType::TEMPLATE_HEAD_SELF:
		throw runtime_error("self in a thead must be within a non-empty thead");
	case WebssType::TEMPLATE_HEAD_STANDARD:
	{
		auto head = move(headWebss.getTemplateHeadStandard());
		auto body = parseTemplateBodyStandard(head.getParameters());
		return{ move(head), move(body) };
	}
	case WebssType::TEMPLATE_HEAD_TEXT:
	{
		auto head = move(headWebss.getTemplateHeadStandard());
		auto body = parseTemplateBodyText(head.getParameters());
		return{ move(head), move(body), true };
	}
#ifdef assert
	default:
		assert(false);
		throw domain_error("");
#endif
	}
}

Webss Parser::parseTemplateText()
{
	auto head = parseTemplateHeadText();
	auto body = parseTemplateBodyText(head.getParameters());
	return{ move(head), move(body), true };
}

Webss Parser::parseTemplateBodyBinary(const TemplateHeadBinary::Parameters& params)
{
	return static_cast<ParserTemplates*>(this)->parseTemplateBodyBinary(params, [&](const TemplateHeadBinary::Parameters& params) { return parseTemplateTupleBinary(params); }, [&](const TemplateHeadBinary::Parameters& params) -> Webss { throw runtime_error(ERROR_UNEXPECTED); });
}

Webss Parser::parseTemplateBodyScoped(const TemplateHeadScoped::Parameters& params)
{
	ParamDocumentIncluder includer(ents, params);
	nextTag = getTag(it);
	return parseValueOnly();
}

Webss Parser::parseTemplateBodyStandard(const TemplateHeadStandard::Parameters& params)
{
	return static_cast<ParserTemplates*>(this)->parseTemplateBodyStandard(params);
}

Webss Parser::parseTemplateBodyText(const TemplateHeadStandard::Parameters& params)
{
	return static_cast<ParserTemplates*>(this)->parseTemplateBodyText(params);
}

Webss Parser::parseTemplateContainer(const TemplateHeadStandard::Parameters& params, const ParamStandard& defaultValue)
{
	switch (defaultValue.getTypeThead())
	{
	case WebssType::TEMPLATE_HEAD_BINARY:
		return parseTemplateBodyBinary(defaultValue.getTemplateHeadBinary().getParameters());
	case WebssType::TEMPLATE_HEAD_SCOPED:
		return parseTemplateBodyScoped(defaultValue.getTemplateHeadScoped().getParameters());
	case WebssType::TEMPLATE_HEAD_SELF:
		return parseTemplateBodyStandard(params);
	case WebssType::TEMPLATE_HEAD_STANDARD:
		return parseTemplateBodyStandard(defaultValue.getTemplateHeadStandard().getParameters());
	case WebssType::TEMPLATE_HEAD_TEXT:
		return parseTemplateBodyText(defaultValue.getTemplateHeadStandard().getParameters());
	default:
		return parseValueOnly();
	}
}

Tuple Parser::parseTemplateTupleStandard(const TemplateHeadStandard::Parameters& params)
{
	Tuple tuple(params.getSharedKeys());
	Tuple::size_type index = 0;
	ContainerSwitcher switcher(*this, ConType::TUPLE, true);
	if (!containerEmpty())
	{
		do
		{
			switch (nextTag)
			{
			case Tag::SEPARATOR: //void
				break;
			case Tag::EXPLICIT_NAME:
			{
				auto name = parseNameExplicit();
				nextTag = getTag(it);
				tuple.at(name) = parseTemplateContainer(params, params.at(name));
				break;
			}
			default:
				tuple.at(index) = parseTemplateContainer(params, params.at(index));
				break;
			}
			++index;
		} while (checkNextElement());
	}
	checkDefaultValues(tuple, params);
	return tuple;
}

Tuple Parser::parseTemplateTupleText(const TemplateHeadStandard::Parameters& params)
{
	Tuple tuple(params.getSharedKeys());
	Tuple::size_type index = 0;
	ContainerSwitcher switcher(*this, ConType::TUPLE, true);
	if (!containerEmpty())
	{
		do
		{
			switch (nextTag)
			{
			case Tag::SEPARATOR: //void
				break;
			case Tag::EXPLICIT_NAME:
			{
				auto name = parseNameExplicit();
				nextTag = getTag(it);
				tuple.at(name) = parseLineString();
				break;
			}
			default:
				tuple.at(index) = parseLineString();
				break;
			}
			++index;
		} while (checkNextElement());
	}
	checkDefaultValues(tuple, params);
	return tuple;
}<|endoftext|>


<commit_before>#ifndef DUNE_GRID_MULTISCALE_PROVIDER_HH
#define DUNE_GRID_MULTISCALE_PROVIDER_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#include "provider/interface.hh"
#include "provider/cube.hh"

namespace Dune {
namespace grid {
namespace Multiscale {
namespace Provider {

#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
Interface< GridType >* create(const std::string& type = "grid.multiscale.provider.cube",
                              const Dune::ParameterTree paramTree = Dune::ParameterTree())
{
  // choose provider
  if (type == "grid.multiscale.provider.cube") {
    typedef Dune::grid::Multiscale::Provider::Cube< GridType > CubeProviderType;
    CubeProviderType* cubeProvider = new CubeProviderType(CubeProviderType::createFromParamTree(paramTree));
    return cubeProvider;
  } else
    DUNE_THROW(Dune::RangeError,
               "\nERROR: unknown grid provider '" << type << "' requested!");
} // Interface< GridImp >* create(const std::string& type, const Dune::ParameterTree paramTree = Dune::ParameterTree())

} // namespace Provider
} // namespace Multiscale
} // namespace grid
} // namespace Dune

#endif // DUNE_GRID_MULTISCALE_PROVIDER_HH
<commit_msg>[provider] minor fix<commit_after>#ifndef DUNE_GRID_MULTISCALE_PROVIDER_HH
#define DUNE_GRID_MULTISCALE_PROVIDER_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#include "provider/interface.hh"
#include "provider/cube.hh"

namespace Dune {
namespace grid {
namespace Multiscale {
namespace Provider {

#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridType = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
Interface< GridType >* create(const std::string& type = "grid.multiscale.provider.cube",
                              const Dune::ParameterTree paramTree = Dune::ParameterTree())
{
  // choose provider
  if (type == "grid.multiscale.provider.cube") {
    typedef Dune::grid::Multiscale::Provider::Cube< GridType > CubeProviderType;
    CubeProviderType* cubeProvider = new CubeProviderType(CubeProviderType::createFromDescription(paramTree));
    return cubeProvider;
  } else
    DUNE_THROW(Dune::RangeError,
               "\nERROR: unknown grid provider '" << type << "' requested!");
} // Interface< GridImp >* create(const std::string& type, const Dune::ParameterTree paramTree = Dune::ParameterTree())

} // namespace Provider
} // namespace Multiscale
} // namespace grid
} // namespace Dune

#endif // DUNE_GRID_MULTISCALE_PROVIDER_HH
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_LA_CONTAINER_EIGEN_HH
#define DUNE_STUFF_LA_CONTAINER_EIGEN_HH

#if HAVE_EIGEN

#include <Eigen/Core>
#include <Eigen/SparseCore>

#include <dune/common/bartonnackmanifcheck.hh>

#include "interface.hh"
#include "pattern.hh"

namespace Dune {
namespace Stuff {
namespace LA {
namespace Container {
namespace Eigen {

template< class Traits >
class Base
{
public:
  typedef typename Traits::derived_type derived_type;
}; // class Base

template< class Traits >
class MatrixBase
  : public Base< Traits >
{
public:
  typedef typename Base< Traits >::derived_type derived_type;
}; // class MatrixBase

template< class Traits >
class VectorBase
  : public Base< Traits >
{
public:
  typedef typename Base< Traits >::derived_type derived_type;
}; // class VectorBase

template< class ElementType >
class RowMajorSparseMatrix;

template< class ElementImp = double >
class RowMajorSparseMatrixTraits
{
public:
  typedef ElementImp ElementType;

  typedef RowMajorSparseMatrix< ElementType > derived_type;

  typedef typename ::Eigen::SparseMatrix< ElementType, ::Eigen::RowMajor > BaseType;

  typedef typename BaseType::Index size_type;
}; // class RowMajorSparseMatrixTraits

template< class ElementImp = double >
class RowMajorSparseMatrix
  : public MatrixInterface< RowMajorSparseMatrixTraits< ElementImp > >
  , virtual public RowMajorSparseMatrixTraits< ElementImp >::BaseType
  , public MatrixBase< RowMajorSparseMatrixTraits< ElementImp > >
{
public:
  typedef RowMajorSparseMatrixTraits< ElementImp > Traits;

  typedef typename Traits::derived_type derived_type;

  typedef typename Traits::BaseType BaseType;

  typedef typename Traits::ElementType ElementType;

  typedef typename Traits::size_type size_type;

  RowMajorSparseMatrix(const size_type _rows,
                       const size_type _cols,
                       const Dune::Stuff::LA::Container::Pattern::Default& _pattern)
    : BaseType(_rows, _cols)
  {
    assert(size_type(_pattern.rows()) == _rows && "Given pattern too short!");
    typedef Dune::Stuff::LA::Container::Pattern::Default PatternType;
    typedef PatternType::ColumnsType ColumnsType;
    for (size_type row = 0; row < size_type(_pattern.rows()); ++row) {
      BaseType::startVec(row);
      const ColumnsType& columns = _pattern.columns(row);
      for (typename ColumnsType::const_iterator columnIt = columns.begin(); columnIt != columns.end(); ++columnIt) {
        const size_type column = *columnIt;
        BaseType::insertBackByOuterInner(row, column);
      }
      // create diagonal entry (insertBackByOuterInner() can not handle empty rows)
      if (columns.size() == 0)
        BaseType::insertBackByOuterInner(row, row);
    }
    BaseType::finalize();
    BaseType::makeCompressed();
  } // RowMajorSparseMatrix(...)

  size_type rows() const
  {
    return BaseType::rows();
  }

  size_type cols() const
  {
    return BaseType::cols();
  }

  void add(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::coeffRef(i, j) += val;
  }

  void set(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::coeffRef(i, j) = val;
  }

  const ElementType get(const size_type i, const size_type j) const
  {
    return BaseType::coeff(i, j);
  }

  BaseType& base()
  {
    return *this;
  }

  const BaseType& base() const
  {
    return *this;
  }
}; // class RowMajorSparseMatrix

template< class ElementImp >
class DenseMatrix;

template< class ElementImp = double >
class DenseMatrixTraits
{
public:
  typedef ElementImp ElementType;

  typedef DenseMatrix< ElementType > derived_type;

  typedef typename ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, ::Eigen::Dynamic > BaseType;

  typedef typename BaseType::Index size_type;
}; // class DenseMatrixTraits

template< class ElementImp = double >
class DenseMatrix
  : public MatrixInterface< DenseMatrixTraits< ElementImp > >
  , virtual public DenseMatrixTraits< ElementImp >::BaseType
  , public MatrixBase< DenseMatrixTraits< ElementImp > >
{
public:
  typedef DenseMatrixTraits< ElementImp > Traits;

  typedef typename Traits::derived_type derived_type;

  typedef typename Traits::BaseType BaseType;

  typedef typename Traits::ElementType ElementType;

  typedef typename Traits::size_type size_type;

  DenseMatrix(const size_type _rows, const size_type _cols)
    : BaseType(_rows, _cols)
  {}

  size_type rows() const
  {
    return BaseType::rows();
  }

  size_type cols() const
  {
    return BaseType::cols();
  }

  void add(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::operator()(i, j) += val;
  }

  void set(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::operator()(i, j) = val;
  }

  const ElementType get(const size_type i, const size_type j) const
  {
    return BaseType::operator()(i, j);
  }

  BaseType& base()
  {
    return *this;
  }

  const BaseType& base() const
  {
    return *this;
  }
}; // class DenseMatrix

template< class ElementImp >
class DenseVector;

template< class ElementImp = double >
class DenseVectorTraits
{
public:
  typedef ElementImp ElementType;

  typedef DenseVector< ElementType > derived_type;

  typedef typename ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, 1 > BaseType;

  typedef typename BaseType::Index size_type;
}; // class DenseVectorTraits

template< class ElementImp = double>
class DenseVector
  : public VectorInterface< DenseVectorTraits< ElementImp > >
  , virtual public DenseVectorTraits< ElementImp >::BaseType
  , public VectorBase< DenseVectorTraits< ElementImp > >
{
public:
  typedef DenseVectorTraits< ElementImp > Traits;

  typedef typename Traits::derived_type derived_type;

  typedef typename Traits::BaseType BaseType;

  typedef typename Traits::ElementType ElementType;

  typedef typename Traits::size_type size_type;

  DenseVector(const size_type _size)
    : BaseType(_size)
  {
    BaseType::setZero();
  }

  size_type size() const
  {
    return BaseType::size();
  }

  void add(const size_type i, const ElementType& val)
  {
    BaseType::operator()(i) += val;
  }

  void set(const size_type i, const ElementType& val)
  {
    BaseType::operator()(i) = val;
  }

  const ElementType get(const size_type i) const
  {
    return BaseType::operator()(i);
  }

  BaseType& base()
  {
    return *this;
  }

  const BaseType& base() const
  {
    return *this;
  }
}; // class DenseVector

} // namespace Container
} // namespace Eigen
} // namespace LA
} // namespace Stuff
} // namespace Dune

#endif // HAVE_EIGEN

#endif // DUNE_STUFF_LA_CONTAINER_EIGEN_HH
<commit_msg>[la.container.eigen] added empty constructor to RowMajorSparseMatrix<commit_after>#ifndef DUNE_STUFF_LA_CONTAINER_EIGEN_HH
#define DUNE_STUFF_LA_CONTAINER_EIGEN_HH

#if HAVE_EIGEN

#include <Eigen/Core>
#include <Eigen/SparseCore>

#include <dune/common/bartonnackmanifcheck.hh>

#include "interface.hh"
#include "pattern.hh"

namespace Dune {
namespace Stuff {
namespace LA {
namespace Container {
namespace Eigen {

template< class Traits >
class Base
{
public:
  typedef typename Traits::derived_type derived_type;
}; // class Base

template< class Traits >
class MatrixBase
  : public Base< Traits >
{
public:
  typedef typename Base< Traits >::derived_type derived_type;
}; // class MatrixBase

template< class Traits >
class VectorBase
  : public Base< Traits >
{
public:
  typedef typename Base< Traits >::derived_type derived_type;
}; // class VectorBase

template< class ElementType >
class RowMajorSparseMatrix;

template< class ElementImp = double >
class RowMajorSparseMatrixTraits
{
public:
  typedef ElementImp ElementType;

  typedef RowMajorSparseMatrix< ElementType > derived_type;

  typedef typename ::Eigen::SparseMatrix< ElementType, ::Eigen::RowMajor > BaseType;

  typedef typename BaseType::Index size_type;
}; // class RowMajorSparseMatrixTraits

template< class ElementImp = double >
class RowMajorSparseMatrix
  : public MatrixInterface< RowMajorSparseMatrixTraits< ElementImp > >
  , virtual public RowMajorSparseMatrixTraits< ElementImp >::BaseType
  , public MatrixBase< RowMajorSparseMatrixTraits< ElementImp > >
{
public:
  typedef RowMajorSparseMatrixTraits< ElementImp > Traits;

  typedef typename Traits::derived_type derived_type;

  typedef typename Traits::BaseType BaseType;

  typedef typename Traits::ElementType ElementType;

  typedef typename Traits::size_type size_type;

  RowMajorSparseMatrix()
    : BaseType()
  {}

  RowMajorSparseMatrix(const size_type _rows,
                       const size_type _cols,
                       const Dune::Stuff::LA::Container::Pattern::Default& _pattern)
    : BaseType(_rows, _cols)
  {
    assert(size_type(_pattern.rows()) == _rows && "Given pattern too short!");
    typedef Dune::Stuff::LA::Container::Pattern::Default PatternType;
    typedef PatternType::ColumnsType ColumnsType;
    for (size_type row = 0; row < size_type(_pattern.rows()); ++row) {
      BaseType::startVec(row);
      const ColumnsType& columns = _pattern.columns(row);
      for (typename ColumnsType::const_iterator columnIt = columns.begin(); columnIt != columns.end(); ++columnIt) {
        const size_type column = *columnIt;
        BaseType::insertBackByOuterInner(row, column);
      }
      // create diagonal entry (insertBackByOuterInner() can not handle empty rows)
      if (columns.size() == 0)
        BaseType::insertBackByOuterInner(row, row);
    }
    BaseType::finalize();
    BaseType::makeCompressed();
  } // RowMajorSparseMatrix(...)

  size_type rows() const
  {
    return BaseType::rows();
  }

  size_type cols() const
  {
    return BaseType::cols();
  }

  void add(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::coeffRef(i, j) += val;
  }

  void set(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::coeffRef(i, j) = val;
  }

  const ElementType get(const size_type i, const size_type j) const
  {
    return BaseType::coeff(i, j);
  }

  BaseType& base()
  {
    return *this;
  }

  const BaseType& base() const
  {
    return *this;
  }
}; // class RowMajorSparseMatrix

template< class ElementImp >
class DenseMatrix;

template< class ElementImp = double >
class DenseMatrixTraits
{
public:
  typedef ElementImp ElementType;

  typedef DenseMatrix< ElementType > derived_type;

  typedef typename ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, ::Eigen::Dynamic > BaseType;

  typedef typename BaseType::Index size_type;
}; // class DenseMatrixTraits

template< class ElementImp = double >
class DenseMatrix
  : public MatrixInterface< DenseMatrixTraits< ElementImp > >
  , virtual public DenseMatrixTraits< ElementImp >::BaseType
  , public MatrixBase< DenseMatrixTraits< ElementImp > >
{
public:
  typedef DenseMatrixTraits< ElementImp > Traits;

  typedef typename Traits::derived_type derived_type;

  typedef typename Traits::BaseType BaseType;

  typedef typename Traits::ElementType ElementType;

  typedef typename Traits::size_type size_type;

  DenseMatrix(const size_type _rows, const size_type _cols)
    : BaseType(_rows, _cols)
  {}

  size_type rows() const
  {
    return BaseType::rows();
  }

  size_type cols() const
  {
    return BaseType::cols();
  }

  void add(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::operator()(i, j) += val;
  }

  void set(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::operator()(i, j) = val;
  }

  const ElementType get(const size_type i, const size_type j) const
  {
    return BaseType::operator()(i, j);
  }

  BaseType& base()
  {
    return *this;
  }

  const BaseType& base() const
  {
    return *this;
  }
}; // class DenseMatrix

template< class ElementImp >
class DenseVector;

template< class ElementImp = double >
class DenseVectorTraits
{
public:
  typedef ElementImp ElementType;

  typedef DenseVector< ElementType > derived_type;

  typedef typename ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, 1 > BaseType;

  typedef typename BaseType::Index size_type;
}; // class DenseVectorTraits

template< class ElementImp = double>
class DenseVector
  : public VectorInterface< DenseVectorTraits< ElementImp > >
  , virtual public DenseVectorTraits< ElementImp >::BaseType
  , public VectorBase< DenseVectorTraits< ElementImp > >
{
public:
  typedef DenseVectorTraits< ElementImp > Traits;

  typedef typename Traits::derived_type derived_type;

  typedef typename Traits::BaseType BaseType;

  typedef typename Traits::ElementType ElementType;

  typedef typename Traits::size_type size_type;

  DenseVector(const size_type _size)
    : BaseType(_size)
  {
    BaseType::setZero();
  }

  size_type size() const
  {
    return BaseType::size();
  }

  void add(const size_type i, const ElementType& val)
  {
    BaseType::operator()(i) += val;
  }

  void set(const size_type i, const ElementType& val)
  {
    BaseType::operator()(i) = val;
  }

  const ElementType get(const size_type i) const
  {
    return BaseType::operator()(i);
  }

  BaseType& base()
  {
    return *this;
  }

  const BaseType& base() const
  {
    return *this;
  }
}; // class DenseVector

} // namespace Container
} // namespace Eigen
} // namespace LA
} // namespace Stuff
} // namespace Dune

#endif // HAVE_EIGEN

#endif // DUNE_STUFF_LA_CONTAINER_EIGEN_HH
<|endoftext|>