<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2021 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/

#include <miopen/batchnorm/solvers.hpp>

#include <miopen/batchnorm/invoke_params.hpp>
#include <miopen/batchnorm/problem_description.hpp>
#include <miopen/visit_float.hpp>
#include <miopen/kernel_build_params.hpp>

#define WORKAROUND_ISSUE_1146 1 // check asm solver applicability for gfx90a

namespace miopen {

namespace solver {

namespace batchnorm {

bool BnBwdTrainingSpatialSingle::IsApplicable(
    const ExecutionContext&, const miopen::batchnorm::ProblemDescription& problem) const
{
    if(problem.GetDirection() != miopen::batchnorm::Direction::Backward ||
       problem.GetMode() != miopenBNSpatial)
        return false;

    if(problem.IsLayoutNHWC())
        return true;

    int n, c, h, w;
    std::tie(n, c, h, w) = tien<4>(problem.GetXDesc().GetLengths());

    unsigned int in_cstride = h * w;
    unsigned int in_nhw     = n * in_cstride;

    return (in_cstride > 1024 && in_nhw < (32 * 1024 * 1024)) ||
           (in_cstride > 512 && in_nhw < (32 * 1024 * 1024)) || in_cstride <= 512;
}

ConvSolution
BnBwdTrainingSpatialSingle::GetSolution(const ExecutionContext& context,
                                        const miopen::batchnorm::ProblemDescription& problem) const
{
    const auto& handle = context.GetStream();

    bool bfpmixparm = false;
    bool bfp16parm  = false;
    bool bfp32parm  = true;

    if(problem.GetXDesc().GetType() == miopenHalf &&
       problem.GetScaleBiasDiffDesc().GetType() == miopenHalf)
    {
        bfp16parm = true;
        bfp32parm = false;
    }
    else if(problem.GetXDesc().GetType() == miopenHalf &&
            problem.GetScaleBiasDiffDesc().GetType() == miopenFloat)
    {
        bfpmixparm = true;
        bfp32parm  = false;
    }

    int n, c, h, w;
    std::tie(n, c, h, w) = tien<4>(problem.GetXDesc().GetLengths());

    unsigned int in_cstride = h * w;
    unsigned int in_nstride = c * in_cstride;
    unsigned int in_nhw     = n * in_cstride;
    unsigned int in_nchw    = n * in_nstride;

    auto inhw = float(1.0 / in_nhw);

    size_t xlocalsize = 1;
    size_t ylocalsize = 1;

    size_t xgridsize = 1;
    size_t ygridsize = 1;

    unsigned int ldsgcn   = 0;
    unsigned int ldsnogcn = 0;
    int variant           = 1;

    if(problem.IsLayoutNHWC())
    {
        xlocalsize = 1024;
        xgridsize  = c * xlocalsize;
        ldsgcn     = xlocalsize / 64;
        ldsnogcn   = xlocalsize;
    }
    else
    {
        //*************************************************************************************************
        // N*H*W < 32M and H*W > 1024, use batchnorm variant#1 implementation which parallelize
        // work groups over channels and loop through NHW.
        //*************************************************************************************************
        if((in_nhw < (32 * 1024 * 1024) && in_cstride > 1024))
        {
            variant    = 1;
            xlocalsize = 1024;
            xgridsize  = c * xlocalsize;
            ldsgcn     = xlocalsize / 64;
            ldsnogcn   = xlocalsize;
        }
        //*************************************************************************************************
        // N*H*W < 32M and H*W > 512  use batchnorm variant#1 or variant#3 implementation which
        // parallelize
        // work groups over channels and loop through N.
        //*************************************************************************************************
        else if(in_nhw < (32 * 1024 * 1024) && in_cstride > 512)
        {
            variant    = (n >= 32) ? 1 : 3;
            xlocalsize = std::min(64 * ((in_cstride + 63) / 64), static_cast<unsigned int>(1024));
            xgridsize  = c * xlocalsize;
            ldsgcn     = xlocalsize / 64;
            ldsnogcn   = xlocalsize;
        }
        //*************************************************************************************************
        // H*W < 512  use batchnorm variant#0 or variant#3 implementation based on batch size and
        // H*W
        //*************************************************************************************************
        else if(in_cstride <= 512)
        {
            if((n > 64) && (in_cstride > 160))
            {
                variant = 3;
                xlocalsize =
                    std::min(64 * ((in_cstride + 63) / 64), static_cast<unsigned int>(1024));
                xgridsize = c * xlocalsize;
                ldsgcn    = xlocalsize / 64;
                ldsnogcn  = xlocalsize;
            }
            else
            {
                variant = 0;
                if(bfp32parm)
                {
                    xlocalsize = 1024;
                    xgridsize  = 1024 * c;
                }
                else
                {
                    xlocalsize = 256;
                    xgridsize  = 256 * c;
                }
                ldsgcn   = xlocalsize / 64;
                ldsnogcn = xlocalsize;
            }
        }
        //*************************************************************************************************
        // N*H*W > 32M, use batchnorm variant#2 implementation which parallelize
        // work groups over channels and data segments.
        //*************************************************************************************************
        else
        {
            variant      = 2;
            ylocalsize   = 1024;
            auto segment = int(std::ceil(double(in_cstride) / double(ylocalsize)));
            xgridsize    = c;
            ygridsize    = segment * ylocalsize;
            ldsgcn       = ylocalsize / 64;
            ldsnogcn     = ylocalsize;
        }
        if((in_cstride < 200) && (in_cstride > 60) && bfpmixparm)
        {
            variant    = 1;
            xlocalsize = 1024;
            xgridsize  = c * xlocalsize;
            ldsgcn     = xlocalsize / 64;
            ldsnogcn   = xlocalsize;
        }
    }
    auto result = ConvSolution{miopenStatusSuccess};

    {
        size_t zlocalsize = 1;
        size_t zgridsize  = 1;

        auto kernel = KernelInfo{};

        auto build_params = KernelBuildParameters{
            {"MIOPEN_USE_FP16", static_cast<int>(bfp16parm)},
            {"MIOPEN_USE_FP32", static_cast<int>(bfp32parm)},
            {"MIOPEN_USE_FPMIX", static_cast<int>(bfpmixparm)},
            {"MIO_BN_USESAVED", static_cast<int>(problem.UseSaved())},
            {"MIO_BN_N", static_cast<int>(n)},
            {"MIO_BN_C", static_cast<int>(c)},
            {"MIO_BN_HW", static_cast<int>(in_cstride)},
            {"MIO_BN_NHW", static_cast<int>(in_nhw)},
            {"MIO_BN_CHW", in_nstride},
            {"MIO_BN_NCHW", in_nchw},
            {"MIO_BN_LDS_SIZE", ldsnogcn},
            {"MIO_BN_LDSGCN_SIZE", ldsgcn},
            {"MIO_BN_VARIANT", variant},
            {"MIO_BN_GRP0", xlocalsize},
            {"MIO_BN_GRP1", ylocalsize},
            {"MIO_BN_GRP2", zlocalsize},
            {"MIO_LAYOUT_NHWC", static_cast<int>(problem.IsLayoutNHWC())},
        };

        if((n > 64) && (n % 2 == 0) && (variant == 3) && (bfpmixparm) && (problem.UseSaved()) &&
           context.use_asm_kernels && context.rmv.IsV2orV3() &&
           (StartsWith(handle.GetDeviceName(), "gfx8") ||
            (StartsWith(handle.GetDeviceName(), "gfx9")
#if WORKAROUND_ISSUE_1146
             && (handle.GetDeviceName() != "gfx90a")
#endif
                 )) &&
           (!handle.GetTargetProperties().Xnack() || !*handle.GetTargetProperties().Xnack()))
        {
            kernel.kernel_file = "gcnAsmBNBwdTrainSpatial.s";
            kernel.kernel_name = "miopenGcnAsmBNBwdTrainSpatial";

            union
            {
                unsigned u32;
                float f32 = 0;
            } NHW_value;

            NHW_value.f32 = static_cast<float>(in_nhw);

            build_params << KernelBuildParameters{
                {"ROCM_METADATA_VERSION", context.rmv.UseV3() ? "5" : "4"},
                {"MIO_BN_NHW_FLOAT", NHW_value.u32},
            };

            kernel.comp_options = build_params.GenerateFor(kbp::GcnAsm{});
        }
        else
        {
            kernel.kernel_file = "MIOpenBatchNormBwdSpatial.cl";
            kernel.kernel_name = "MIOpenBatchNormBwdSpatial";

            build_params << KernelBuildParameters{
                {"MIO_BN_GFX1030", (handle.GetDeviceName() == "gfx1030") ? "1" : "0"},
            };

            kernel.comp_options = build_params.GenerateFor(kbp::OpenCL{});
        }

        kernel.l_wk.push_back(xlocalsize);
        kernel.l_wk.push_back(ylocalsize);
        kernel.l_wk.push_back(zlocalsize);

        kernel.g_wk.push_back(xgridsize);
        kernel.g_wk.push_back(ygridsize);
        kernel.g_wk.push_back(zgridsize);

        result.construction_params.push_back(kernel);
    }

    const auto dtype    = problem.GetScaleBiasDiffDesc().GetType();
    const auto useSaved = problem.UseSaved();

    result.invoker_factory = [=](const std::vector<Kernel>& kernels) {
        return [=](const Handle& handle_, const AnyInvokeParams& raw_params) {
            decltype(auto) kernel = handle_.Run(kernels.front());
            decltype(auto) params = raw_params.CastTo<miopen::batchnorm::BwdInvokeParams>();

            visit_float(dtype, [&](auto as_float) {
                if(useSaved)
                {
                    kernel(params.x,
                           params.dy,
                           params.dx,
                           params.bnScale,
                           params.resultBnScaleDiff,
                           params.resultBnBiasDiff,
                           params.savedMean,
                           params.savedInvVariance,
                           as_float(inhw));
                }
                else
                {
                    kernel(params.x,
                           params.dy,
                           params.dx,
                           params.bnScale,
                           params.resultBnScaleDiff,
                           params.resultBnBiasDiff,
                           params.epsilon,
                           inhw);
                }
            });
        };
    };

    return result;
}

} // namespace batchnorm

} // namespace solver

} // namespace miopen
<commit_msg>[Navi21] Fixing Batchnorm backward precision issues by adjusting workgroup size (SWDEV-292187, SWDEV-319919) (#1386)<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2021 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/

#include <miopen/batchnorm/solvers.hpp>

#include <miopen/batchnorm/invoke_params.hpp>
#include <miopen/batchnorm/problem_description.hpp>
#include <miopen/visit_float.hpp>
#include <miopen/kernel_build_params.hpp>

#define WORKAROUND_ISSUE_1146 1 // check asm solver applicability for gfx90a

namespace miopen {

namespace solver {

namespace batchnorm {

bool BnBwdTrainingSpatialSingle::IsApplicable(
    const ExecutionContext&, const miopen::batchnorm::ProblemDescription& problem) const
{
    if(problem.GetDirection() != miopen::batchnorm::Direction::Backward ||
       problem.GetMode() != miopenBNSpatial)
        return false;

    if(problem.IsLayoutNHWC())
        return true;

    int n, c, h, w;
    std::tie(n, c, h, w) = tien<4>(problem.GetXDesc().GetLengths());

    unsigned int in_cstride = h * w;
    unsigned int in_nhw     = n * in_cstride;

    return (in_cstride > 1024 && in_nhw < (32 * 1024 * 1024)) ||
           (in_cstride > 512 && in_nhw < (32 * 1024 * 1024)) || in_cstride <= 512;
}

ConvSolution
BnBwdTrainingSpatialSingle::GetSolution(const ExecutionContext& context,
                                        const miopen::batchnorm::ProblemDescription& problem) const
{
    const auto& handle      = context.GetStream();
    const unsigned wavesize = (miopen::StartsWith(handle.GetDeviceName(), "gfx10") ? 32 : 64);

    bool bfpmixparm = false;
    bool bfp16parm  = false;
    bool bfp32parm  = true;

    if(problem.GetXDesc().GetType() == miopenHalf &&
       problem.GetScaleBiasDiffDesc().GetType() == miopenHalf)
    {
        bfp16parm = true;
        bfp32parm = false;
    }
    else if(problem.GetXDesc().GetType() == miopenHalf &&
            problem.GetScaleBiasDiffDesc().GetType() == miopenFloat)
    {
        bfpmixparm = true;
        bfp32parm  = false;
    }

    int n, c, h, w;
    std::tie(n, c, h, w) = tien<4>(problem.GetXDesc().GetLengths());

    unsigned int in_cstride = h * w;
    unsigned int in_nstride = c * in_cstride;
    unsigned int in_nhw     = n * in_cstride;
    unsigned int in_nchw    = n * in_nstride;

    auto inhw = float(1.0 / in_nhw);

    size_t xlocalsize = 1;
    size_t ylocalsize = 1;

    size_t xgridsize = 1;
    size_t ygridsize = 1;

    unsigned int ldsgcn   = 0;
    unsigned int ldsnogcn = 0;
    int variant           = 1;

    if(problem.IsLayoutNHWC())
    {
        xlocalsize = 1024;
        xgridsize  = c * xlocalsize;
        ldsgcn     = xlocalsize / wavesize;
        ldsnogcn   = xlocalsize;
    }
    else
    {
        //*************************************************************************************************
        // N*H*W < 32M and H*W > 1024, use batchnorm variant#1 implementation which parallelize
        // work groups over channels and loop through NHW.
        //*************************************************************************************************
        if((in_nhw < (32 * 1024 * 1024) && in_cstride > 1024))
        {
            variant    = 1;
            xlocalsize = 1024;
            xgridsize  = c * xlocalsize;
            ldsgcn     = xlocalsize / wavesize;
            ldsnogcn   = xlocalsize;
        }
        //*************************************************************************************************
        // N*H*W < 32M and H*W > 512  use batchnorm variant#1 or variant#3 implementation which
        // parallelize
        // work groups over channels and loop through N.
        //*************************************************************************************************
        else if(in_nhw < (32 * 1024 * 1024) && in_cstride > 512)
        {
            variant    = (n >= 32) ? 1 : 3;
            xlocalsize = 1024;
            xgridsize  = c * xlocalsize;
            ldsgcn     = xlocalsize / wavesize;
            ldsnogcn   = xlocalsize;
        }
        //*************************************************************************************************
        // H*W < 512  use batchnorm variant#0 or variant#3 implementation based on batch size and
        // H*W
        //*************************************************************************************************
        else if(in_cstride <= 512)
        {
            if((n > 64) && (in_cstride > 160))
            {
                variant    = 3;
                xlocalsize = 1024;
                xgridsize  = c * xlocalsize;
                ldsgcn     = xlocalsize / wavesize;
                ldsnogcn   = xlocalsize;
            }
            else
            {
                variant    = 0;
                xlocalsize = 1024;
                xgridsize  = 1024 * c;
                ldsgcn     = xlocalsize / wavesize;
                ldsnogcn   = xlocalsize;
            }
        }
        //*************************************************************************************************
        // N*H*W > 32M, use batchnorm variant#2 implementation which parallelize
        // work groups over channels and data segments.
        //*************************************************************************************************
        else
        {
            variant      = 2;
            ylocalsize   = 1024;
            auto segment = int(std::ceil(double(in_cstride) / double(ylocalsize)));
            xgridsize    = c;
            ygridsize    = segment * ylocalsize;
            ldsgcn       = ylocalsize / wavesize;
            ldsnogcn     = ylocalsize;
        }
        if((in_cstride < 200) && (in_cstride > 60) && bfpmixparm)
        {
            variant    = 1;
            xlocalsize = 1024;
            xgridsize  = c * xlocalsize;
            ldsgcn     = xlocalsize / wavesize;
            ldsnogcn   = xlocalsize;
        }
    }
    auto result = ConvSolution{miopenStatusSuccess};

    {
        size_t zlocalsize = 1;
        size_t zgridsize  = 1;

        auto kernel = KernelInfo{};

        auto build_params = KernelBuildParameters{
            {"MIOPEN_USE_FP16", static_cast<int>(bfp16parm)},
            {"MIOPEN_USE_FP32", static_cast<int>(bfp32parm)},
            {"MIOPEN_USE_FPMIX", static_cast<int>(bfpmixparm)},
            {"MIO_BN_USESAVED", static_cast<int>(problem.UseSaved())},
            {"MIO_BN_N", static_cast<int>(n)},
            {"MIO_BN_C", static_cast<int>(c)},
            {"MIO_BN_HW", static_cast<int>(in_cstride)},
            {"MIO_BN_NHW", static_cast<int>(in_nhw)},
            {"MIO_BN_CHW", in_nstride},
            {"MIO_BN_NCHW", in_nchw},
            {"MIO_BN_LDS_SIZE", ldsnogcn},
            {"MIO_BN_LDSGCN_SIZE", ldsgcn},
            {"MIO_BN_VARIANT", variant},
            {"MIO_WAVESIZE", wavesize},
            {"MIO_BN_GRP0", xlocalsize},
            {"MIO_BN_GRP1", ylocalsize},
            {"MIO_BN_GRP2", zlocalsize},
            {"MIO_LAYOUT_NHWC", static_cast<int>(problem.IsLayoutNHWC())},
        };

        if((n > 64) && (n % 2 == 0) && (variant == 3) && (bfpmixparm) && (problem.UseSaved()) &&
           context.use_asm_kernels && context.rmv.IsV2orV3() &&
           (StartsWith(handle.GetDeviceName(), "gfx8") ||
            (StartsWith(handle.GetDeviceName(), "gfx9")
#if WORKAROUND_ISSUE_1146
             && (handle.GetDeviceName() != "gfx90a")
#endif
                 )) &&
           (!handle.GetTargetProperties().Xnack() || !*handle.GetTargetProperties().Xnack()))
        {
            kernel.kernel_file = "gcnAsmBNBwdTrainSpatial.s";
            kernel.kernel_name = "miopenGcnAsmBNBwdTrainSpatial";

            union
            {
                unsigned u32;
                float f32 = 0;
            } NHW_value;

            NHW_value.f32 = static_cast<float>(in_nhw);

            build_params << KernelBuildParameters{
                {"ROCM_METADATA_VERSION", context.rmv.UseV3() ? "5" : "4"},
                {"MIO_BN_NHW_FLOAT", NHW_value.u32},
            };

            kernel.comp_options = build_params.GenerateFor(kbp::GcnAsm{});
        }
        else
        {
            kernel.kernel_file = "MIOpenBatchNormBwdSpatial.cl";
            kernel.kernel_name = "MIOpenBatchNormBwdSpatial";

            build_params << KernelBuildParameters{
                {"MIO_BN_GFX1030", (handle.GetDeviceName() == "gfx1030") ? "1" : "0"},
            };

            kernel.comp_options = build_params.GenerateFor(kbp::OpenCL{});
        }

        kernel.l_wk.push_back(xlocalsize);
        kernel.l_wk.push_back(ylocalsize);
        kernel.l_wk.push_back(zlocalsize);

        kernel.g_wk.push_back(xgridsize);
        kernel.g_wk.push_back(ygridsize);
        kernel.g_wk.push_back(zgridsize);

        result.construction_params.push_back(kernel);
    }

    const auto dtype    = problem.GetScaleBiasDiffDesc().GetType();
    const auto useSaved = problem.UseSaved();

    result.invoker_factory = [=](const std::vector<Kernel>& kernels) {
        return [=](const Handle& handle_, const AnyInvokeParams& raw_params) {
            decltype(auto) kernel = handle_.Run(kernels.front());
            decltype(auto) params = raw_params.CastTo<miopen::batchnorm::BwdInvokeParams>();

            visit_float(dtype, [&](auto as_float) {
                if(useSaved)
                {
                    kernel(params.x,
                           params.dy,
                           params.dx,
                           params.bnScale,
                           params.resultBnScaleDiff,
                           params.resultBnBiasDiff,
                           params.savedMean,
                           params.savedInvVariance,
                           as_float(inhw));
                }
                else
                {
                    kernel(params.x,
                           params.dy,
                           params.dx,
                           params.bnScale,
                           params.resultBnScaleDiff,
                           params.resultBnBiasDiff,
                           params.epsilon,
                           inhw);
                }
            });
        };
    };

    return result;
}

} // namespace batchnorm

} // namespace solver

} // namespace miopen
<|endoftext|>


<commit_before>/***************************************************************************
                          kmailcvt2.cpp  -  description
                             -------------------
    begin                : Wed Aug  2 11:23:04 CEST 2000
    copyright            : (C) 2000 by Hans Dijkema
    email                : kmailcvt@hum.org
 ***************************************************************************/

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

#include "kmailcvt.h"
#include <kaboutdialog.h>
#include <klocale.h>
#include <kapplication.h>
#include <qlayout.h>
#include <kaboutdata.h>
#include <kaboutapplication.h>
#include <qpushbutton.h>

//////////////////////////////////////////////////////////////////////////////
//
// Add filters here
//
//////////////////////////////////////////////////////////////////////////////

#include "filter_oe4.hxx"
#include "filter_oe5.hxx"
#include "filter_pmail.hxx"
#include "filter_plain.hxx"
#include "filter_pab.hxx"
#include "filter_eudora_ab.hxx"
#include "filter_ldif.hxx"

Kmailcvt2::Kmailcvt2(QWidget *parent, const char *name)
	: KWizard(parent, name, true) {

	_parent = parent;

	selfilterpage = new KSelFilterPage(this);
	addPage( selfilterpage, i18n( "Step 1: Select filter" ) );

	importpage = new KImportPage(this);
	addPage( importpage, i18n( "Step 2: Importing..." ) );
	setFinishEnabled(QWizard::page(2), false);

	selfilterpage->addFilter(new filter_oe5);
	selfilterpage->addFilter(new filter_pmail);
	selfilterpage->addFilter(new filter_plain);
	selfilterpage->addFilter(new filter_oe4);
	selfilterpage->addFilter(new filter_pab);
	selfilterpage->addFilter(new filter_ldif);
	selfilterpage->addFilter(new filter_eudora_ab);
}

Kmailcvt2::~Kmailcvt2() {
}

void Kmailcvt2::next() {
	if(currentPage()==selfilterpage){
		// Save selected filter
		filter *selectedFilter = selfilterpage->getSelectedFilter();
		// Goto next page
		QWizard::next();
		// Disable cancel & back
		QWizard::cancelButton()->setEnabled(false);
		setBackEnabled(QWizard::currentPage(), false);
		// Start import
		filterInfo *info = new filterInfo(importpage, _parent);
		info->clear(); // Clear info from last time
		selectedFilter->import(info);
		// Cleanup
		delete info;
		// Enable finish button also reenable back
		setFinishEnabled(QWizard::currentPage(), true);
		setBackEnabled(QWizard::currentPage(), true);
		return;
	}
	QWizard::next();
}

void Kmailcvt2::back() {
	QWizard::cancelButton()->setEnabled(true); // Re-enable cancel
	QWizard::back();
}

void Kmailcvt2::help()
{
	KAboutData aboutData( "KMailCVT", I18N_NOOP("KMAILCVT"),
		KMAILCVT_VERSION, KMAILCVT,
		KAboutData::License_GPL_V2,
		"(c) 2000, Hans Dijkema");
	aboutData.addAuthor("Hans Dijkema","Original author", "kmailcvt@hum.org", "http://www.hum.org/kmailcvt.html");
	selfilterpage->setAuthors(aboutData);

	KAboutApplication a(&aboutData, _parent);
	a.exec();
}

#include "kmailcvt.moc"
<commit_msg>reorder, makes more sense imho<commit_after>/***************************************************************************
                          kmailcvt2.cpp  -  description
                             -------------------
    begin                : Wed Aug  2 11:23:04 CEST 2000
    copyright            : (C) 2000 by Hans Dijkema
    email                : kmailcvt@hum.org
 ***************************************************************************/

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

#include "kmailcvt.h"
#include <kaboutdialog.h>
#include <klocale.h>
#include <kapplication.h>
#include <qlayout.h>
#include <kaboutdata.h>
#include <kaboutapplication.h>
#include <qpushbutton.h>

//////////////////////////////////////////////////////////////////////////////
//
// Add filters here
//
//////////////////////////////////////////////////////////////////////////////

#include "filter_oe4.hxx"
#include "filter_oe5.hxx"
#include "filter_pmail.hxx"
#include "filter_plain.hxx"
#include "filter_pab.hxx"
#include "filter_eudora_ab.hxx"
#include "filter_ldif.hxx"

Kmailcvt2::Kmailcvt2(QWidget *parent, const char *name)
	: KWizard(parent, name, true) {

	_parent = parent;

	selfilterpage = new KSelFilterPage(this);
	addPage( selfilterpage, i18n( "Step 1: Select filter" ) );

	importpage = new KImportPage(this);
	addPage( importpage, i18n( "Step 2: Importing..." ) );
	setFinishEnabled(QWizard::page(2), false);

	selfilterpage->addFilter(new filter_oe5);
	selfilterpage->addFilter(new filter_oe4);
	selfilterpage->addFilter(new filter_pmail);
	selfilterpage->addFilter(new filter_plain);
	selfilterpage->addFilter(new filter_pab);
	selfilterpage->addFilter(new filter_ldif);
	selfilterpage->addFilter(new filter_eudora_ab);
}

Kmailcvt2::~Kmailcvt2() {
}

void Kmailcvt2::next() {
	if(currentPage()==selfilterpage){
		// Save selected filter
		filter *selectedFilter = selfilterpage->getSelectedFilter();
		// Goto next page
		QWizard::next();
		// Disable cancel & back
		QWizard::cancelButton()->setEnabled(false);
		setBackEnabled(QWizard::currentPage(), false);
		// Start import
		filterInfo *info = new filterInfo(importpage, _parent);
		info->clear(); // Clear info from last time
		selectedFilter->import(info);
		// Cleanup
		delete info;
		// Enable finish button also reenable back
		setFinishEnabled(QWizard::currentPage(), true);
		setBackEnabled(QWizard::currentPage(), true);
		return;
	}
	QWizard::next();
}

void Kmailcvt2::back() {
	QWizard::cancelButton()->setEnabled(true); // Re-enable cancel
	QWizard::back();
}

void Kmailcvt2::help()
{
	KAboutData aboutData( "KMailCVT", I18N_NOOP("KMAILCVT"),
		KMAILCVT_VERSION, KMAILCVT,
		KAboutData::License_GPL_V2,
		"(c) 2000, Hans Dijkema");
	aboutData.addAuthor("Hans Dijkema","Original author", "kmailcvt@hum.org", "http://www.hum.org/kmailcvt.html");
	selfilterpage->setAuthors(aboutData);

	KAboutApplication a(&aboutData, _parent);
	a.exec();
}

#include "kmailcvt.moc"
<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH

#include <dune/common/bartonnackmanifcheck.hh>
#include <dune/common/dynvector.hh>

#include <dune/stuff/la/container/pattern.hh>

namespace Dune {
namespace Detailed {
namespace Discretizations {

template< class Traits >
class SpaceInterface
{
public:
  typedef typename Traits::derived_type derived_type;

  typedef typename Traits::GridPartType   GridPartType;
  static const int                        polOrder = Traits::polOrder;
  typedef typename GridPartType::ctype    DomainFieldType;
  static const unsigned int               dimDomain = GridPartType::dimension;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRangeRows = Traits::dimRangeRows;
  static const unsigned int               dimRangeCols = Traits::dimRangeCols;

  typedef typename Traits::BackendType          BackendType;
  typedef typename Traits::MapperType           MapperType;
  typedef typename Traits::BaseFunctionSetType  BaseFunctionSetType;
  typedef typename Traits::EntityType           EntityType;

  typedef Dune::Stuff::LA::Container::SparsityPatternDefault PatternType;

  const GridPartType& gridPart() const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().gridPart());
    return asImp().gridPart();
  }

  const BackendType& backend() const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().backend());
    return asImp().backend();
  }

  bool continuous() const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().continuous());
    return asImp().continuous();
  }

  const MapperType& mapper() const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().mapper());
    return asImp().mapper();
  }

  BaseFunctionSetType baseFunctionSet(const EntityType& entity) const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().baseFunctionSet(entity));
    return asImp().baseFunctionSet(entity);
  }

  PatternType* computePattern() const
  {
    return computePattern(*this);
  }

  template< class OtherSpaceType >
  PatternType* computePattern(const OtherSpaceType& other) const
  {
    // check type of the other space
    return computePattern(gridPart(), other);
  }

  /**
   *  \brief  computes a sparsity pattern, where this space is the test space (rows/outer) and the other space is the
   *          ansatz space (cols/inner)
   */
  template< class LocalGridPartType, class O >
  PatternType* computePattern(const LocalGridPartType& localGridPart,
                              const SpaceInterface< O >& otherSpace) const
  {
    typedef typename PatternType::size_type size_type;
    PatternType* ret = new PatternType(mapper().size());
    PatternType& pattern = *ret;
    // walk the grid part
    for (typename LocalGridPartType::template Codim< 0 >::IteratorType entityIt = localGridPart.template begin< 0 >();
         entityIt != localGridPart.template end< 0 >();
         ++entityIt) {
      const typename LocalGridPartType::template Codim< 0 >::EntityType& entity = *entityIt;
      // get basefunctionsets
      const auto testBase = baseFunctionSet(entity);
      const auto ansatzBase = otherSpace.baseFunctionSet(entity);
      Dune::DynamicVector< size_t > globalRows(testBase.size(), 0);
      mapper().globalIndices(entity, globalRows);
      Dune::DynamicVector< size_t > globalCols(ansatzBase.size(), 0);
      otherSpace.mapper().globalIndices(entity, globalCols);
      for (size_t ii = 0; ii < testBase.size(); ++ii) {
        auto& columns = pattern.inner(globalRows[ii]);
        for (size_t jj = 0; jj < ansatzBase.size(); ++jj) {
          columns.insert(globalCols[jj]);
        }
      }
    } // walk the grid part
    return ret;
  } // ... computePattern(...)

  derived_type& asImp()
  {
    return static_cast< derived_type& >(*this);
  }

  const derived_type& asImp() const
  {
    return static_cast< const derived_type& >(*this);
  }
}; // class SpaceInterface

} // namespace Discretizations
} // namespace Detailed
} // namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH
<commit_msg>[spaceinterface] added localConstraints()<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH
#define DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH

#include <dune/common/bartonnackmanifcheck.hh>
#include <dune/common/dynvector.hh>

#include <dune/stuff/la/container/pattern.hh>

#include "constraints.hh"

namespace Dune {
namespace Detailed {
namespace Discretizations {

template< class Traits >
class SpaceInterface
{
public:
  typedef typename Traits::derived_type derived_type;

  typedef typename Traits::GridPartType   GridPartType;
  static const int                        polOrder = Traits::polOrder;
  typedef typename GridPartType::ctype    DomainFieldType;
  static const unsigned int               dimDomain = GridPartType::dimension;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int               dimRangeRows = Traits::dimRangeRows;
  static const unsigned int               dimRangeCols = Traits::dimRangeCols;

  typedef typename Traits::BackendType          BackendType;
  typedef typename Traits::MapperType           MapperType;
  typedef typename Traits::BaseFunctionSetType  BaseFunctionSetType;
  typedef typename Traits::EntityType           EntityType;

  typedef Dune::Stuff::LA::Container::SparsityPatternDefault PatternType;

  const GridPartType& gridPart() const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().gridPart());
    return asImp().gridPart();
  }

  const BackendType& backend() const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().backend());
    return asImp().backend();
  }

  bool continuous() const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().continuous());
    return asImp().continuous();
  }

  const MapperType& mapper() const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().mapper());
    return asImp().mapper();
  }

  BaseFunctionSetType baseFunctionSet(const EntityType& entity) const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().baseFunctionSet(entity));
    return asImp().baseFunctionSet(entity);
  }

  template< class ConstraintsType >
  void localConstraints(const EntityType& entity, ConstraintsType& ret) const
  {
    CHECK_INTERFACE_IMPLEMENTATION(asImp().localConstraints(entity, ret));
    asImp().localConstraints(entity, ret);
  }

  PatternType* computePattern() const
  {
    return computePattern(*this);
  }

  template< class OtherSpaceType >
  PatternType* computePattern(const OtherSpaceType& other) const
  {
    // check type of the other space
    return computePattern(gridPart(), other);
  }

  /**
   *  \brief  computes a sparsity pattern, where this space is the test space (rows/outer) and the other space is the
   *          ansatz space (cols/inner)
   */
  template< class LocalGridPartType, class O >
  PatternType* computePattern(const LocalGridPartType& localGridPart,
                              const SpaceInterface< O >& otherSpace) const
  {
    typedef typename PatternType::size_type size_type;
    PatternType* ret = new PatternType(mapper().size());
    PatternType& pattern = *ret;
    // walk the grid part
    for (typename LocalGridPartType::template Codim< 0 >::IteratorType entityIt = localGridPart.template begin< 0 >();
         entityIt != localGridPart.template end< 0 >();
         ++entityIt) {
      const typename LocalGridPartType::template Codim< 0 >::EntityType& entity = *entityIt;
      // get basefunctionsets
      const auto testBase = baseFunctionSet(entity);
      const auto ansatzBase = otherSpace.baseFunctionSet(entity);
      Dune::DynamicVector< size_t > globalRows(testBase.size(), 0);
      mapper().globalIndices(entity, globalRows);
      Dune::DynamicVector< size_t > globalCols(ansatzBase.size(), 0);
      otherSpace.mapper().globalIndices(entity, globalCols);
      for (size_t ii = 0; ii < testBase.size(); ++ii) {
        auto& columns = pattern.inner(globalRows[ii]);
        for (size_t jj = 0; jj < ansatzBase.size(); ++jj) {
          columns.insert(globalCols[jj]);
        }
      }
    } // walk the grid part
    return ret;
  } // ... computePattern(...)

  derived_type& asImp()
  {
    return static_cast< derived_type& >(*this);
  }

  const derived_type& asImp() const
  {
    return static_cast< const derived_type& >(*this);
  }
}; // class SpaceInterface

} // namespace Discretizations
} // namespace Detailed
} // namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH
#define DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH

#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/ESV2007.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/grid/provider/cube.hh>

#include <dune/gdt/test/stationary-eocstudy.hh>

#include "base.hh"

namespace Dune {
namespace GDT {
namespace LinearElliptic {

template <class E, class D, int d, class R, int r = 1>
class ESV2007Problem : public ProblemBase<E, D, d, R, r>
{
  static_assert(AlwaysFalse<E>::value, "Not available for these dimensions!");
};

template <class EntityImp, class DomainFieldImp, class RangeFieldImp>
class ESV2007Problem<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1>
    : public ProblemBase<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1>
{
  typedef ProblemBase<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1> BaseType;
  typedef Stuff::Functions::Constant<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1> ScalarConstantFunctionType;
  typedef Stuff::Functions::Constant<EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2> MatrixConstantFunctionType;
  typedef Stuff::Functions::ESV2007::Testcase1Force<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1> ForceType;

  template <class G, bool anything = true>
  struct GridHelper
  {
    static Stuff::Common::Configuration default_grid_cfg()
    {
      // currently: SGrid, add specialization for other grids, if needed
      auto cfg               = Stuff::Grid::Providers::Configs::Cube_default();
      cfg["lower_left"]      = "[-1 -1]";
      cfg["num_elements"]    = "[8 8]";
      cfg["num_refinements"] = "0";
      return cfg;
    }
  };

  template <bool anything>
  struct GridHelper<ALU2dGrid<2, 2, (ALU2DGrid::ElementType)0u>, anything>
  {
    static Stuff::Common::Configuration default_grid_cfg()
    {
      auto cfg               = Stuff::Grid::Providers::Configs::Cube_default();
      cfg["lower_left"]      = "[-1 -1]";
      cfg["num_elements"]    = "[4 4]";
      cfg["num_refinements"] = "2";
      return cfg;
    }
  };

  template <class E, bool anything = true>
  struct Helper
  {
    static_assert(AlwaysFalse<E>::value, "");
  };

  template <int cd, int dim, class G, template <int, int, class> class E, bool anything>
  struct Helper<Entity<cd, dim, G, E>, anything>
  {
    static Stuff::Common::Configuration default_grid_cfg()
    {
      return GridHelper<typename std::remove_const<G>::type>::default_grid_cfg();
    }
  };

public:
  static const size_t default_integration_order = 2;

  static Stuff::Common::Configuration default_grid_cfg()
  {
    return Helper<EntityImp>::default_grid_cfg();
  }

  static Stuff::Common::Configuration default_boundary_info_cfg()
  {
    return Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config();
  }

  ESV2007Problem(const size_t integration_order = default_integration_order,
                 const Stuff::Common::Configuration& grd_cfg = default_grid_cfg(),
                 const Stuff::Common::Configuration& bnd_cfg = default_boundary_info_cfg())
    : BaseType(new ScalarConstantFunctionType(1, "diffusion_factor"),
               new MatrixConstantFunctionType(Stuff::Functions::internal::unit_matrix<RangeFieldImp, 2>(),
                                              "diffusion_tensor"),
               new ForceType(integration_order, "force"), new ScalarConstantFunctionType(0, "dirichlet"),
               new ScalarConstantFunctionType(0, "neumann"), grd_cfg, bnd_cfg)
  {
  }
}; // class ESV2007Problem< ..., 1 >

template <class G, class R = double, int r = 1>
class ESV2007TestCase
    : public Test::StationaryTestCase<G, LinearElliptic::ESV2007Problem<typename G::template Codim<0>::Entity,
                                                                        typename G::ctype, G::dimension, R, r>>
{
  typedef typename G::template Codim<0>::Entity E;
  typedef typename G::ctype D;
  static const size_t d = G::dimension;
  typedef Stuff::Functions::ESV2007::Testcase1ExactSolution<E, D, d, R, r> ExactSolutionType;

public:
  typedef LinearElliptic::ESV2007Problem<E, D, d, R, r> ProblemType;

private:
  typedef Test::StationaryTestCase<G, ProblemType> BaseType;

public:
  using typename BaseType::GridType;

  ESV2007TestCase(const size_t num_refs = 3)
    : BaseType(Stuff::Grid::Providers::Cube<G>::create(ProblemType::default_grid_cfg())->grid_ptr(), num_refs)
    , problem_()
    , exact_solution_()
  {
  }

  virtual const ProblemType& problem() const override final
  {
    return problem_;
  }

  virtual void print_header(std::ostream& out = std::cout) const override final
  {
    out << "+==================================================================+\n"
        << "|+================================================================+|\n"
        << "||  Testcase ESV2007: smooth data, homogeneous dirichlet          ||\n"
        << "||  (see testcase 1, page 23 in Ern, Stephansen, Vohralik, 2007)  ||\n"
        << "|+----------------------------------------------------------------+|\n"
        << "||  domain = [-1, 1] x [-1, 1]                                    ||\n"
        << "||  diffusion = 1                                                 ||\n"
        << "||  force     = 1/2 pi^2 cos(1/2 pi x) cos(1/2 pi y)              ||\n"
        << "||  dirichlet = 0                                                 ||\n"
        << "||  exact solution = cos(1/2 pi x) cos(1/2 pi y)                  ||\n"
        << "|+================================================================+|\n"
        << "+==================================================================+" << std::endl;
  }

  virtual bool provides_exact_solution() const override final
  {
    return true;
  }

  virtual const ExactSolutionType& exact_solution() const override final
  {
    return exact_solution_;
  }

private:
  const ProblemType problem_;
  const ExactSolutionType exact_solution_;
}; // class ESV2007TestCase

} // namespace LinearElliptic
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH
<commit_msg>[linearelliptic.problems.ESV2007] simplify grid cfg handling<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH
#define DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH

#if HAVE_ALUGRID
#include <dune/grid/alugrid.hh>
#endif

#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/ESV2007.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/grid/provider/cube.hh>

#include <dune/gdt/test/stationary-eocstudy.hh>

#include "base.hh"

namespace Dune {
namespace GDT {
namespace LinearElliptic {

template <class E, class D, int d, class R, int r = 1>
class ESV2007Problem : public ProblemBase<E, D, d, R, r>
{
  static_assert(AlwaysFalse<E>::value, "Not available for these dimensions!");
};

template <class EntityImp, class DomainFieldImp, class RangeFieldImp>
class ESV2007Problem<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1>
    : public ProblemBase<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1>
{
  typedef ProblemBase<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1> BaseType;
  typedef Stuff::Functions::Constant<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1> ScalarConstantFunctionType;
  typedef Stuff::Functions::Constant<EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2> MatrixConstantFunctionType;
  typedef Stuff::Functions::ESV2007::Testcase1Force<EntityImp, DomainFieldImp, 2, RangeFieldImp, 1> ForceType;

  template <class E>
  struct Helper
  {
    static_assert(AlwaysFalse<E>::value, "This should not happen!");
  };

  template <int cd, int dim, class G, template <int, int, class> class E>
  struct Helper<Entity<cd, dim, G, E>>
  {
    static Stuff::Common::Configuration default_grid_cfg()
    {
      auto cfg               = Stuff::Grid::Providers::Configs::Cube_default();
      cfg["lower_left"]      = "[-1 -1]";
      cfg["num_elements"]    = "[8 8]";
      cfg["num_refinements"] = "0";
#if HAVE_ALUGRID
      if (std::is_same<typename std::decay<G>::type, ALU2dGrid<2, 2, (ALU2DGrid::ElementType)0u>>::value) {
        cfg["num_elements"]    = "[4 4]";
        cfg["num_refinements"] = "2";
      }
#endif // HAVE_ALUGRID
      return cfg;
    }
  };

public:
  static const size_t default_integration_order = 2;

  static Stuff::Common::Configuration default_grid_cfg()
  {
    return Helper<EntityImp>::default_grid_cfg();
  }

  static Stuff::Common::Configuration default_boundary_info_cfg()
  {
    return Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config();
  }

  ESV2007Problem(const size_t integration_order = default_integration_order,
                 const Stuff::Common::Configuration& grd_cfg = default_grid_cfg(),
                 const Stuff::Common::Configuration& bnd_cfg = default_boundary_info_cfg())
    : BaseType(new ScalarConstantFunctionType(1, "diffusion_factor"),
               new MatrixConstantFunctionType(Stuff::Functions::internal::unit_matrix<RangeFieldImp, 2>(),
                                              "diffusion_tensor"),
               new ForceType(integration_order, "force"), new ScalarConstantFunctionType(0, "dirichlet"),
               new ScalarConstantFunctionType(0, "neumann"), grd_cfg, bnd_cfg)
  {
  }
}; // class ESV2007Problem< ..., 1 >

template <class G, class R = double, int r = 1>
class ESV2007TestCase
    : public Test::StationaryTestCase<G, LinearElliptic::ESV2007Problem<typename G::template Codim<0>::Entity,
                                                                        typename G::ctype, G::dimension, R, r>>
{
  typedef typename G::template Codim<0>::Entity E;
  typedef typename G::ctype D;
  static const size_t d = G::dimension;
  typedef Stuff::Functions::ESV2007::Testcase1ExactSolution<E, D, d, R, r> ExactSolutionType;

public:
  typedef LinearElliptic::ESV2007Problem<E, D, d, R, r> ProblemType;

private:
  typedef Test::StationaryTestCase<G, ProblemType> BaseType;

public:
  using typename BaseType::GridType;

  ESV2007TestCase(const size_t num_refs = 3)
    : BaseType(Stuff::Grid::Providers::Cube<G>::create(ProblemType::default_grid_cfg())->grid_ptr(), num_refs)
    , problem_()
    , exact_solution_()
  {
  }

  virtual const ProblemType& problem() const override final
  {
    return problem_;
  }

  virtual void print_header(std::ostream& out = std::cout) const override final
  {
    out << "+==================================================================+\n"
        << "|+================================================================+|\n"
        << "||  Testcase ESV2007: smooth data, homogeneous dirichlet          ||\n"
        << "||  (see testcase 1, page 23 in Ern, Stephansen, Vohralik, 2007)  ||\n"
        << "|+----------------------------------------------------------------+|\n"
        << "||  domain = [-1, 1] x [-1, 1]                                    ||\n"
        << "||  diffusion = 1                                                 ||\n"
        << "||  force     = 1/2 pi^2 cos(1/2 pi x) cos(1/2 pi y)              ||\n"
        << "||  dirichlet = 0                                                 ||\n"
        << "||  exact solution = cos(1/2 pi x) cos(1/2 pi y)                  ||\n"
        << "|+================================================================+|\n"
        << "+==================================================================+" << std::endl;
  }

  virtual bool provides_exact_solution() const override final
  {
    return true;
  }

  virtual const ExactSolutionType& exact_solution() const override final
  {
    return exact_solution_;
  }

private:
  const ProblemType problem_;
  const ExactSolutionType exact_solution_;
}; // class ESV2007TestCase

} // namespace LinearElliptic
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH
<|endoftext|>


<commit_before>/*
* Copyright (c) 2011 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and 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 <processor/SyscallManager.h>
#include <processor/Processor.h>
#include <process/Scheduler.h>
#include <Log.h>

#include <ipc/Ipc.h>
#include <native-ipc.h>

#include "NativeSyscallManager.h"
#include <nativeSyscallNumbers.h>

NativeSyscallManager::NativeSyscallManager()
{
}

NativeSyscallManager::~NativeSyscallManager()
{
}

void NativeSyscallManager::initialise()
{
    SyscallManager::instance().registerSyscallHandler(native, this);
}

uintptr_t NativeSyscallManager::call(uintptr_t function, uintptr_t p1, uintptr_t p2, uintptr_t p3, uintptr_t p4, uintptr_t p5)
{
    if (function >= serviceEnd)
    {
        ERROR("NativeSyscallManager: invalid function called: " << Dec << static_cast<int>(function));
        return 0;
    }
    return SyscallManager::instance().syscall(posix, function, p1, p2, p3, p4, p5);
}

uintptr_t NativeSyscallManager::syscall(SyscallState &state)
{
    uintptr_t p1 = state.getSyscallParameter(0);
    uintptr_t p2 = state.getSyscallParameter(1);
    uintptr_t p3 = state.getSyscallParameter(2);
    uintptr_t p4 = state.getSyscallParameter(3);
    uintptr_t p5 = state.getSyscallParameter(4);

    // We're interruptible.
    Processor::setInterrupts(true);

    // NOTICE("Native syscall " << state.getSyscallNumber() << " (" << p1 << ", " << p2 << ", " << p3 << ", " << p4 << ", " << p5);

    switch (state.getSyscallNumber())
    {
        case IPC_CREATE_STANDARD_MESSAGE:
            return createStandardMessage(reinterpret_cast<PedigreeIpc::IpcMessage*>(p1));
        case IPC_CREATE_SHARED_MESSAGE:
            return createSharedMessage(reinterpret_cast<PedigreeIpc::IpcMessage*>(p1), static_cast<size_t>(p2), p3);
        case IPC_GET_SHARED_REGION:
            return reinterpret_cast<uintptr_t>(getIpcSharedRegion(reinterpret_cast<PedigreeIpc::IpcMessage*>(p1)));
        case IPC_DESTROY_MESSAGE:
            destroyMessage(reinterpret_cast<PedigreeIpc::IpcMessage*>(p1));
            break;

        case IPC_SEND_IPC:
            return static_cast<uintptr_t>(sendIpc(reinterpret_cast<PedigreeIpc::IpcEndpoint*>(p1),reinterpret_cast<PedigreeIpc::IpcMessage*>(p2), static_cast<bool>(p3)));
        case IPC_RECV_PHASE1:
            return reinterpret_cast<uintptr_t>(recvIpcPhase1(reinterpret_cast<PedigreeIpc::IpcEndpoint*>(p1), static_cast<bool>(p2)));
        case IPC_RECV_PHASE2:
            return recvIpcPhase2(reinterpret_cast<PedigreeIpc::IpcMessage*>(p1), reinterpret_cast<void*>(p2));

        case IPC_CREATE_ENDPOINT:
            createEndpoint(reinterpret_cast<const char *>(p1));
            break;
        case IPC_REMOVE_ENDPOINT:
            removeEndpoint(reinterpret_cast<const char *>(p1));
            break;
        case IPC_GET_ENDPOINT:
            return reinterpret_cast<uintptr_t>(getEndpoint(reinterpret_cast<const char *>(p1)));
            break;

        default: ERROR ("NativeSyscallManager: invalid syscall received: " << Dec << state.getSyscallNumber()); return 0;
    }

    return 0;
}
<commit_msg>native: native syscall timing (alerts if ~ > 1s spent in a syscall)<commit_after>/*
* Copyright (c) 2011 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and 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 <processor/SyscallManager.h>
#include <processor/Processor.h>
#include <process/Scheduler.h>
#include <Log.h>

#define MACHINE_FORWARD_DECL_ONLY
#include <machine/Machine.h>
#include <machine/Timer.h>

#include <ipc/Ipc.h>
#include <native-ipc.h>

#include "NativeSyscallManager.h"
#include <nativeSyscallNumbers.h>

NativeSyscallManager::NativeSyscallManager()
{
}

NativeSyscallManager::~NativeSyscallManager()
{
}

void NativeSyscallManager::initialise()
{
    SyscallManager::instance().registerSyscallHandler(native, this);
}

uintptr_t NativeSyscallManager::call(uintptr_t function, uintptr_t p1, uintptr_t p2, uintptr_t p3, uintptr_t p4, uintptr_t p5)
{
    if (function >= serviceEnd)
    {
        ERROR("NativeSyscallManager: invalid function called: " << Dec << static_cast<int>(function));
        return 0;
    }

    uintptr_t ret = SyscallManager::instance().syscall(native, function, p1, p2, p3, p4, p5);
    return ret;
}

class SyscallTimer
{
    public:
        SyscallTimer(uintptr_t func) : function(func), t1(0), t2(0), p1(0), p2(0)
        {
            Timer *pTimer = Machine::instance().getTimer();
            t1 = pTimer->getUnixTimestamp();
            p1 = pTimer->getTickCount();
        }

        ~SyscallTimer()
        {
            Timer *pTimer = Machine::instance().getTimer();
            t2 = pTimer->getUnixTimestamp();
            p2 = pTimer->getTickCount();

            if(t2 - t1)
            {
                NOTICE("native: syscall " << function);
                NOTICE(" -> start=" << t1 << " (" << p1 << ")");
                NOTICE(" -> end=" << t2 << " (" << p2 << ")");
            }
        }

    private:
        uintptr_t function;
        uint64_t t1, t2;
        uint64_t p1, p2;
};

uintptr_t NativeSyscallManager::syscall(SyscallState &state)
{
    uintptr_t p1 = state.getSyscallParameter(0);
    uintptr_t p2 = state.getSyscallParameter(1);
    uintptr_t p3 = state.getSyscallParameter(2);
    uintptr_t p4 = state.getSyscallParameter(3);
    uintptr_t p5 = state.getSyscallParameter(4);

    // We're interruptible.
    Processor::setInterrupts(true);

    // NOTICE("Native syscall " << state.getSyscallNumber() << " (" << p1 << ", " << p2 << ", " << p3 << ", " << p4 << ", " << p5);

    SyscallTimer timeme(state.getSyscallNumber());

    switch (state.getSyscallNumber())
    {
        case IPC_CREATE_STANDARD_MESSAGE:
            return createStandardMessage(reinterpret_cast<PedigreeIpc::IpcMessage*>(p1));
        case IPC_CREATE_SHARED_MESSAGE:
            return createSharedMessage(reinterpret_cast<PedigreeIpc::IpcMessage*>(p1), static_cast<size_t>(p2), p3);
        case IPC_GET_SHARED_REGION:
            return reinterpret_cast<uintptr_t>(getIpcSharedRegion(reinterpret_cast<PedigreeIpc::IpcMessage*>(p1)));
        case IPC_DESTROY_MESSAGE:
            destroyMessage(reinterpret_cast<PedigreeIpc::IpcMessage*>(p1));
            break;

        case IPC_SEND_IPC:
            return static_cast<uintptr_t>(sendIpc(reinterpret_cast<PedigreeIpc::IpcEndpoint*>(p1),reinterpret_cast<PedigreeIpc::IpcMessage*>(p2), static_cast<bool>(p3)));
        case IPC_RECV_PHASE1:
            return reinterpret_cast<uintptr_t>(recvIpcPhase1(reinterpret_cast<PedigreeIpc::IpcEndpoint*>(p1), static_cast<bool>(p2)));
        case IPC_RECV_PHASE2:
            return recvIpcPhase2(reinterpret_cast<PedigreeIpc::IpcMessage*>(p1), reinterpret_cast<void*>(p2));

        case IPC_CREATE_ENDPOINT:
            createEndpoint(reinterpret_cast<const char *>(p1));
            break;
        case IPC_REMOVE_ENDPOINT:
            removeEndpoint(reinterpret_cast<const char *>(p1));
            break;
        case IPC_GET_ENDPOINT:
            return reinterpret_cast<uintptr_t>(getEndpoint(reinterpret_cast<const char *>(p1)));
            break;

        default: ERROR ("NativeSyscallManager: invalid syscall received: " << Dec << state.getSyscallNumber()); return 0;
    }

    return 0;
}
<|endoftext|>


<commit_before>#ifndef ENGINE_IGNITER_RENDERER_THREAD_CALLBABLE_BY_PLATFORM_HPP
#define ENGINE_IGNITER_RENDERER_THREAD_CALLBABLE_BY_PLATFORM_HPP
#pragma once

#include "../renderer_thread.hpp"

namespace engine
{

    namespace global
    {

        class renderer_thread_callable_by_platform_t : public renderer_thread_t
        {

        public:

        };

    }

}

#endif<commit_msg>Fixed typo in #ifndef header<commit_after>#ifndef ENGINE_IGNITER_RENDERER_THREAD_CALLABLE_BY_PLATFORM_HPP
#define ENGINE_IGNITER_RENDERER_THREAD_CALLABLE_BY_PLATFORM_HPP
#pragma once

#include "../renderer_thread.hpp"

namespace engine
{

    namespace global
    {

        class renderer_thread_callable_by_platform_t : public renderer_thread_t
        {

        public:

        };

    }

}

#endif<|endoftext|>


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

#ifndef RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_
#define RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_

#include <cassert>
#include <cstdlib>
#include <memory>
#include <vector>

#include <ros_middleware_interface/functions.h>
#include <ros_middleware_interface/handles.h>

#include <rclcpp/executor.hpp>
#include <rclcpp/macros.hpp>
#include <rclcpp/node.hpp>
#include <rclcpp/utilities.hpp>
#include <rclcpp/rate.hpp>

namespace rclcpp
{
namespace executors
{
namespace single_threaded_executor
{

class SingleThreadedExecutor : public executor::Executor
{
public:
  RCLCPP_MAKE_SHARED_DEFINITIONS(SingleThreadedExecutor);

  SingleThreadedExecutor() {}

  ~SingleThreadedExecutor() {}

  void spin()
  {
    while (rclcpp::utilities::ok())
    {
      auto any_exec = get_next_executable();
      execute_any_executable(any_exec);
    }
  }

  void spin_node_some(rclcpp::node::Node &node)
  {
    reset_subscriber_handles();
    populate_subscriber_handles_with_node(node);
    // non-blocking = true
    auto any_exec = get_next_executable(true);
    while (any_exec->subscription)
    {
      execute_subscription(any_exec->subscription);
      // non-blocking = true
      any_exec = get_next_executable(true);
    }
    reset_subscriber_handles();
  }

private:
  RCLCPP_DISABLE_COPY(SingleThreadedExecutor);

  std::vector<std::weak_ptr<rclcpp::node::Node>> weak_nodes_;

};

} /* namespace single_threaded_executor */
} /* namespace executors */
} /* namespace rclcpp */

#endif /* RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_ */
<commit_msg>STE: remove vestigial overlaid storage for nodes<commit_after>/* Copyright 2014 Open Source Robotics Foundation, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_
#define RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_

#include <cassert>
#include <cstdlib>
#include <memory>
#include <vector>

#include <ros_middleware_interface/functions.h>
#include <ros_middleware_interface/handles.h>

#include <rclcpp/executor.hpp>
#include <rclcpp/macros.hpp>
#include <rclcpp/node.hpp>
#include <rclcpp/utilities.hpp>
#include <rclcpp/rate.hpp>

namespace rclcpp
{
namespace executors
{
namespace single_threaded_executor
{

class SingleThreadedExecutor : public executor::Executor
{
public:
  RCLCPP_MAKE_SHARED_DEFINITIONS(SingleThreadedExecutor);

  SingleThreadedExecutor() {}

  ~SingleThreadedExecutor() {}

  void spin()
  {
    while (rclcpp::utilities::ok())
    {
      auto any_exec = get_next_executable();
      execute_any_executable(any_exec);
    }
  }

  void spin_node_some(rclcpp::node::Node &node)
  {
    reset_subscriber_handles();
    populate_subscriber_handles_with_node(node);
    // non-blocking = true
    auto any_exec = get_next_executable(true);
    while (any_exec->subscription)
    {
      execute_subscription(any_exec->subscription);
      // non-blocking = true
      any_exec = get_next_executable(true);
    }
    reset_subscriber_handles();
  }

private:
  RCLCPP_DISABLE_COPY(SingleThreadedExecutor);

};

} /* namespace single_threaded_executor */
} /* namespace executors */
} /* namespace rclcpp */

#endif /* RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_ */
<|endoftext|>


<commit_before>#include <threadPool/threadPool.h>
#include <gtest/gtest.h>

using namespace threadPool;

TEST(TestThreadPool, SimpleQueue) {
	std::atomic_int ct(0);

	ThreadPool<int> threadPool;
	threadPool.spawnThread([&ct](int) { ++ct; sleep(1); }, 5);

	for (int i(0); i<10; ++i) {
		threadPool.queue(0);
	}
	threadPool.wait();

	EXPECT_EQ(ct, 10);
}
TEST(TestThreadPool, SimpleQueue2) {
	for (int j(0); j<100; ++j) {
		std::atomic_int ct(0);
		ThreadPool<int> threadPool;
		threadPool.spawnThread([&ct](int) { ++ct; }, 5);

		for (int i(0); i<10; ++i) {
			threadPool.queue(0);
		}
		threadPool.wait();

		EXPECT_EQ(ct, 10);
	}
}

TEST(TestThreadPool, RecursiveQueue) {
	std::atomic_int ct(0);

	ThreadPool<int> threadPool;
	threadPool.spawnThread([&ct, &threadPool](int _ct) {
		++ct; sleep(1);
		if (_ct > 0)
			threadPool.queue(_ct-1);
	}, 5);

	for (int i(0); i<10; ++i) {
		threadPool.queue(1);
	}
	threadPool.wait();

	EXPECT_EQ(ct, 20);
}

TEST(TestThreadPool, RecursiveQueue2) {
	for (int j(0); j<100; ++j) {

		std::atomic_int ct(0);
		ThreadPool<int> threadPool;
		threadPool.spawnThread([&ct, &threadPool](int _ct) {
			++ct;
			if (_ct > 0)
				threadPool.queue(_ct-1);
		}, 5);

		for (int i(0); i<10; ++i) {
			threadPool.queue(1);
		}
		threadPool.wait();

		EXPECT_EQ(ct, 20);
	}
}

<commit_msg>removing sleeps for faster unit testing<commit_after>#include <threadPool/threadPool.h>
#include <gtest/gtest.h>

using namespace threadPool;

TEST(TestThreadPool, SimpleQueue) {
	std::atomic_int ct(0);

	ThreadPool<int> threadPool;
	threadPool.spawnThread([&ct](int) { ++ct; }, 5);

	for (int i(0); i<10; ++i) {
		threadPool.queue(0);
	}
	threadPool.wait();

	EXPECT_EQ(ct, 10);
}
TEST(TestThreadPool, SimpleQueue2) {
	for (int j(0); j<100; ++j) {
		std::atomic_int ct(0);
		ThreadPool<int> threadPool;
		threadPool.spawnThread([&ct](int) { ++ct; }, 5);

		for (int i(0); i<10; ++i) {
			threadPool.queue(0);
		}
		threadPool.wait();

		EXPECT_EQ(ct, 10);
	}
}

TEST(TestThreadPool, RecursiveQueue) {
	std::atomic_int ct(0);

	ThreadPool<int> threadPool;
	threadPool.spawnThread([&ct, &threadPool](int _ct) {
		++ct;
		if (_ct > 0)
			threadPool.queue(_ct-1);
	}, 5);

	for (int i(0); i<10; ++i) {
		threadPool.queue(1);
	}
	threadPool.wait();

	EXPECT_EQ(ct, 20);
}

TEST(TestThreadPool, RecursiveQueue2) {
	for (int j(0); j<100; ++j) {

		std::atomic_int ct(0);
		ThreadPool<int> threadPool;
		threadPool.spawnThread([&ct, &threadPool](int _ct) {
			++ct;
			if (_ct > 0)
				threadPool.queue(_ct-1);
		}, 5);

		for (int i(0); i<10; ++i) {
			threadPool.queue(1);
		}
		threadPool.wait();

		EXPECT_EQ(ct, 20);
	}
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AIndexes.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 02:13:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#ifndef _CONNECTIVITY_ADO_INDEXES_HXX_
#include "ado/AIndexes.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_INDEX_HXX_
#include "ado/AIndex.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_INDEXTYPE_HPP_
#include <com/sun/star/sdbc/IndexType.hpp>
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif

using namespace ::comphelper;

using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::container;

sdbcx::ObjectType OIndexes::createObject(const ::rtl::OUString& _rName)
{
    return new OAdoIndex(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));
}
// -------------------------------------------------------------------------
void OIndexes::impl_refresh() throw(RuntimeException)
{
    m_aCollection.Refresh();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OIndexes::createDescriptor()
{
    return new OAdoIndex(isCaseSensitive(),m_pConnection);
}
// -------------------------------------------------------------------------
// XAppend
sdbcx::ObjectType OIndexes::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )
{
    OAdoIndex* pIndex = NULL;
    if ( !getImplementation(pIndex,descriptor) || pIndex == NULL )
        ::dbtools::throwGenericSQLException(
            ::rtl::OUString::createFromAscii( "Could not create index: invalid object descriptor." ),
            static_cast<XTypeProvider*>(this)
        );

    ADOIndexes* pIndexes = m_aCollection;
    if ( FAILED( pIndexes->Append( OLEVariant( _rForName ), OLEVariant( pIndex->getImpl() ) ) ) )
    {
        ADOS::ThrowException(*m_pConnection->getConnection(),static_cast<XTypeProvider*>(this));
        ::dbtools::throwGenericSQLException(
            ::rtl::OUString::createFromAscii( "Could not append index." ),
            static_cast<XTypeProvider*>(this)
        );
    }

    return new OAdoIndex(isCaseSensitive(),m_pConnection,pIndex->getImpl());
}
// -------------------------------------------------------------------------
// XDrop
void OIndexes::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
    m_aCollection.Delete(_sElementName);
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS changefileheader (1.16.216); FILE MERGED 2008/04/01 15:08:36 thb 1.16.216.3: #i85898# Stripping all external header guards 2008/04/01 10:52:49 thb 1.16.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:26 rt 1.16.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: AIndexes.cxx,v $
 * $Revision: 1.17 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "ado/AIndexes.hxx"
#include "ado/AIndex.hxx"
#include "ado/AConnection.hxx"
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdbc/IndexType.hpp>
#include "TConnection.hxx"
#include <comphelper/types.hxx>
#include <connectivity/dbexception.hxx>

using namespace ::comphelper;

using namespace connectivity;
using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::container;

sdbcx::ObjectType OIndexes::createObject(const ::rtl::OUString& _rName)
{
    return new OAdoIndex(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));
}
// -------------------------------------------------------------------------
void OIndexes::impl_refresh() throw(RuntimeException)
{
    m_aCollection.Refresh();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OIndexes::createDescriptor()
{
    return new OAdoIndex(isCaseSensitive(),m_pConnection);
}
// -------------------------------------------------------------------------
// XAppend
sdbcx::ObjectType OIndexes::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )
{
    OAdoIndex* pIndex = NULL;
    if ( !getImplementation(pIndex,descriptor) || pIndex == NULL )
        ::dbtools::throwGenericSQLException(
            ::rtl::OUString::createFromAscii( "Could not create index: invalid object descriptor." ),
            static_cast<XTypeProvider*>(this)
        );

    ADOIndexes* pIndexes = m_aCollection;
    if ( FAILED( pIndexes->Append( OLEVariant( _rForName ), OLEVariant( pIndex->getImpl() ) ) ) )
    {
        ADOS::ThrowException(*m_pConnection->getConnection(),static_cast<XTypeProvider*>(this));
        ::dbtools::throwGenericSQLException(
            ::rtl::OUString::createFromAscii( "Could not append index." ),
            static_cast<XTypeProvider*>(this)
        );
    }

    return new OAdoIndex(isCaseSensitive(),m_pConnection,pIndex->getImpl());
}
// -------------------------------------------------------------------------
// XDrop
void OIndexes::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
    m_aCollection.Delete(_sElementName);
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>#include <aleph/math/SymmetricMatrix.hh>

#include <aleph/persistenceDiagrams/Distances.hh>
#include <aleph/persistenceDiagrams/Norms.hh>
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>

#include <aleph/topology/filtrations/Data.hh>

#include <aleph/topology/io/BipartiteAdjacencyMatrix.hh>

#include <algorithm>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>

#include <getopt.h>

// These declarations should remain global because we have to refer to
// them in utility functions that are living outside of `main()`.
using DataType          = double;
using VertexType        = unsigned short;
using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

SimplicialComplex makeFiltration( const SimplicialComplex& K, bool upper = false )
{
  std::vector<Simplex> simplices;
  simplices.reserve( K.size() );

  std::transform( K.begin(), K.end(), std::back_inserter( simplices ),
    [&upper] ( const Simplex& s )
    {
      if( ( upper && s.data() > DataType() ) || ( !upper && s.data() < DataType() ) )
        return s;

      // Copy the simplex but set its weight to be zero because it does
      // not correspond to any structure that we want to learn.
      else
      {
        std::vector<VertexType> vertices( s.begin(), s.end() );
        return Simplex( s.begin(), s.end(), DataType() );
      }
    }
  );

  return SimplicialComplex( simplices.begin(), simplices.end() );
}

SimplicialComplex makeLowerFiltration( const SimplicialComplex& K )
{
  auto L = makeFiltration( K );
  L.sort(
    aleph::topology::filtrations::Data<Simplex, std::greater<DataType> >()
  );

  return L;
}

SimplicialComplex makeUpperFiltration( const SimplicialComplex& K )
{
  auto L = makeFiltration( K, true );
  L.sort(
    aleph::topology::filtrations::Data<Simplex, std::less<DataType> >()
  );

  return makeFiltration( K, true );
}

using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
using Point              = typename PersistenceDiagram::Point;

PersistenceDiagram merge( const PersistenceDiagram& D, const PersistenceDiagram& E )
{
  PersistenceDiagram F;

  if( D.dimension() != F.dimension() )
    throw std::runtime_error( "Persistence diagram dimensions have to agree" );

  for( auto&& diagram : { D, E } )
    for( auto&& p : diagram )
      F.add( p.x(), p.y() );

  return F;
}

int main( int argc, char** argv )
{
  bool absolute              = false;
  bool cycles                = false;
  bool minimum               = false;
  bool normalize             = false;
  bool calculateDiagrams     = false;
  bool calculateTrajectories = false;

  {
    static option commandLineOptions[] =
    {
      { "absolute"            , no_argument, nullptr, 'a' },
      { "cycles"              , no_argument, nullptr, 'c' },
      { "minimum"             , no_argument, nullptr, 'm' },
      { "normalize"           , no_argument, nullptr, 'n' },
      { "persistence-diagrams", no_argument, nullptr, 'p' },
      { "trajectories"        , no_argument, nullptr, 't' },
      { nullptr               , 0          , nullptr,  0  }
    };

    int option = 0;
    while( ( option = getopt_long( argc, argv, "acmnpt", commandLineOptions, nullptr ) ) != -1 )
    {
      switch( option )
      {
      case 'a':
        absolute = true;
        break;
      case 'c':
        cycles = true;
        break;
      case 'm':
        minimum = true;
        break;
      case 'n':
        normalize = true;
        break;
      case 'p':
        calculateDiagrams = true;
        break;
      case 't':
        calculateTrajectories = true;
        break;
      default:
        break;
      }
    }
  }

  // 1. Read simplicial complexes --------------------------------------

  std::vector<SimplicialComplex> simplicialComplexes;
  simplicialComplexes.reserve( static_cast<unsigned>( argc - optind - 1 ) );

  std::vector<DataType> minData;
  std::vector<DataType> maxData;

  minData.reserve( simplicialComplexes.size() );
  maxData.reserve( simplicialComplexes.size() );

  {
    aleph::topology::io::BipartiteAdjacencyMatrixReader reader;

    if( absolute )
      reader.setUseAbsoluteValues();

    if( minimum )
      reader.setAssignMinimumVertexWeight();

    for( int i = optind; i < argc; i++ )
    {
      auto filename = std::string( argv[i] );

      std::cerr << "* Processing " << filename << "...";

      SimplicialComplex K;
      reader( filename, K );

      std::cerr << "finished\n";

      DataType minData_ = std::numeric_limits<DataType>::max();
      DataType maxData_ = std::numeric_limits<DataType>::lowest();

      // *Always* determine minimum and maximum weights so that we may
      // report them later on. They are only used for normalization in
      // the persistence diagram calculation step.
      for( auto&& s : K )
      {
        minData_ = std::min( minData_, s.data() );
        maxData_ = std::max( maxData_, s.data() );
      }

      minData.push_back( minData_ );
      maxData.push_back( maxData_ );

      simplicialComplexes.emplace_back( K );
    }
  }

  // 2. Calculate persistent homology ----------------------------------

  using Matrix = aleph::math::SymmetricMatrix<double>;

  // Stores the distance matrix for the trajectories of persistence
  // diagrams. This will only be used if the client set the correct
  // flag.
  Matrix trajectoryDistances;
  if( calculateTrajectories )
    trajectoryDistances = Matrix( simplicialComplexes.size() );

  using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
  using Point              = typename PersistenceDiagram::Point;

  // Stores the zeroth persistence diagram for calculating trajectories
  // later on. This may need to be extended in order to handle diagrams
  // with higher-dimensional features.
  std::vector<PersistenceDiagram> trajectoryDiagrams;
  if( calculateTrajectories )
    trajectoryDiagrams.reserve( simplicialComplexes.size() );

  for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )
  {
    bool dualize                    = true;
    bool includeAllUnpairedCreators = cycles;

    auto&& K      = simplicialComplexes[i];
    auto diagrams = aleph::calculatePersistenceDiagrams(
      K,
      dualize,
      includeAllUnpairedCreators
    );
    auto&& D      = diagrams.back(); // always use the last diagram; in the
                                     // absence of another mechanism,  this
                                     // will always give us the features in
                                     // the highest dimension.

    D.removeDiagonal();
    if( !cycles )
      D.removeUnpaired();

    if( normalize )
    {
      // Ensures that points are in [-1:+1] or [0:1] if absolute values
      // have been selected by the client.
      std::transform( D.begin(), D.end(), D.begin(),
        [&absolute, &i, &minData, &maxData] ( const Point& p )
        {
          auto x = p.x();
          auto y = p.y();

          if( absolute )
          {
            x = (x - minData[i]) / (maxData[i] - minData[i]);
            y = (y - minData[i]) / (maxData[i] - minData[i]);
          }
          else
          {
            x = 2 * (x - minData[i]) / (maxData[i] - minData[i]) - 1;
            y = 2 * (y - minData[i]) / (maxData[i] - minData[i]) - 1;
          }

          return Point( x,y );
        }
      );
    }

    if( cycles )
    {
      std::transform( D.begin(), D.end(), D.begin(),
        [] ( const Point& p )
        {
          auto x = p.x();
          auto y = DataType();

          return Point( x,y );
        }
      );
    }

    // Determine mode of operation -------------------------------------
    //
    // Several modes of operation exist for this program. They can be
    // set using the flags specified above. At present, the following
    // operations are possible:
    //
    // - Calculate persistence diagrams
    // - Calculate persistence diagram trajectories
    // - Calculate 2-norm of the persistence diagrams

    if( calculateDiagrams )
      std::cout << D << "\n\n";
    else if( calculateTrajectories )
      trajectoryDiagrams.push_back( D );
    else
      std::cout << i << "\t" << aleph::pNorm( D ) << "\n";
  }

  // Need to calculate the trajectories afterwards because they require
  // building a database of persistence diagrams.
  if( calculateTrajectories )
  {
    for( std::size_t i = 0; i < trajectoryDiagrams.size(); i++ )
    {
      auto&& Di = trajectoryDiagrams[i];

      for( std::size_t j = i+1; j < trajectoryDiagrams.size(); j++ )
      {
        auto&& Dj = trajectoryDiagrams[j];
        auto dist = aleph::distances::hausdorffDistance(
          Di, Dj
        );

        trajectoryDistances(i,j) = dist;
      }
    }

    // FIXME: replace with proper layout
    std::cout << trajectoryDistances;
  }
}
<commit_msg>Added support for merged persistence diagrams<commit_after>#include <aleph/math/SymmetricMatrix.hh>

#include <aleph/persistenceDiagrams/Distances.hh>
#include <aleph/persistenceDiagrams/Norms.hh>
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>

#include <aleph/topology/filtrations/Data.hh>

#include <aleph/topology/io/BipartiteAdjacencyMatrix.hh>

#include <algorithm>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>

#include <getopt.h>

// These declarations should remain global because we have to refer to
// them in utility functions that are living outside of `main()`.
using DataType          = double;
using VertexType        = unsigned short;
using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

SimplicialComplex makeFiltration( const SimplicialComplex& K, bool upper = false )
{
  std::vector<Simplex> simplices;
  simplices.reserve( K.size() );

  std::transform( K.begin(), K.end(), std::back_inserter( simplices ),
    [&upper] ( const Simplex& s )
    {
      if( ( upper && s.data() > DataType() ) || ( !upper && s.data() < DataType() ) )
        return s;

      // Copy the simplex but set its weight to be zero because it does
      // not correspond to any structure that we want to learn.
      else
      {
        std::vector<VertexType> vertices( s.begin(), s.end() );
        return Simplex( s.begin(), s.end(), DataType() );
      }
    }
  );

  return SimplicialComplex( simplices.begin(), simplices.end() );
}

SimplicialComplex makeLowerFiltration( const SimplicialComplex& K )
{
  auto L = makeFiltration( K );
  L.sort(
    aleph::topology::filtrations::Data<Simplex, std::greater<DataType> >()
  );

  return L;
}

SimplicialComplex makeUpperFiltration( const SimplicialComplex& K )
{
  auto L = makeFiltration( K, true );
  L.sort(
    aleph::topology::filtrations::Data<Simplex, std::less<DataType> >()
  );

  return makeFiltration( K, true );
}

using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
using Point              = typename PersistenceDiagram::Point;

PersistenceDiagram merge( const PersistenceDiagram& D, const PersistenceDiagram& E )
{
  PersistenceDiagram F;

  if( D.dimension() != F.dimension() )
    throw std::runtime_error( "Persistence diagram dimensions have to agree" );

  for( auto&& diagram : { D, E } )
    for( auto&& p : diagram )
      F.add( p.x(), p.y() );

  return F;
}

int main( int argc, char** argv )
{
  bool absolute              = false;
  bool cycles                = false;
  bool filtration            = false;
  bool minimum               = false;
  bool normalize             = false;
  bool calculateDiagrams     = false;
  bool calculateTrajectories = false;

  {
    static option commandLineOptions[] =
    {
      { "absolute"            , no_argument, nullptr, 'a' },
      { "cycles"              , no_argument, nullptr, 'c' },
      { "filtration"          , no_argument, nullptr, 'f' },
      { "minimum"             , no_argument, nullptr, 'm' },
      { "normalize"           , no_argument, nullptr, 'n' },
      { "persistence-diagrams", no_argument, nullptr, 'p' },
      { "trajectories"        , no_argument, nullptr, 't' },
      { nullptr               , 0          , nullptr,  0  }
    };

    int option = 0;
    while( ( option = getopt_long( argc, argv, "acfmnpt", commandLineOptions, nullptr ) ) != -1 )
    {
      switch( option )
      {
      case 'a':
        absolute = true;
        break;
      case 'c':
        cycles = true;
        break;
      case 'f':
        filtration = true;
        break;
      case 'm':
        minimum = true;
        break;
      case 'n':
        normalize = true;
        break;
      case 'p':
        calculateDiagrams = true;
        break;
      case 't':
        calculateTrajectories = true;
        break;
      default:
        break;
      }
    }
  }

  // 1. Read simplicial complexes --------------------------------------

  std::vector<SimplicialComplex> simplicialComplexes;
  simplicialComplexes.reserve( static_cast<unsigned>( argc - optind - 1 ) );

  std::vector<DataType> minData;
  std::vector<DataType> maxData;

  minData.reserve( simplicialComplexes.size() );
  maxData.reserve( simplicialComplexes.size() );

  {
    aleph::topology::io::BipartiteAdjacencyMatrixReader reader;

    if( absolute )
      reader.setUseAbsoluteValues();

    if( minimum )
      reader.setAssignMinimumVertexWeight();

    for( int i = optind; i < argc; i++ )
    {
      auto filename = std::string( argv[i] );

      std::cerr << "* Processing " << filename << "...";

      SimplicialComplex K;
      reader( filename, K );

      std::cerr << "finished\n";

      DataType minData_ = std::numeric_limits<DataType>::max();
      DataType maxData_ = std::numeric_limits<DataType>::lowest();

      // *Always* determine minimum and maximum weights so that we may
      // report them later on. They are only used for normalization in
      // the persistence diagram calculation step.
      for( auto&& s : K )
      {
        minData_ = std::min( minData_, s.data() );
        maxData_ = std::max( maxData_, s.data() );
      }

      minData.push_back( minData_ );
      maxData.push_back( maxData_ );

      simplicialComplexes.emplace_back( K );
    }
  }

  // 2. Calculate persistent homology ----------------------------------

  using Matrix = aleph::math::SymmetricMatrix<double>;

  // Stores the distance matrix for the trajectories of persistence
  // diagrams. This will only be used if the client set the correct
  // flag.
  Matrix trajectoryDistances;
  if( calculateTrajectories )
    trajectoryDistances = Matrix( simplicialComplexes.size() );

  // Stores the zeroth persistence diagram for calculating trajectories
  // later on. This may need to be extended in order to handle diagrams
  // with higher-dimensional features.
  std::vector<PersistenceDiagram> trajectoryDiagrams;
  if( calculateTrajectories )
    trajectoryDiagrams.reserve( simplicialComplexes.size() );

  for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )
  {
    // The persistence diagram that will be used in the subsequent
    // analysis. This does not necessarily have to stem from data,
    // but can be calculated from a suitable transformation.
    PersistenceDiagram D;

    bool dualize                    = true;
    bool includeAllUnpairedCreators = cycles;

    auto&& K                        = simplicialComplexes[i];

    if( filtration )
    {
      auto L = makeLowerFiltration( K );
      auto U = makeUpperFiltration( K );

      auto lowerDiagrams = aleph::calculatePersistenceDiagrams(
        L,
        dualize,
        includeAllUnpairedCreators
      );

      auto upperDiagrams = aleph::calculatePersistenceDiagrams(
        U,
        dualize,
        includeAllUnpairedCreators
      );

      D = merge( lowerDiagrams.back(), upperDiagrams.back() );
    }
    else
    {
      auto diagrams = aleph::calculatePersistenceDiagrams(
        K,
        dualize,
        includeAllUnpairedCreators
      );

      D = diagrams.back(); // Use the *last* diagram of the filtration so that
                           // we get features in the highest dimension.
    }

    D.removeDiagonal();
    if( !cycles )
      D.removeUnpaired();

    if( normalize )
    {
      // Ensures that points are in [-1:+1] or [0:1] if absolute values
      // have been selected by the client.
      std::transform( D.begin(), D.end(), D.begin(),
        [&absolute, &i, &minData, &maxData] ( const Point& p )
        {
          auto x = p.x();
          auto y = p.y();

          if( absolute )
          {
            x = (x - minData[i]) / (maxData[i] - minData[i]);
            y = (y - minData[i]) / (maxData[i] - minData[i]);
          }
          else
          {
            x = 2 * (x - minData[i]) / (maxData[i] - minData[i]) - 1;
            y = 2 * (y - minData[i]) / (maxData[i] - minData[i]) - 1;
          }

          return Point( x,y );
        }
      );
    }

    if( cycles )
    {
      std::transform( D.begin(), D.end(), D.begin(),
        [] ( const Point& p )
        {
          auto x = p.x();
          auto y = DataType();

          return Point( x,y );
        }
      );
    }

    // Determine mode of operation -------------------------------------
    //
    // Several modes of operation exist for this program. They can be
    // set using the flags specified above. At present, the following
    // operations are possible:
    //
    // - Calculate persistence diagrams
    // - Calculate persistence diagram trajectories
    // - Calculate 2-norm of the persistence diagrams

    if( calculateDiagrams )
      std::cout << D << "\n\n";
    else if( calculateTrajectories )
      trajectoryDiagrams.push_back( D );
    else
      std::cout << i << "\t" << aleph::pNorm( D ) << "\n";
  }

  // Need to calculate the trajectories afterwards because they require
  // building a database of persistence diagrams.
  if( calculateTrajectories )
  {
    for( std::size_t i = 0; i < trajectoryDiagrams.size(); i++ )
    {
      auto&& Di = trajectoryDiagrams[i];

      for( std::size_t j = i+1; j < trajectoryDiagrams.size(); j++ )
      {
        auto&& Dj = trajectoryDiagrams[j];
        auto dist = aleph::distances::hausdorffDistance(
          Di, Dj
        );

        trajectoryDistances(i,j) = dist;
      }
    }

    // FIXME: replace with proper layout
    std::cout << trajectoryDistances;
  }
}
<|endoftext|>