<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#ifndef _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_
#define _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_  1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

#include    <type_traits>

#include    "../Math/Common.h"
#include    "../Execution/Exceptions.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   DataExchangeFormat {

            /*
             ********************************************************************************
             *********************** DataExchangeFormat::Private_ ***************************
             ********************************************************************************
             */
            namespace Private_ {
                template    <typename T>
                inline  typename std::enable_if < !std::is_floating_point<T>::value, T >::type CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
                {
                    return t;
                }
                template    <typename T>
                inline  typename std::enable_if<std::is_floating_point<T>::value, T>::type  CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
                {
                    if (Math::NearlyEquals (t, lower)) {
                        return lower;
                    }
                    if (Math::NearlyEquals (t, upper)) {
                        return upper;
                    }
                    return t;
                }
            }

            /*
             ********************************************************************************
             ************** DataExchangeFormat::CheckedConverter_Range **********************
             ********************************************************************************
             */
            template    <typename   RANGE_TYPE>
            RANGE_TYPE  CheckedConverter_Range (const typename RANGE_TYPE::ElementType& s, const typename RANGE_TYPE::ElementType& e)
            {
                typename    RANGE_TYPE::ElementType useS    =   Private_::CheckedConverter_Range_Helper_Pinner_ (s, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
                typename    RANGE_TYPE::ElementType useE    =   Private_::CheckedConverter_Range_Helper_Pinner_ (e, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
                if (not (RANGE_TYPE::TraitsType::kMin <= useS)) {
                    Execution::DoThrow (BadFormatException ());
                }
                if (not (useS <= useE)) {
                    Execution::DoThrow (BadFormatException ());
                }
                if (not (useE <= RANGE_TYPE::TraitsType::kMax)) {
                    Execution::DoThrow (BadFormatException ());
                }
                return RANGE_TYPE (useS, useE);
            }

            /*
             ********************************************************************************
             ********* DataExchangeFormat::CheckedConverter_ValueInRange ********************
             ********************************************************************************
             */
            template    <typename   RANGE_TYPE>
            typename RANGE_TYPE::ElementType  CheckedConverter_ValueInRange (typename RANGE_TYPE::ElementType val, const RANGE_TYPE& r)
            {
                typename    RANGE_TYPE::ElementType useVal    =   Private_::CheckedConverter_Range_Helper_Pinner_ (val, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
                if (not (RANGE_TYPE::TraitsType::kMin <= useVal)) {
                    Execution::DoThrow (BadFormatException ());
                }
                if (not (useVal <= RANGE_TYPE::TraitsType::kMax)) {
                    Execution::DoThrow (BadFormatException ());
                }
                return useVal;
            }

        }

    }
}
#endif  /*_Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_*/
<commit_msg>use new Math::PinToSpecialPoint () in DataExchangeFormat/CheckedConverter<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#ifndef _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_
#define _Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_  1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

#include    <type_traits>

#include    "../Math/Common.h"
#include    "../Execution/Exceptions.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   DataExchangeFormat {

            /*
             ********************************************************************************
             *********************** DataExchangeFormat::Private_ ***************************
             ********************************************************************************
             */
            namespace Private_ {
                template    <typename T>
                inline  typename std::enable_if < !std::is_floating_point<T>::value, T >::type CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
                {
                    return t;
                }
                template    <typename T>
                inline  typename std::enable_if<std::is_floating_point<T>::value, T>::type  CheckedConverter_Range_Helper_Pinner_ (T t, T lower, T upper)
                {
                    return Math::PinToSpecialPoint (PinToSpecialPoint (t, lower), upper);
                }
            }

            /*
             ********************************************************************************
             ************** DataExchangeFormat::CheckedConverter_Range **********************
             ********************************************************************************
             */
            template    <typename   RANGE_TYPE>
            RANGE_TYPE  CheckedConverter_Range (const typename RANGE_TYPE::ElementType& s, const typename RANGE_TYPE::ElementType& e)
            {
                typename    RANGE_TYPE::ElementType useS    =   Private_::CheckedConverter_Range_Helper_Pinner_ (s, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
                typename    RANGE_TYPE::ElementType useE    =   Private_::CheckedConverter_Range_Helper_Pinner_ (e, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
                if (not (RANGE_TYPE::TraitsType::kMin <= useS)) {
                    Execution::DoThrow (BadFormatException ());
                }
                if (not (useS <= useE)) {
                    Execution::DoThrow (BadFormatException ());
                }
                if (not (useE <= RANGE_TYPE::TraitsType::kMax)) {
                    Execution::DoThrow (BadFormatException ());
                }
                return RANGE_TYPE (useS, useE);
            }

            /*
             ********************************************************************************
             ********* DataExchangeFormat::CheckedConverter_ValueInRange ********************
             ********************************************************************************
             */
            template    <typename   RANGE_TYPE>
            typename RANGE_TYPE::ElementType  CheckedConverter_ValueInRange (typename RANGE_TYPE::ElementType val, const RANGE_TYPE& r)
            {
                typename    RANGE_TYPE::ElementType useVal    =   Private_::CheckedConverter_Range_Helper_Pinner_ (val, RANGE_TYPE::TraitsType::kMin, RANGE_TYPE::TraitsType::kMax);
                if (not (RANGE_TYPE::TraitsType::kMin <= useVal)) {
                    Execution::DoThrow (BadFormatException ());
                }
                if (not (useVal <= RANGE_TYPE::TraitsType::kMax)) {
                    Execution::DoThrow (BadFormatException ());
                }
                return useVal;
            }

        }

    }
}
#endif  /*_Stroika_Foundation_DataExchangeFormat_CheckedConverter_inl_*/
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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_desktop.hxx"

#include "dp_misc.h"
#include "dp_platform.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/instance.hxx"
#include "rtl/bootstrap.hxx"

#define PLATFORM_ALL                "all"
#define PLATFORM_WIN_X86            "windows_x86"
#define PLATFORM_LINUX_X86          "linux_x86"
#define PLATFORM_LINUX_X86_64       "linux_x86_64"
#define PLATFORM_LINUX_SPARC        "linux_sparc"
#define PLATFORM_LINUX_POWERPC      "linux_powerpc"
#define PLATFORM_LINUX_POWERPC64    "linux_powerpc64"
#define PLATFORM_LINUX_ARM_EABI     "linux_arm_eabi"
#define PLATFORM_LINUX_ARM_OABI     "linux_arm_oabi"
#define PLATFORM_LINUX_MIPS_EL      "linux_mips_el"
#define PLATFORM_LINUX_MIPS_EB      "linux_mips_eb"
#define PLATFORM_LINUX_IA64         "linux_ia64"
#define PLATFORM_LINUX_S390         "linux_s390"
#define PLATFORM_LINUX_S390x        "linux_s390x"

#define PLATFORM_SOLARIS_SPARC      "solaris_sparc"
#define PLATFORM_SOLARIS_SPARC64    "solaris_sparc64"
#define PLATFORM_SOLARIS_X86        "solaris_x86"
#define PLATFORM_FREEBSD_X86        "freebsd_x86"
#define PLATFORM_FREEBSD_X86_64     "freebsd_x86_64"
#define PLATFORM_MACOSX_X86         "macosx_x86"
#define PLATFORM_MACOSX_PPC         "macosx_powerpc"
#define PLATFORM_OS2_X86            "os2_x86"

#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using ::rtl::OUString;
namespace css = ::com::sun::star;

namespace dp_misc
{
namespace
{
    struct StrOperatingSystem :
        public rtl::StaticWithInit<const OUString, StrOperatingSystem> {
            const OUString operator () () {
                OUString os( RTL_CONSTASCII_USTRINGPARAM("$_OS") );
                ::rtl::Bootstrap::expandMacros( os );
                return os;
            }
    };

    struct StrCPU :
        public rtl::StaticWithInit<const OUString, StrCPU> {
            const OUString operator () () {
                OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
                ::rtl::Bootstrap::expandMacros( arch );
                return arch;
            }
    };

    struct StrPlatform : public rtl::StaticWithInit<
        const OUString, StrPlatform> {
            const OUString operator () () {
                ::rtl::OUStringBuffer buf;
                buf.append( StrOperatingSystem::get() );
                buf.append( static_cast<sal_Unicode>('_') );
                OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
                ::rtl::Bootstrap::expandMacros( arch );
                buf.append( arch );
                return buf.makeStringAndClear();
            }
    };

    bool checkOSandCPU(OUString const & os, OUString const & cpu)
    {
        return os.equals(StrOperatingSystem::get())
            && cpu.equals(StrCPU::get());
    }

    bool isValidPlatform(OUString const &  token )
    {
        bool ret = false;
        if (token.equals(OUSTR(PLATFORM_ALL)))
            ret = true;
        else if (token.equals(OUSTR(PLATFORM_WIN_X86)))
            ret = checkOSandCPU(OUSTR("Windows"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_X86)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_X86_64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_SPARC)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("SPARC"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC_64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_EABI)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_EABI"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_OABI)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_OABI"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EL)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EL"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EB)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EB"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_IA64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("IA64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_S390)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_S390x)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390x"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC64)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC64"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_X86)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86)))
            ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86_64)))
            ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_MACOSX_X86)))
            ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_MACOSX_PPC)))
            ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("PowerPC"));
        else if (token.equals(OUSTR(PLATFORM_OS2_X86)))
            ret = checkOSandCPU(OUSTR("OS2"), OUSTR("x86"));
        else
        {
            OSL_ENSURE(0, "Extension Manager: The extension supports an unknown platform. "
            "Check the platform element in the descripion.xml");
            ret = false;
        }
        return ret;
    }

} // anon namespace
//=============================================================================

OUString const & getPlatformString()
{
    return StrPlatform::get();
}

bool platform_fits( OUString const & platform_string )
{
    sal_Int32 index = 0;
    for (;;)
    {
        const OUString token(
            platform_string.getToken( 0, ',', index ).trim() );
        // check if this platform:
        if (token.equalsIgnoreAsciiCase( StrPlatform::get() ) ||
            (token.indexOf( '_' ) < 0 && /* check OS part only */
             token.equalsIgnoreAsciiCase( StrOperatingSystem::get() )))
        {
            return true;
        }
        if (index < 0)
            break;
    }
    return false;
}

bool hasValidPlatform( css::uno::Sequence<OUString> const & platformStrings)
{
    bool ret = false;
    for (sal_Int32 i  = 0; i < platformStrings.getLength(); i++)
    {
        if (isValidPlatform(platformStrings[i]))
        {
            ret = true;
            break;
        }
    }
    return ret;
}

}

<commit_msg>linuxaxp01: #i110145# yet another hard-coded list to fall over<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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_desktop.hxx"

#include "dp_misc.h"
#include "dp_platform.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/instance.hxx"
#include "rtl/bootstrap.hxx"

#define PLATFORM_ALL                "all"
#define PLATFORM_WIN_X86            "windows_x86"
#define PLATFORM_LINUX_X86          "linux_x86"
#define PLATFORM_LINUX_X86_64       "linux_x86_64"
#define PLATFORM_LINUX_SPARC        "linux_sparc"
#define PLATFORM_LINUX_POWERPC      "linux_powerpc"
#define PLATFORM_LINUX_POWERPC64    "linux_powerpc64"
#define PLATFORM_LINUX_ARM_EABI     "linux_arm_eabi"
#define PLATFORM_LINUX_ARM_OABI     "linux_arm_oabi"
#define PLATFORM_LINUX_MIPS_EL      "linux_mips_el"
#define PLATFORM_LINUX_MIPS_EB      "linux_mips_eb"
#define PLATFORM_LINUX_IA64         "linux_ia64"
#define PLATFORM_LINUX_S390         "linux_s390"
#define PLATFORM_LINUX_S390x        "linux_s390x"
#define PLATFORM_LINUX_HPPA         "linux_hppa"
#define PLATFORM_LINUX_ALPHA        "linux_alpha"

#define PLATFORM_SOLARIS_SPARC      "solaris_sparc"
#define PLATFORM_SOLARIS_SPARC64    "solaris_sparc64"
#define PLATFORM_SOLARIS_X86        "solaris_x86"
#define PLATFORM_FREEBSD_X86        "freebsd_x86"
#define PLATFORM_FREEBSD_X86_64     "freebsd_x86_64"
#define PLATFORM_MACOSX_X86         "macosx_x86"
#define PLATFORM_MACOSX_PPC         "macosx_powerpc"
#define PLATFORM_OS2_X86            "os2_x86"

#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using ::rtl::OUString;
namespace css = ::com::sun::star;

namespace dp_misc
{
namespace
{
    struct StrOperatingSystem :
        public rtl::StaticWithInit<const OUString, StrOperatingSystem> {
            const OUString operator () () {
                OUString os( RTL_CONSTASCII_USTRINGPARAM("$_OS") );
                ::rtl::Bootstrap::expandMacros( os );
                return os;
            }
    };

    struct StrCPU :
        public rtl::StaticWithInit<const OUString, StrCPU> {
            const OUString operator () () {
                OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
                ::rtl::Bootstrap::expandMacros( arch );
                return arch;
            }
    };

    struct StrPlatform : public rtl::StaticWithInit<
        const OUString, StrPlatform> {
            const OUString operator () () {
                ::rtl::OUStringBuffer buf;
                buf.append( StrOperatingSystem::get() );
                buf.append( static_cast<sal_Unicode>('_') );
                OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
                ::rtl::Bootstrap::expandMacros( arch );
                buf.append( arch );
                return buf.makeStringAndClear();
            }
    };

    bool checkOSandCPU(OUString const & os, OUString const & cpu)
    {
        return os.equals(StrOperatingSystem::get())
            && cpu.equals(StrCPU::get());
    }

    bool isValidPlatform(OUString const &  token )
    {
        bool ret = false;
        if (token.equals(OUSTR(PLATFORM_ALL)))
            ret = true;
        else if (token.equals(OUSTR(PLATFORM_WIN_X86)))
            ret = checkOSandCPU(OUSTR("Windows"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_X86)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_X86_64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_SPARC)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("SPARC"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC_64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_EABI)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_EABI"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_OABI)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_OABI"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EL)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EL"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EB)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EB"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_IA64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("IA64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_S390)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_S390x)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390x"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_HPPA)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("HPPA"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ALPHA)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ALPHA"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC64)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC64"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_X86)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86)))
            ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86_64)))
            ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_MACOSX_X86)))
            ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_MACOSX_PPC)))
            ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("PowerPC"));
        else if (token.equals(OUSTR(PLATFORM_OS2_X86)))
            ret = checkOSandCPU(OUSTR("OS2"), OUSTR("x86"));
        else
        {
            OSL_ENSURE(0, "Extension Manager: The extension supports an unknown platform. "
            "Check the platform element in the descripion.xml");
            ret = false;
        }
        return ret;
    }

} // anon namespace
//=============================================================================

OUString const & getPlatformString()
{
    return StrPlatform::get();
}

bool platform_fits( OUString const & platform_string )
{
    sal_Int32 index = 0;
    for (;;)
    {
        const OUString token(
            platform_string.getToken( 0, ',', index ).trim() );
        // check if this platform:
        if (token.equalsIgnoreAsciiCase( StrPlatform::get() ) ||
            (token.indexOf( '_' ) < 0 && /* check OS part only */
             token.equalsIgnoreAsciiCase( StrOperatingSystem::get() )))
        {
            return true;
        }
        if (index < 0)
            break;
    }
    return false;
}

bool hasValidPlatform( css::uno::Sequence<OUString> const & platformStrings)
{
    bool ret = false;
    for (sal_Int32 i  = 0; i < platformStrings.getLength(); i++)
    {
        if (isValidPlatform(platformStrings[i]))
        {
            ret = true;
            break;
        }
    }
    return ret;
}

}

<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#ifndef _Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_
#define _Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_    1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
namespace   Stroika {
    namespace   Foundation {
        namespace   IO {
            namespace   FileSystem {

                /*
                 ********************************************************************************
                 ***************************** Implementation Details ***************************
                 ********************************************************************************
                 */
                inline  Streams::BinaryInputStream   BinaryFileInputStream::mk (const String& fileName, BufferFlag bufferFlag)
                {
                    return mk (fileName, eSeekable, bufferFlag);
                }

            }
        }
    }
}
#endif  /*_Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_*/
<commit_msg>Comments<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#ifndef _Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_
#define _Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_    1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
namespace   Stroika {
    namespace   Foundation {
        namespace   IO {
            namespace   FileSystem {

                /*
                 ********************************************************************************
                 ********************************** BinaryInputStream ***************************
                 ********************************************************************************
                 */
                inline  Streams::BinaryInputStream   BinaryFileInputStream::mk (const String& fileName, BufferFlag bufferFlag)
                {
                    return mk (fileName, eSeekable, bufferFlag);
                }

            }
        }
    }
}
#endif  /*_Stroika_Foundation_IO_FileSystem_BinaryFileInputStream_inl_*/
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbStreamingStatisticsVectorImageFilter.h"
#include "otbEigenvalueLikelihoodMaximisation.h"
#include "otbVirtualDimensionality.h"

namespace otb
{
namespace Wrapper
{

class EndmemberNumberEstimation : public Application
{
public:
  /** Standard class typedefs. */
  typedef EndmemberNumberEstimation         Self;
  typedef Application                       Superclass;
  typedef itk::SmartPointer<Self>           Pointer;
  typedef itk::SmartPointer<const Self>     ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(EndmemberNumberEstimation, otb::Application);

  typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType, float> StreamingStatisticsVectorImageFilterType;
  typedef otb::VirtualDimensionality<float>                                      VirtualDimensionalityType;
  typedef otb::EigenvalueLikelihoodMaximisation<float>                           EigenvalueLikelihoodMaximisationType;

private:
  void DoInit() override
  {
    SetName("EndmemberNumberEstimation");
    SetDescription("Estimate the number of endmembers in a hyperspectral image");

    // Documentation
    SetDocName("Endmember Number Estimation");
    SetDocLongDescription("Estimate the number of endmembers "
    "in a hyperspectral image. First, compute statistics on the image and then "
    "apply an endmember number estimation algorithm using these statistics. Two "
    "algorithms are available:\n\n"

    "1. Virtual Dimensionality (VD) [1][2]\n"
    "2. Eigenvalue Likelihood Maximization (ELM) [3][4]\n\n"

    "The application then returns the estimated number of endmembers.\n\n"

    "[1] C.-I. Chang and Q. Du, Estimation of number of spectrally distinct signal "
    "sources in hyperspectral imagery, IEEE Transactions on Geoscience and Remote "
    "Sensing, vol. 43, no. 3, mar 2004.\n\n"

    "[2] J. Wang and C.-I. Chang, Applications of independent component analysis "
    "in endmember extraction and abundance quantification for hyperspectral imagery"
    ", IEEE Transactions on Geoscience and Remote Sensing, vol. 44, no. 9, pp. "
    "2601-1616, sep 2006.\n\n"

    "[3] Unsupervised Endmember Extraction of Martian Hyperspectral Images, B.Luo, "
    "J. Chanussot, S. Dout\'e and X. Ceamanos, IEEE Whispers 2009, Grenoble France, 2009\n\n"

    "[4] Unsupervised classification of hyperspectral images by using "
    "linear unmixing algorithm Luo, B. and Chanussot, J., IEEE Int. Conf. On Image"
    "Processing(ICIP) 2009, Cairo, Egypte, 2009"
    );

    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso("VertexComponentAnalysis, HyperspectralUnmixing");

    AddDocTag(Tags::Hyperspectral);

    AddParameter(ParameterType_InputImage,  "in", "Input Image Filename");
    SetParameterDescription("in","The hyperspectral data cube input");

    AddParameter(ParameterType_Choice, "algo", "Unmixing algorithm");
    SetParameterDescription("algo", "The algorithm to use for the estimation");
    AddChoice("algo.elm", "Eigenvalue Likelihood Maximization");
    SetParameterDescription("algo.elm", "");
    AddChoice("algo.vd", "Virtual Dimensionality");
    SetParameterDescription("algo.vd", "");

    AddParameter( ParameterType_Float , "algo.vd.far" , "False alarm rate");
    SetMinimumParameterFloatValue("algo.vd.far", 0);
    SetMaximumParameterFloatValue("algo.vd.far", 1);
    SetDefaultParameterFloat( "algo.vd.far" , 1.0E-3 );
    SetParameterDescription( "algo.vd.far" ,
      "False alarm rate for the virtual dimensionality algorithm");

    AddParameter(ParameterType_Int,"number","Number of endmembers");
    SetParameterDescription("number", "The output estimated number of endmembers");
    SetParameterRole("number", Role_Output);

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "cupriteSubHsi.tif");
    SetDocExampleParameterValue("algo", "vd");
    SetDocExampleParameterValue("algo.vd.far", "1.0E-3");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() override
  {
    // Nothing to do here : all parameters are independent
  }

  void DoExecute() override
  {
    // Load input image
    auto inputImage = GetParameterImage("in");

    otbAppLogINFO("Computing statistics on input image...");
    auto statisticsFilter = StreamingStatisticsVectorImageFilterType::New();
    statisticsFilter->SetInput(inputImage);
    AddProcess(statisticsFilter->GetStreamer(), "Statistic estimation step");

    statisticsFilter->Update();

    auto correlationMatrix = statisticsFilter->GetCorrelation().GetVnlMatrix();
    auto covarianceMatrix = statisticsFilter->GetCovariance().GetVnlMatrix();
    auto numberOfPixels = inputImage->GetLargestPossibleRegion().GetNumberOfPixels();

    int numberOfEndmembers = 0;
    const std::string algorithm = GetParameterString("algo");
    if (algorithm=="elm")
      {
      otbAppLogINFO("Estimation algorithm: Eigenvalue Likelihood Maximization.");
      auto elm = EigenvalueLikelihoodMaximisationType::New();
      elm->SetCovariance(covarianceMatrix);
      elm->SetCorrelation(correlationMatrix);
      elm->SetNumberOfPixels(numberOfPixels);
      elm->Compute();
      numberOfEndmembers = elm->GetNumberOfEndmembers();
      }
    else if (algorithm=="vd")
      {
      otbAppLogINFO("Estimation algorithm: Virtual Dimensionality.");
      auto vd = VirtualDimensionalityType::New();
      vd->SetCovariance(covarianceMatrix);
      vd->SetCorrelation(correlationMatrix);
      vd->SetNumberOfPixels(numberOfPixels);
      vd->SetFAR(GetParameterFloat("algo.vd.far"));
      vd->Compute();
      numberOfEndmembers = vd->GetNumberOfEndmembers();
      }
    SetParameterInt("number", numberOfEndmembers);
  }

};

}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::EndmemberNumberEstimation)
<commit_msg>DOC: moved the output parameter up in the app so it shows up on top in otbgui<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbStreamingStatisticsVectorImageFilter.h"
#include "otbEigenvalueLikelihoodMaximisation.h"
#include "otbVirtualDimensionality.h"

namespace otb
{
namespace Wrapper
{

class EndmemberNumberEstimation : public Application
{
public:
  /** Standard class typedefs. */
  typedef EndmemberNumberEstimation         Self;
  typedef Application                       Superclass;
  typedef itk::SmartPointer<Self>           Pointer;
  typedef itk::SmartPointer<const Self>     ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(EndmemberNumberEstimation, otb::Application);

  typedef otb::StreamingStatisticsVectorImageFilter<FloatVectorImageType, float> StreamingStatisticsVectorImageFilterType;
  typedef otb::VirtualDimensionality<float>                                      VirtualDimensionalityType;
  typedef otb::EigenvalueLikelihoodMaximisation<float>                           EigenvalueLikelihoodMaximisationType;

private:
  void DoInit() override
  {
    SetName("EndmemberNumberEstimation");
    SetDescription("Estimate the number of endmembers in a hyperspectral image");

    // Documentation
    SetDocName("Endmember Number Estimation");
    SetDocLongDescription("Estimate the number of endmembers "
    "in a hyperspectral image. First, compute statistics on the image and then "
    "apply an endmember number estimation algorithm using these statistics. Two "
    "algorithms are available:\n\n"

    "1. Virtual Dimensionality (VD) [1][2]\n"
    "2. Eigenvalue Likelihood Maximization (ELM) [3][4]\n\n"

    "The application then returns the estimated number of endmembers.\n\n"

    "[1] C.-I. Chang and Q. Du, Estimation of number of spectrally distinct signal "
    "sources in hyperspectral imagery, IEEE Transactions on Geoscience and Remote "
    "Sensing, vol. 43, no. 3, mar 2004.\n\n"

    "[2] J. Wang and C.-I. Chang, Applications of independent component analysis "
    "in endmember extraction and abundance quantification for hyperspectral imagery"
    ", IEEE Transactions on Geoscience and Remote Sensing, vol. 44, no. 9, pp. "
    "2601-1616, sep 2006.\n\n"

    "[3] Unsupervised Endmember Extraction of Martian Hyperspectral Images, B.Luo, "
    "J. Chanussot, S. Dout\'e and X. Ceamanos, IEEE Whispers 2009, Grenoble France, 2009\n\n"

    "[4] Unsupervised classification of hyperspectral images by using "
    "linear unmixing algorithm Luo, B. and Chanussot, J., IEEE Int. Conf. On Image"
    "Processing(ICIP) 2009, Cairo, Egypte, 2009"
    );

    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso("VertexComponentAnalysis, HyperspectralUnmixing");

    AddDocTag(Tags::Hyperspectral);

    AddParameter(ParameterType_InputImage,  "in", "Input Image Filename");
    SetParameterDescription("in","The hyperspectral data cube input");

    AddParameter(ParameterType_Int,"number","Number of endmembers");
    SetParameterDescription("number", "The output estimated number of endmembers");
    SetParameterRole("number", Role_Output);

    AddParameter(ParameterType_Choice, "algo", "Unmixing algorithm");
    SetParameterDescription("algo", "The algorithm to use for the estimation");
    AddChoice("algo.elm", "Eigenvalue Likelihood Maximization");
    SetParameterDescription("algo.elm", "");
    AddChoice("algo.vd", "Virtual Dimensionality");
    SetParameterDescription("algo.vd", "");

    AddParameter( ParameterType_Float , "algo.vd.far" , "False alarm rate");
    SetMinimumParameterFloatValue("algo.vd.far", 0);
    SetMaximumParameterFloatValue("algo.vd.far", 1);
    SetDefaultParameterFloat( "algo.vd.far" , 1.0E-3 );
    SetParameterDescription( "algo.vd.far" ,
      "False alarm rate for the virtual dimensionality algorithm");

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "cupriteSubHsi.tif");
    SetDocExampleParameterValue("algo", "vd");
    SetDocExampleParameterValue("algo.vd.far", "1.0E-3");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() override
  {
    // Nothing to do here : all parameters are independent
  }

  void DoExecute() override
  {
    // Load input image
    auto inputImage = GetParameterImage("in");

    otbAppLogINFO("Computing statistics on input image...");
    auto statisticsFilter = StreamingStatisticsVectorImageFilterType::New();
    statisticsFilter->SetInput(inputImage);
    AddProcess(statisticsFilter->GetStreamer(), "Statistic estimation step");

    statisticsFilter->Update();

    auto correlationMatrix = statisticsFilter->GetCorrelation().GetVnlMatrix();
    auto covarianceMatrix = statisticsFilter->GetCovariance().GetVnlMatrix();
    auto numberOfPixels = inputImage->GetLargestPossibleRegion().GetNumberOfPixels();

    int numberOfEndmembers = 0;
    const std::string algorithm = GetParameterString("algo");
    if (algorithm=="elm")
      {
      otbAppLogINFO("Estimation algorithm: Eigenvalue Likelihood Maximization.");
      auto elm = EigenvalueLikelihoodMaximisationType::New();
      elm->SetCovariance(covarianceMatrix);
      elm->SetCorrelation(correlationMatrix);
      elm->SetNumberOfPixels(numberOfPixels);
      elm->Compute();
      numberOfEndmembers = elm->GetNumberOfEndmembers();
      }
    else if (algorithm=="vd")
      {
      otbAppLogINFO("Estimation algorithm: Virtual Dimensionality.");
      auto vd = VirtualDimensionalityType::New();
      vd->SetCovariance(covarianceMatrix);
      vd->SetCorrelation(correlationMatrix);
      vd->SetNumberOfPixels(numberOfPixels);
      vd->SetFAR(GetParameterFloat("algo.vd.far"));
      vd->Compute();
      numberOfEndmembers = vd->GetNumberOfEndmembers();
      }
    SetParameterInt("number", numberOfEndmembers);
  }

};

}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::EndmemberNumberEstimation)
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#ifndef __itkKspaceImageFilter_txx
#define __itkKspaceImageFilter_txx

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

#include "itkKspaceImageFilter.h"
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionConstIteratorWithIndex.h>
#include <itkImageRegionIterator.h>
#include <itkImageFileWriter.h>

#define _USE_MATH_DEFINES
#include <math.h>

namespace itk {

template< class TPixelType >
KspaceImageFilter< TPixelType >
::KspaceImageFilter()
    : m_tLine(1)
    , m_kOffset(0)
    , m_FrequencyMap(NULL)
    , m_SimulateRelaxation(true)
    , m_SimulateEddyCurrents(false)
    , m_Tau(70)
    , m_EddyGradientMagnitude(30)
    , m_IsBaseline(true)
    , m_SignalScale(1)
    , m_Spikes(0)
    , m_SpikeAmplitude(1)
{
    m_DiffusionGradientDirection.Fill(0.0);
}

template< class TPixelType >
void KspaceImageFilter< TPixelType >
::BeforeThreadedGenerateData()
{
    typename OutputImageType::Pointer outputImage = OutputImageType::New();
    outputImage->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
    outputImage->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
    outputImage->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
    itk::ImageRegion<2> region; region.SetSize(0, m_OutSize[0]);  region.SetSize(1, m_OutSize[1]);
    outputImage->SetLargestPossibleRegion( region );
    outputImage->SetBufferedRegion( region );
    outputImage->SetRequestedRegion( region );
    outputImage->Allocate();

    m_TEMPIMAGE = InputImageType::New();
    m_TEMPIMAGE->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
    m_TEMPIMAGE->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
    m_TEMPIMAGE->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
    m_TEMPIMAGE->SetLargestPossibleRegion( region );
    m_TEMPIMAGE->SetBufferedRegion( region );
    m_TEMPIMAGE->SetRequestedRegion( region );
    m_TEMPIMAGE->Allocate();

    m_SimulateDistortions = true;
    if (m_FrequencyMap.IsNull())
    {
        m_SimulateDistortions = false;
        m_FrequencyMap = InputImageType::New();
        m_FrequencyMap->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
        m_FrequencyMap->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
        m_FrequencyMap->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
        m_FrequencyMap->SetLargestPossibleRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
        m_FrequencyMap->SetBufferedRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
        m_FrequencyMap->SetRequestedRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
        m_FrequencyMap->Allocate();
        m_FrequencyMap->FillBuffer(0);
    }

    double gamma = 42576000;    // Gyromagnetic ratio in Hz/T
    if (m_DiffusionGradientDirection.GetNorm()>0.001)
    {
        m_DiffusionGradientDirection.Normalize();
        m_EddyGradientMagnitude /= 1000; // eddy gradient magnitude in T/m
        m_DiffusionGradientDirection = m_DiffusionGradientDirection * m_EddyGradientMagnitude *  gamma;
        m_IsBaseline = false;
    }
    else
        m_EddyGradientMagnitude = gamma*m_EddyGradientMagnitude/1000;

    this->SetNthOutput(0, outputImage);
}

template< class TPixelType >
void KspaceImageFilter< TPixelType >
::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType threadId)
{
    typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0));

    ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread);

    typedef ImageRegionConstIterator< InputImageType > InputIteratorType;

    double kxMax = outputImage->GetLargestPossibleRegion().GetSize(0);
    double kyMax = outputImage->GetLargestPossibleRegion().GetSize(1);
    double numPix = kxMax*kyMax;
    double dt = m_tLine/kxMax;

    double fromMaxEcho = - m_tLine*kyMax/2;

    double in_szx = m_CompartmentImages.at(0)->GetLargestPossibleRegion().GetSize(0);
    double in_szy = m_CompartmentImages.at(0)->GetLargestPossibleRegion().GetSize(1);
    int xOffset = in_szx-kxMax;
    int yOffset = in_szy-kyMax;

    vcl_complex<double> spike(0,0);
    while( !oit.IsAtEnd() )
    {
        itk::Index< 2 > kIdx;
        kIdx[0] = oit.GetIndex()[0];
        kIdx[1] = oit.GetIndex()[1];

        double t = fromMaxEcho + ((double)kIdx[1]*kxMax+(double)kIdx[0])*dt;    // dephasing time

        // rearrange slice
        if( kIdx[0] <  kxMax/2 )
            kIdx[0] = kIdx[0] + kxMax/2;
        else
            kIdx[0] = kIdx[0] - kxMax/2;

        if( kIdx[1] <  kyMax/2 )
            kIdx[1] = kIdx[1] + kyMax/2;
        else
            kIdx[1] = kIdx[1] - kyMax/2;

        // calculate eddy current decay factors
        double eddyDecay = 0;
        if (m_SimulateEddyCurrents)
            eddyDecay = exp(-(m_TE/2 + t)/m_Tau) * t/1000;

        // calcualte signal relaxation factors
        std::vector< double > relaxFactor;
        if (m_SimulateRelaxation)
            for (int i=0; i<m_CompartmentImages.size(); i++)
                relaxFactor.push_back(exp(-(m_TE+t)/m_T2.at(i) -fabs(t)/m_Tinhom));

        double kx = kIdx[0];
        double ky = kIdx[1];
        if (oit.GetIndex()[1]%2 == 1)               // reverse readout direction and add ghosting
        {
            kIdx[0] = kxMax-kIdx[0]-1;                // reverse readout direction
            kx = (double)kIdx[0]-m_kOffset;    // add gradient delay induced offset
        }
        else
            kx += m_kOffset;    // add gradient delay induced offset

        // add gibbs ringing offset (cropps k-space)
        if (kx>=kxMax/2)
            kx += xOffset;
        if (ky>=kyMax/2)
            ky += yOffset;

        vcl_complex<double> s(0,0);
        InputIteratorType it(m_CompartmentImages.at(0), m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
        while( !it.IsAtEnd() )
        {
            double x = it.GetIndex()[0]-in_szx/2;
            double y = it.GetIndex()[1]-in_szy/2;

            vcl_complex<double> f(0, 0);

            // sum compartment signals and simulate relaxation
            for (int i=0; i<m_CompartmentImages.size(); i++)
                if (m_SimulateRelaxation)
                    f += std::complex<double>( m_CompartmentImages.at(i)->GetPixel(it.GetIndex()) * relaxFactor.at(i) * m_SignalScale, 0);
                else
                    f += std::complex<double>( m_CompartmentImages.at(i)->GetPixel(it.GetIndex()) * m_SignalScale );

            // simulate eddy currents and other distortions
            double omega_t = 0;
            if ( m_SimulateEddyCurrents && !m_IsBaseline)
            {
                itk::Vector< double, 3 > pos; pos[0] = x; pos[1] = y; pos[2] = m_Z;
                pos = m_DirectionMatrix*pos/1000;   // vector from image center to current position (in meter)
                omega_t += (m_DiffusionGradientDirection[0]*pos[0]+m_DiffusionGradientDirection[1]*pos[1]+m_DiffusionGradientDirection[2]*pos[2])*eddyDecay;
            }
            if (m_SimulateDistortions)
                omega_t += m_FrequencyMap->GetPixel(it.GetIndex())*t/1000;

            // actual DFT term
            s += f * exp( std::complex<double>(0, 2 * M_PI * (kx*x/in_szx + ky*y/in_szy + omega_t )) );

            ++it;
        }
        s /= numPix;

        if (m_Spikes>0 && sqrt(s.imag()*s.imag()+s.real()*s.real()) > sqrt(spike.imag()*spike.imag()+spike.real()*spike.real()) )
            spike = s;

        //        m_TEMPIMAGE->SetPixel(kIdx, sqrt(s.real()*s.real()+s.imag()*s.imag()));
        outputImage->SetPixel(kIdx, s);
        ++oit;
    }

    spike *= m_SpikeAmplitude;
    for (int i=0; i<m_Spikes; i++)
    {
        itk::Index< 2 > spikeIdx;
        spikeIdx[0] = rand()%(int)kxMax;
        spikeIdx[1] = rand()%(int)kyMax;
        outputImage->SetPixel(spikeIdx, spike);
    }

    //    typedef itk::ImageFileWriter< InputImageType > WriterType;
    //    typename WriterType::Pointer writer = WriterType::New();
    //    writer->SetFileName("/local/kspace.nrrd");
    //    writer->SetInput(m_TEMPIMAGE);
    //    writer->Update();
}

template< class TPixelType >
void KspaceImageFilter< TPixelType >
::AfterThreadedGenerateData()
{

}

}
#endif
<commit_msg>zucker<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#ifndef __itkKspaceImageFilter_txx
#define __itkKspaceImageFilter_txx

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

#include "itkKspaceImageFilter.h"
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionConstIteratorWithIndex.h>
#include <itkImageRegionIterator.h>
#include <itkImageFileWriter.h>

#define _USE_MATH_DEFINES
#include <math.h>

namespace itk {

template< class TPixelType >
KspaceImageFilter< TPixelType >
::KspaceImageFilter()
    : m_tLine(1)
    , m_kOffset(0)
    , m_FrequencyMap(NULL)
    , m_SimulateRelaxation(true)
    , m_SimulateEddyCurrents(false)
    , m_Tau(70)
    , m_EddyGradientMagnitude(30)
    , m_IsBaseline(true)
    , m_SignalScale(1)
    , m_Spikes(0)
    , m_SpikeAmplitude(1)
{
    m_DiffusionGradientDirection.Fill(0.0);
}

template< class TPixelType >
void KspaceImageFilter< TPixelType >
::BeforeThreadedGenerateData()
{
    typename OutputImageType::Pointer outputImage = OutputImageType::New();
    outputImage->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
    outputImage->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
    outputImage->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
    itk::ImageRegion<2> region; region.SetSize(0, m_OutSize[0]);  region.SetSize(1, m_OutSize[1]);
    outputImage->SetLargestPossibleRegion( region );
    outputImage->SetBufferedRegion( region );
    outputImage->SetRequestedRegion( region );
    outputImage->Allocate();

    m_TEMPIMAGE = InputImageType::New();
    m_TEMPIMAGE->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
    m_TEMPIMAGE->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
    m_TEMPIMAGE->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
    m_TEMPIMAGE->SetLargestPossibleRegion( region );
    m_TEMPIMAGE->SetBufferedRegion( region );
    m_TEMPIMAGE->SetRequestedRegion( region );
    m_TEMPIMAGE->Allocate();

    m_SimulateDistortions = true;
    if (m_FrequencyMap.IsNull())
    {
        m_SimulateDistortions = false;
        m_FrequencyMap = InputImageType::New();
        m_FrequencyMap->SetSpacing( m_CompartmentImages.at(0)->GetSpacing() );
        m_FrequencyMap->SetOrigin( m_CompartmentImages.at(0)->GetOrigin() );
        m_FrequencyMap->SetDirection( m_CompartmentImages.at(0)->GetDirection() );
        m_FrequencyMap->SetLargestPossibleRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
        m_FrequencyMap->SetBufferedRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
        m_FrequencyMap->SetRequestedRegion( m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
        m_FrequencyMap->Allocate();
        m_FrequencyMap->FillBuffer(0);
    }

    double gamma = 42576000;    // Gyromagnetic ratio in Hz/T
    if (m_DiffusionGradientDirection.GetNorm()>0.001)
    {
        m_EddyGradientMagnitude /= 1000; // eddy gradient magnitude in T/m
        m_DiffusionGradientDirection.Normalize();
        m_DiffusionGradientDirection = m_DiffusionGradientDirection * m_EddyGradientMagnitude *  gamma;
        m_IsBaseline = false;
    }

    this->SetNthOutput(0, outputImage);
}

template< class TPixelType >
void KspaceImageFilter< TPixelType >
::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType threadId)
{
    typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0));

    ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread);

    typedef ImageRegionConstIterator< InputImageType > InputIteratorType;

    double kxMax = outputImage->GetLargestPossibleRegion().GetSize(0);
    double kyMax = outputImage->GetLargestPossibleRegion().GetSize(1);
    double numPix = kxMax*kyMax;
    double dt = m_tLine/kxMax;

    double fromMaxEcho = - m_tLine*kyMax/2;

    double in_szx = m_CompartmentImages.at(0)->GetLargestPossibleRegion().GetSize(0);
    double in_szy = m_CompartmentImages.at(0)->GetLargestPossibleRegion().GetSize(1);
    int xOffset = in_szx-kxMax;
    int yOffset = in_szy-kyMax;

    vcl_complex<double> spike(0,0);
    while( !oit.IsAtEnd() )
    {
        itk::Index< 2 > kIdx;
        kIdx[0] = oit.GetIndex()[0];
        kIdx[1] = oit.GetIndex()[1];

        double t = fromMaxEcho + ((double)kIdx[1]*kxMax+(double)kIdx[0])*dt;    // dephasing time

        // rearrange slice
        if( kIdx[0] <  kxMax/2 )
            kIdx[0] = kIdx[0] + kxMax/2;
        else
            kIdx[0] = kIdx[0] - kxMax/2;

        if( kIdx[1] <  kyMax/2 )
            kIdx[1] = kIdx[1] + kyMax/2;
        else
            kIdx[1] = kIdx[1] - kyMax/2;

        // calculate eddy current decay factors
        double eddyDecay = 0;
        if (m_SimulateEddyCurrents)
            eddyDecay = exp(-(m_TE/2 + t)/m_Tau) * t/1000;

        // calcualte signal relaxation factors
        std::vector< double > relaxFactor;
        if (m_SimulateRelaxation)
            for (int i=0; i<m_CompartmentImages.size(); i++)
                relaxFactor.push_back(exp(-(m_TE+t)/m_T2.at(i) -fabs(t)/m_Tinhom));

        double kx = kIdx[0];
        double ky = kIdx[1];
        if (oit.GetIndex()[1]%2 == 1)               // reverse readout direction and add ghosting
        {
            kIdx[0] = kxMax-kIdx[0]-1;                // reverse readout direction
            kx = (double)kIdx[0]-m_kOffset;    // add gradient delay induced offset
        }
        else
            kx += m_kOffset;    // add gradient delay induced offset

        // add gibbs ringing offset (cropps k-space)
        if (kx>=kxMax/2)
            kx += xOffset;
        if (ky>=kyMax/2)
            ky += yOffset;

        vcl_complex<double> s(0,0);
        InputIteratorType it(m_CompartmentImages.at(0), m_CompartmentImages.at(0)->GetLargestPossibleRegion() );
        while( !it.IsAtEnd() )
        {
            double x = it.GetIndex()[0]-in_szx/2;
            double y = it.GetIndex()[1]-in_szy/2;

            vcl_complex<double> f(0, 0);

            // sum compartment signals and simulate relaxation
            for (int i=0; i<m_CompartmentImages.size(); i++)
                if (m_SimulateRelaxation)
                    f += std::complex<double>( m_CompartmentImages.at(i)->GetPixel(it.GetIndex()) * relaxFactor.at(i) * m_SignalScale, 0);
                else
                    f += std::complex<double>( m_CompartmentImages.at(i)->GetPixel(it.GetIndex()) * m_SignalScale );

            // simulate eddy currents and other distortions
            double omega_t = 0;
            if ( m_SimulateEddyCurrents && !m_IsBaseline)
            {
                itk::Vector< double, 3 > pos; pos[0] = x; pos[1] = y; pos[2] = m_Z;
                pos = m_DirectionMatrix*pos/1000;   // vector from image center to current position (in meter)
                omega_t += (m_DiffusionGradientDirection[0]*pos[0]+m_DiffusionGradientDirection[1]*pos[1]+m_DiffusionGradientDirection[2]*pos[2])*eddyDecay;
            }
            if (m_SimulateDistortions)
                omega_t += m_FrequencyMap->GetPixel(it.GetIndex())*t/1000;

            // actual DFT term
            s += f * exp( std::complex<double>(0, 2 * M_PI * (kx*x/in_szx + ky*y/in_szy + omega_t )) );

            ++it;
        }
        s /= numPix;

        if (m_Spikes>0 && sqrt(s.imag()*s.imag()+s.real()*s.real()) > sqrt(spike.imag()*spike.imag()+spike.real()*spike.real()) )
            spike = s;

        //        m_TEMPIMAGE->SetPixel(kIdx, sqrt(s.real()*s.real()+s.imag()*s.imag()));
        outputImage->SetPixel(kIdx, s);
        ++oit;
    }

    spike *= m_SpikeAmplitude;
    for (int i=0; i<m_Spikes; i++)
    {
        itk::Index< 2 > spikeIdx;
        spikeIdx[0] = rand()%(int)kxMax;
        spikeIdx[1] = rand()%(int)kyMax;
        outputImage->SetPixel(spikeIdx, spike);
    }

    //    typedef itk::ImageFileWriter< InputImageType > WriterType;
    //    typename WriterType::Pointer writer = WriterType::New();
    //    writer->SetFileName("/local/kspace.nrrd");
    //    writer->SetInput(m_TEMPIMAGE);
    //    writer->Update();
}

template< class TPixelType >
void KspaceImageFilter< TPixelType >
::AfterThreadedGenerateData()
{

}

}
#endif
<|endoftext|>


<commit_before>#include "GLFWWindowManager.h"

using namespace phoenix;

/*!
    Open function.
*/
bool GLFWWindowManager::open( const Vector2d& _sz, const bool _f )
{

    // Set our internal screen size variable.
    screensize = _sz;

	// No GLFW functions may be called before this
	if( !glfwInit() ) return false;

	// Important defines
	#define RED_BITS 8
	#define BLUE_BITS 8
	#define GREEN_BITS 8
	#define ALPHA_BITS 8
	#define STENCIL_BITS 0
	#ifdef DISABLE_DEPTHBUFFER
		#define DEPTH_BITS 0
	#else
		#define DEPTH_BITS 8
	#endif

	int mode = _f ? GLFW_FULLSCREEN : GLFW_WINDOW;

	if( !glfwOpenWindow(int(_sz.getX()), int(_sz.getY()), RED_BITS, BLUE_BITS, GREEN_BITS, ALPHA_BITS, DEPTH_BITS, STENCIL_BITS, mode) ) return false;

	// Disable vsync.
	glfwSwapInterval( 0 );

	// Set the window caption
	setWindowTitle( PHOENIXCORE_VERSION );

	// Set GLFW event callbacks
	glfwSetKeyCallback( &GLFWWindowManager::glfwKeyboardCallback );
	glfwSetCharCallback( &GLFWWindowManager::glfwCharacterCallback );
	glfwSetMouseButtonCallback( &GLFWWindowManager::glfwKeyboardCallback );
	glfwSetMousePosCallback( &GLFWWindowManager::glfwMousePosCallback );
	glfwSetWindowCloseCallback( &GLFWWindowManager::glfwWindowCloseCallback );
	glfwSetMouseWheelCallback( &GLFWWindowManager::glfwMouseWheelPosCallback );
    glfwSetWindowSizeCallback( &GLFWWindowManager::glfwWindowResizeCallback );
	glfwSetWindowMoveCallback( &GLFWWindowManager::glfwWindowMoveCallback );

	// Disable key repeat; event receiver manages that.
	glfwDisable(GLFW_KEY_REPEAT);

	return true;

}

/*
	Swap Buffers and Update Events.
*/
void GLFWWindowManager::update()
{
	// send the update event. ( done first because glfwSwapBuffers sends new events ).
	WindowEvent e;
	e.type = WET_UPDATE;
	signal(e);

	glfwSwapBuffers();
}

//! Window Resize callback (from GLFW).
void GLFWWindowManager::glfwWindowResizeCallback( int width, int height )
{
	WindowManagerPtr wm = WindowManager::Instance();

	Vector2d size( (float) width, (float) height );
	wm->setWindowSize( size );

	WindowEvent e;
	e.type = WET_RESIZE;
	e.vector_data = size;
	wm->signal(e);
}

//! Keyboard callback (from GLFW).
void GLFWWindowManager::glfwKeyboardCallback( int key, int action )
{
	WindowEvent e;
	e.type = WET_KEY;
	e.int_data = key;
	e.bool_data = action == GLFW_PRESS ? true : false;
	Instance()->signal(e);
}

//! Character callback (from GLFW).
void GLFWWindowManager::glfwCharacterCallback( int key, int action )
{
	if( action == GLFW_PRESS ){
		WindowEvent e;
		e.type = WET_CHAR;
		e.int_data = key;
		e.bool_data = true;
		Instance()->signal(e);
	}
}

//! Mouse position callback (from GLFW).
void GLFWWindowManager::glfwMousePosCallback( int x, int y )
{
	WindowEvent e;
	e.type = WET_MOUSE_POSITION;
	e.bool_data = true;
	e.vector_data = Vector2d( float(x), float(y) );
	Instance()->signal(e);
}

//! Window callback (from GLFW).
int GLFWWindowManager::glfwWindowCloseCallback()
{
	WindowEvent e;
	e.type = WET_CLOSE;
	e.bool_data = true;
	Instance()->signal(e);
	return false;
}

//! Mouse wheel callback (from GLFW).
void GLFWWindowManager::glfwMouseWheelPosCallback( int pos )
{
	WindowEvent e;
	e.type = WET_MOUSE_WHEEL;
	e.bool_data = true;
	e.int_data = pos;
	Instance()->signal(e);
}

#ifdef _GLFW_WM_MOVE_HACK
void GLFWWindowManager::glfwWindowMoveCallback( int state )
{
	WindowEvent e;
	e.type = WET_MOVE;
	e.bool_data = state == GLFW_MOVE_ENTER ? 1 : 0;
	Instance()->signal(e);
}

#endif //_GLFW_WM_MOVE_HACK<commit_msg>Forgot to check for the glfw move hack definition in the source.<commit_after>#include "GLFWWindowManager.h"

using namespace phoenix;

/*!
    Open function.
*/
bool GLFWWindowManager::open( const Vector2d& _sz, const bool _f )
{

    // Set our internal screen size variable.
    screensize = _sz;

	// No GLFW functions may be called before this
	if( !glfwInit() ) return false;

	// Important defines
	#define RED_BITS 8
	#define BLUE_BITS 8
	#define GREEN_BITS 8
	#define ALPHA_BITS 8
	#define STENCIL_BITS 0
	#ifdef DISABLE_DEPTHBUFFER
		#define DEPTH_BITS 0
	#else
		#define DEPTH_BITS 8
	#endif

	int mode = _f ? GLFW_FULLSCREEN : GLFW_WINDOW;

	if( !glfwOpenWindow(int(_sz.getX()), int(_sz.getY()), RED_BITS, BLUE_BITS, GREEN_BITS, ALPHA_BITS, DEPTH_BITS, STENCIL_BITS, mode) ) return false;

	// Disable vsync.
	glfwSwapInterval( 0 );

	// Set the window caption
	setWindowTitle( PHOENIXCORE_VERSION );

	// Set GLFW event callbacks
	glfwSetKeyCallback( &GLFWWindowManager::glfwKeyboardCallback );
	glfwSetCharCallback( &GLFWWindowManager::glfwCharacterCallback );
	glfwSetMouseButtonCallback( &GLFWWindowManager::glfwKeyboardCallback );
	glfwSetMousePosCallback( &GLFWWindowManager::glfwMousePosCallback );
	glfwSetWindowCloseCallback( &GLFWWindowManager::glfwWindowCloseCallback );
	glfwSetMouseWheelCallback( &GLFWWindowManager::glfwMouseWheelPosCallback );
    glfwSetWindowSizeCallback( &GLFWWindowManager::glfwWindowResizeCallback );
#ifdef _GLFW_WM_MOVE_HACK
	glfwSetWindowMoveCallback( &GLFWWindowManager::glfwWindowMoveCallback );
#endif

	// Disable key repeat; event receiver manages that.
	glfwDisable(GLFW_KEY_REPEAT);

	return true;

}

/*
	Swap Buffers and Update Events.
*/
void GLFWWindowManager::update()
{
	// send the update event. ( done first because glfwSwapBuffers sends new events ).
	WindowEvent e;
	e.type = WET_UPDATE;
	signal(e);

	glfwSwapBuffers();
}

//! Window Resize callback (from GLFW).
void GLFWWindowManager::glfwWindowResizeCallback( int width, int height )
{
	WindowManagerPtr wm = WindowManager::Instance();

	Vector2d size( (float) width, (float) height );
	wm->setWindowSize( size );

	WindowEvent e;
	e.type = WET_RESIZE;
	e.vector_data = size;
	wm->signal(e);
}

//! Keyboard callback (from GLFW).
void GLFWWindowManager::glfwKeyboardCallback( int key, int action )
{
	WindowEvent e;
	e.type = WET_KEY;
	e.int_data = key;
	e.bool_data = action == GLFW_PRESS ? true : false;
	Instance()->signal(e);
}

//! Character callback (from GLFW).
void GLFWWindowManager::glfwCharacterCallback( int key, int action )
{
	if( action == GLFW_PRESS ){
		WindowEvent e;
		e.type = WET_CHAR;
		e.int_data = key;
		e.bool_data = true;
		Instance()->signal(e);
	}
}

//! Mouse position callback (from GLFW).
void GLFWWindowManager::glfwMousePosCallback( int x, int y )
{
	WindowEvent e;
	e.type = WET_MOUSE_POSITION;
	e.bool_data = true;
	e.vector_data = Vector2d( float(x), float(y) );
	Instance()->signal(e);
}

//! Window callback (from GLFW).
int GLFWWindowManager::glfwWindowCloseCallback()
{
	WindowEvent e;
	e.type = WET_CLOSE;
	e.bool_data = true;
	Instance()->signal(e);
	return false;
}

//! Mouse wheel callback (from GLFW).
void GLFWWindowManager::glfwMouseWheelPosCallback( int pos )
{
	WindowEvent e;
	e.type = WET_MOUSE_WHEEL;
	e.bool_data = true;
	e.int_data = pos;
	Instance()->signal(e);
}

#ifdef _GLFW_WM_MOVE_HACK
void GLFWWindowManager::glfwWindowMoveCallback( int state )
{
	WindowEvent e;
	e.type = WET_MOVE;
	e.bool_data = state == GLFW_MOVE_ENTER ? 1 : 0;
	Instance()->signal(e);
}

#endif //_GLFW_WM_MOVE_HACK<|endoftext|>


<commit_before>// $Id: ooiEnergy.C,v 1.5 2000/05/30 10:35:18 oliver Exp $

#include <BALL/SOLVATION/ooiEnergy.h>

#include <BALL/common.h>
#include <BALL/DATATYPE/hashGrid.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/DATATYPE/stringHashMap.h>
#include <BALL/STRUCTURE/geometricProperties.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/STRUCTURE/numericalSAS.h>
#include <BALL/FORMAT/parameters.h>
#include <BALL/FORMAT/parameterSection.h>
#include <BALL/MOLMEC/COMMON/typeRuleProcessor.h>

#define OOI_PARAMETER_FILENAME "solvation/Ooi.ini"

using namespace std;

namespace BALL
{

	namespace OoiEnergy
	{
		bool is_initialized = false;

		// a hash map to convert names to Ooi types
		StringHashMap<Atom::Type> type_map;

		// a type rule assignment processor
		TypeRuleProcessor type_rule;

		// free energy is calculated as
		// dG = \sum_i g_i A_i
		// where A_i is the atomic solvent accesible surface
		// area. The atomic radii are taken from the vector radius below.
		vector<float> radius;
		vector<float> g;

		// read the parameter files for calculateOoiEnergy
		// and set up the basic data structures
		void init()
		{
			// extract the parameters from the file
			Path path;
			String filename = path.find(OOI_PARAMETER_FILENAME);
			if (filename == "")
			{
				filename = OOI_PARAMETER_FILENAME;
			}
			Parameters parameters(filename);

			ParameterSection parameter_section;
			if (!parameter_section.extractSection(parameters, "OoiParameters"))
			{
				Log.error() << "calculateOoiEnergy: cannot find section [OoiParameters] in file "
					<< parameters.getFilename() << "." << endl;
				return;
			}
			if (!parameter_section.hasVariable("g") || !parameter_section.hasVariable("radius"))
			{
				Log.error() << "OoiEnergy: section [OoiTypes] of file "
					<< parameters.getFilename() << " requires at least the columns 'g' and 'radius'." << endl;
				return;
			}

			ParameterSection type_section;
			if (!type_section.extractSection(parameters, "OoiTypes"))
			{
				Log.error() << "calculateOoiEnergy: cannot find section [OoiTypes] in file "
					<< parameters.getFilename() << "." << endl;
				return;
			}
			if (!type_section.hasVariable("type"))
			{
				Log.error() << "OoiEnergy: section [OoiTypes] of file "
					<< parameters.getFilename() << " does not contain a variable column 'type'." << endl;
				return;
			}

			// extract the parameters for each type
			//
			Position radius_column = parameter_section.getColumnIndex("radius");
			Position g_column = parameter_section.getColumnIndex("g");
			Index max_index = -1;
			Size i;
			for (i = 1; i <= parameter_section.getNumberOfKeys(); i++)
			{
				Index index = parameter_section.getKey(i).toInt();
				if (index < 0)
				{
					Log.error() << "calculateOoiEnergy: illegal atom type index: " << index << endl;
				}
				else
				{
					if (index > max_index)
					{
						max_index = index;
					}
				}
			}

			if (max_index < 0)
			{
				Log.error() << "calculateOoiEnergy: could not find any atom type in file "
									  << parameters.getFilename() << endl;
				return;
			}

			// resize the vectors to hold all indices
			radius.resize((Size)max_index + 1);
			g.resize((Size)max_index + 1);

			// and read all values from the parameter section
			for (i = 1; i <= parameter_section.getNumberOfKeys(); i++)
			{
				Index index = parameter_section.getKey(i).toInt();

				// we ignore illegal (negative) indices
				if (index >= 0)
				{
					radius[index] = parameter_section.getValue(i, radius_column).toFloat();
					g[index] = parameter_section.getValue(i, g_column).toFloat();
				}
			}

			// extract all known types by iterating over all keys
		  // and construct the hash map type_map
			Position type_column = type_section.getColumnIndex("type");
			for (i = 1; i <= type_section.getNumberOfKeys(); i++)
			{
				// retrieve the type and check for validity
				Atom::Type type = type_section.getValue(i, type_column).toInt();
				if (type >= (Atom::Type)radius.size())
				{
					Log.error() << "calculateOoiEnergy: illegal atom type: " << type << " while reading parameter file." << endl;
				}
				else
				{
					type_map.insert(type_section.getKey(i), (Atom::Type)type_section.getValue(i, type_column).toInt());
				}
			}

			// set up the type rule processor
			// from the rules in the INI file
			type_rule.initialize(parameters.getParameterFile(), "TypeRules");

			// we're done with the initialization
			is_initialized = true;
		}
	}

	double calculateOoiEnergy(BaseFragment& fragment)
	{
		using namespace OoiEnergy;

		// read and interpret the parameters
		// this is only done the first time calculateOoiEnergy is called
		if (!is_initialized)
		{
			init();
			if (!is_initialized)
			{
				return 0;
			}
		}

		// assign radii and atom types for all atoms
		AtomIterator atom_it = fragment.beginAtom();
		for (; +atom_it; ++atom_it)
		{
			// construct correct name, <RESNAME>:<ATOMNAME>
			String atom_name = atom_it->getFullName();

			// get the atom type from hash table
			// first, try a direct match
			Atom::Type atom_type = -1;
			if (type_map.has(atom_name))
			{
				atom_type = type_map[atom_name];
			}
			else
			{
				atom_name = atom_it->getFullName(Atom::NO_VARIANT_EXTENSIONS);
				if (type_map.has(atom_name))
				{
					atom_type = type_map[atom_name];
				}
				else
				{
					// try wildcard match
					atom_name = "*:" + atom_it->getName();
					if (type_map.has(atom_name))
					{
						atom_type = type_map[atom_name];
					}
				}
			}

			// if the atom type could not be determined, complain
			if (atom_type < 0)
			{
				// try to apply the type rule processor
				atom_it->setType(-1);
				type_rule(*atom_it);
				atom_type = atom_it->getType();
			}

			if (atom_type < 0)
			{
				Log.warn() << "calculateOOIEnergy: did not find a suitable type for " << atom_it->getFullName() << endl;

				// ignore this atom....
				atom_it->setType(-1);
				atom_it->setRadius(0.0);
			}
			else
			{
				// assign type and radius
				atom_it->setType(atom_type);
				atom_it->setRadius(radius[atom_type]);
			}
		}

		// calculate the atomic SAS areas
		// atom_SAS_areas hashes the atom pointer to the
		// surface area (in Angstrom^2)
		HashMap<Atom*,float> atom_SAS_areas;
		calculateNumericalSASAtomAreas(atom_SAS_areas, fragment, 1.4, 1888);

		// iterate over all atoms and add up the energies
		float energy = 0.0;
		for (atom_it = fragment.beginAtom(); +atom_it; ++atom_it)
		{

			if (atom_SAS_areas.has(&*atom_it))
			{
				Atom::Type atom_type = atom_it->getType();
				// if the atom type could not be determined, complain
				if (atom_type >= 0)
				{
					// add the energy contribution of the atom
					float tmp = atom_SAS_areas[&*atom_it] * g[atom_type];
					energy += tmp;
				}
			}
		}

		// we're done.
		return energy;
	}

} // namespace BALL
<commit_msg>changed: adapted to the new interface of numericalSAS<commit_after>// $Id: ooiEnergy.C,v 1.6 2000/06/02 07:14:21 oliver Exp $

#include <BALL/SOLVATION/ooiEnergy.h>

#include <BALL/common.h>
#include <BALL/DATATYPE/hashGrid.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/DATATYPE/stringHashMap.h>
#include <BALL/STRUCTURE/geometricProperties.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/STRUCTURE/numericalSAS.h>
#include <BALL/FORMAT/parameters.h>
#include <BALL/FORMAT/parameterSection.h>
#include <BALL/MOLMEC/COMMON/typeRuleProcessor.h>

#define OOI_PARAMETER_FILENAME "solvation/Ooi.ini"

using namespace std;

namespace BALL
{

	namespace OoiEnergy
	{
		bool is_initialized = false;

		// a hash map to convert names to Ooi types
		StringHashMap<Atom::Type> type_map;

		// a type rule assignment processor
		TypeRuleProcessor type_rule;

		// free energy is calculated as
		// dG = \sum_i g_i A_i
		// where A_i is the atomic solvent accesible surface
		// area. The atomic radii are taken from the vector radius below.
		vector<float> radius;
		vector<float> g;

		// read the parameter files for calculateOoiEnergy
		// and set up the basic data structures
		void init()
		{
			// extract the parameters from the file
			Path path;
			String filename = path.find(OOI_PARAMETER_FILENAME);
			if (filename == "")
			{
				filename = OOI_PARAMETER_FILENAME;
			}
			Parameters parameters(filename);

			ParameterSection parameter_section;
			if (!parameter_section.extractSection(parameters, "OoiParameters"))
			{
				Log.error() << "calculateOoiEnergy: cannot find section [OoiParameters] in file "
					<< parameters.getFilename() << "." << endl;
				return;
			}
			if (!parameter_section.hasVariable("g") || !parameter_section.hasVariable("radius"))
			{
				Log.error() << "OoiEnergy: section [OoiTypes] of file "
					<< parameters.getFilename() << " requires at least the columns 'g' and 'radius'." << endl;
				return;
			}

			ParameterSection type_section;
			if (!type_section.extractSection(parameters, "OoiTypes"))
			{
				Log.error() << "calculateOoiEnergy: cannot find section [OoiTypes] in file "
					<< parameters.getFilename() << "." << endl;
				return;
			}
			if (!type_section.hasVariable("type"))
			{
				Log.error() << "OoiEnergy: section [OoiTypes] of file "
					<< parameters.getFilename() << " does not contain a variable column 'type'." << endl;
				return;
			}

			// extract the parameters for each type
			//
			Position radius_column = parameter_section.getColumnIndex("radius");
			Position g_column = parameter_section.getColumnIndex("g");
			Index max_index = -1;
			Size i;
			for (i = 1; i <= parameter_section.getNumberOfKeys(); i++)
			{
				Index index = parameter_section.getKey(i).toInt();
				if (index < 0)
				{
					Log.error() << "calculateOoiEnergy: illegal atom type index: " << index << endl;
				}
				else
				{
					if (index > max_index)
					{
						max_index = index;
					}
				}
			}

			if (max_index < 0)
			{
				Log.error() << "calculateOoiEnergy: could not find any atom type in file "
									  << parameters.getFilename() << endl;
				return;
			}

			// resize the vectors to hold all indices
			radius.resize((Size)max_index + 1);
			g.resize((Size)max_index + 1);

			// and read all values from the parameter section
			for (i = 1; i <= parameter_section.getNumberOfKeys(); i++)
			{
				Index index = parameter_section.getKey(i).toInt();

				// we ignore illegal (negative) indices
				if (index >= 0)
				{
					radius[index] = parameter_section.getValue(i, radius_column).toFloat();
					g[index] = parameter_section.getValue(i, g_column).toFloat();
				}
			}

			// extract all known types by iterating over all keys
		  // and construct the hash map type_map
			Position type_column = type_section.getColumnIndex("type");
			for (i = 1; i <= type_section.getNumberOfKeys(); i++)
			{
				// retrieve the type and check for validity
				Atom::Type type = type_section.getValue(i, type_column).toInt();
				if (type >= (Atom::Type)radius.size())
				{
					Log.error() << "calculateOoiEnergy: illegal atom type: " << type << " while reading parameter file." << endl;
				}
				else
				{
					type_map.insert(type_section.getKey(i), (Atom::Type)type_section.getValue(i, type_column).toInt());
				}
			}

			// set up the type rule processor
			// from the rules in the INI file
			type_rule.initialize(parameters.getParameterFile(), "TypeRules");

			// we're done with the initialization
			is_initialized = true;
		}
	}

	double calculateOoiEnergy(BaseFragment& fragment)
	{
		using namespace OoiEnergy;

		// read and interpret the parameters
		// this is only done the first time calculateOoiEnergy is called
		if (!is_initialized)
		{
			init();
			if (!is_initialized)
			{
				return 0;
			}
		}

		// assign radii and atom types for all atoms
		AtomIterator atom_it = fragment.beginAtom();
		for (; +atom_it; ++atom_it)
		{
			// construct correct name, <RESNAME>:<ATOMNAME>
			String atom_name = atom_it->getFullName();

			// get the atom type from hash table
			// first, try a direct match
			Atom::Type atom_type = -1;
			if (type_map.has(atom_name))
			{
				atom_type = type_map[atom_name];
			}
			else
			{
				atom_name = atom_it->getFullName(Atom::NO_VARIANT_EXTENSIONS);
				if (type_map.has(atom_name))
				{
					atom_type = type_map[atom_name];
				}
				else
				{
					// try wildcard match
					atom_name = "*:" + atom_it->getName();
					if (type_map.has(atom_name))
					{
						atom_type = type_map[atom_name];
					}
				}
			}

			// if the atom type could not be determined, complain
			if (atom_type < 0)
			{
				// try to apply the type rule processor
				atom_it->setType(-1);
				type_rule(*atom_it);
				atom_type = atom_it->getType();
			}

			if (atom_type < 0)
			{
				Log.warn() << "calculateOOIEnergy: did not find a suitable type for " << atom_it->getFullName() << endl;

				// ignore this atom....
				atom_it->setType(-1);
				atom_it->setRadius(0.0);
			}
			else
			{
				// assign type and radius
				atom_it->setType(atom_type);
				atom_it->setRadius(radius[atom_type]);
			}
		}

		// calculate the atomic SAS areas
		// atom_SAS_areas hashes the atom pointer to the
		// surface area (in Angstrom^2)
		HashMap<Atom*,float> atom_SAS_areas;
		calculateNumericalSASAtomAreas(fragment, atom_SAS_areas, 1.4, 1888);

		// iterate over all atoms and add up the energies
		float energy = 0.0;
		for (atom_it = fragment.beginAtom(); +atom_it; ++atom_it)
		{

			if (atom_SAS_areas.has(&*atom_it))
			{
				Atom::Type atom_type = atom_it->getType();
				// if the atom type could not be determined, complain
				if (atom_type >= 0)
				{
					// add the energy contribution of the atom
					float tmp = atom_SAS_areas[&*atom_it] * g[atom_type];
					energy += tmp;
				}
			}
		}

		// we're done.
		return energy;
	}

} // namespace BALL
<|endoftext|>


<commit_before>#include <PluginFactory/PluginFactory.hpp>
#include <PluginFactory/details/PolicyProperties.hpp>

#include <load_plugins/PluginInterface.hpp>
#include <load_plugins/PluginServiceInterface.hpp>

#include "ConcreteService.hpp"

#include <iostream>
#include <memory>

using MyPlugin = std::unique_ptr<load_plugins::MyPlugin, PluginFactory::PluginDeleter<load_plugins::MyPlugin>>;
using MyPluginFactory = PluginFactory::PluginFactory<load_plugins::MyPlugin, load_plugins::PluginServiceInterface, PluginFactory::details::PolicyIsExternal>;

int usage(char const * const programName);
int run(int argc, char** argv);

void printPluginNames(const std::vector<std::string>& plugins);
void createPlugins(MyPluginFactory& factory, const std::vector<std::string>& availablePlugins, std::deque<MyPlugin>& plugins);
void callPlugins(const std::deque<MyPlugin>& plugins);

int main(int argc, char** argv)
{
    if(argc < 2)
    {
        return usage(argv[0]);
    }

    try
    {
        return run(argc, argv);
    }
    catch(const std::exception& e )
    {
        std::cerr << e.what() << std::endl;
    }

    return -1;
}

int usage(char const * const programName)
{
    std::cerr << "Usage: " << programName << " <plugin_path>" << std::endl;
    return -1;
}

int run(int /*argc*/, char** argv)
{
    std::string pluginPath(argv[1]);
    std::deque<MyPlugin> plugins;

    std::unique_ptr<load_plugins::PluginServiceInterface> service(new load_plugins::ConcreteService());
    MyPluginFactory factory(pluginPath, *service);
    factory.load();

    auto availablePlugins = factory.availablePlugins();
    printPluginNames(availablePlugins);
    createPlugins(factory, availablePlugins, plugins);

    callPlugins(plugins);
    service->report();

    return 0;
}

void printPluginNames(const std::vector<std::string>& plugins)
{
    std::cout << "loaded: ";
    for(const auto& pluginName : plugins)
    {
        std::cout << pluginName << " ";
    }
    std::cout << std::endl;
}

void createPlugins(MyPluginFactory& factory, const std::vector<std::string>& availablePlugins, std::deque<MyPlugin>& plugins)
{
    for(const auto& pluginName : availablePlugins)
    {
        plugins.emplace_back(factory.instance(pluginName));
    }
}

void callPlugins(const std::deque<MyPlugin>& plugins)
{
    for(auto& plugin : plugins)
    {
        plugin->do_stuff();
    }
}

<commit_msg>Change the plugin handle to a raw pointer, we won't be responsible for cleaning up the memory - the plugin shared library must do that.<commit_after>#include <PluginFactory/PluginFactory.hpp>
#include <PluginFactory/details/PolicyProperties.hpp>

#include <load_plugins/PluginInterface.hpp>
#include <load_plugins/PluginServiceInterface.hpp>

#include "ConcreteService.hpp"

#include <iostream>
#include <memory>

using MyPlugin = load_plugins::MyPlugin*;
using MyPluginFactory = PluginFactory::PluginFactory<load_plugins::MyPlugin, load_plugins::PluginServiceInterface, PluginFactory::details::PolicyIsExternal>;

int usage(char const * const programName);
int run(int argc, char** argv);

void printPluginNames(const std::vector<std::string>& plugins);
void createPlugins(MyPluginFactory& factory, const std::vector<std::string>& availablePlugins, std::deque<MyPlugin>& plugins);
void callPlugins(const std::deque<MyPlugin>& plugins);

int main(int argc, char** argv)
{
    if(argc < 2)
    {
        return usage(argv[0]);
    }

    try
    {
        return run(argc, argv);
    }
    catch(const std::exception& e )
    {
        std::cerr << e.what() << std::endl;
    }

    return -1;
}

int usage(char const * const programName)
{
    std::cerr << "Usage: " << programName << " <plugin_path>" << std::endl;
    return -1;
}

int run(int /*argc*/, char** argv)
{
    std::string pluginPath(argv[1]);
    std::deque<MyPlugin> plugins;

    std::unique_ptr<load_plugins::PluginServiceInterface> service(new load_plugins::ConcreteService());
    MyPluginFactory factory(pluginPath, *service);
    factory.load();

    auto availablePlugins = factory.availablePlugins();
    printPluginNames(availablePlugins);
    createPlugins(factory, availablePlugins, plugins);

    callPlugins(plugins);
    service->report();

    return 0;
}

void printPluginNames(const std::vector<std::string>& plugins)
{
    std::cout << "loaded: ";
    for(const auto& pluginName : plugins)
    {
        std::cout << pluginName << " ";
    }
    std::cout << std::endl;
}

void createPlugins(MyPluginFactory& factory, const std::vector<std::string>& availablePlugins, std::deque<MyPlugin>& plugins)
{
    for(const auto& pluginName : availablePlugins)
    {
        plugins.emplace_back(factory.instance(pluginName));
    }
}

void callPlugins(const std::deque<MyPlugin>& plugins)
{
    for(auto& plugin : plugins)
    {
        plugin->do_stuff();
    }
}

<|endoftext|>


<commit_before>#pragma once

#pragma message("NETClassBase.hpp - 1")
#include "NETClassBase.inl"
#pragma message("NETClassBase.hpp - 2")
#include "NETClass.hpp"
#pragma message("NETClassBase.hpp - 3")
#pragma message("NETClassBase.hpp - 4")
#include "../NETDerivedClassChecker/NETDerivedClassChecker.hpp"
#pragma message("NETClassBase.hpp - 5")
#include "../NETTemplateChecker/NETTemplateChecker.hpp"
#pragma message("NETClassBase.hpp - 6")
//	We must include ADTChecker after loaded TClass declarations and its
//	implementations(= TClass.hpp).
//	Why do we have to keep this sequence:
//		in order to use ADTChecker including TClass must be predeterminded first.
//		because ADTChecker can checks whether T is kind of Interface Class by
//		applying SFINAE with TInterfaceClass(is part of TClass.hpp)
#pragma message("NETClassBase.hpp - 7")
#include "../NETADTChecker/NETADTChecker.hpp"
#pragma message("NETClassBase.hpp - 8")
//	Following one is just same as above.
#include "../NETUnknownMetaClass/NETUnknownMetaClass.hpp"
#pragma message("NETClassBase.hpp - 9")

namespace NE
{
	template <typename T>
	const NEClassBase& NETClassBase<T>::getClassStatically()
	{
		//	What is this:
		//		When NETClass is templated with some parameter type T,
		//		it's a problem to provide metaclass of NETClass. (of course,
		//		because NETClass is a kind of metaclass, giving metaclass of
		//		metaclass is the problem mentioned above)
		//		The reason which this going to be a problem is templating reculsively.
		//		Just imagine NETClass<T> that is returning NETClassMetaClass as
		//		its metaclass.
		//		so, this get crack the codes. to prevent this, we replace metaclass
		//		to NETMetaClass. Dummy.
		//		All NETClass<T> will return NETClassMetaClass at getClass()
		//		method.
		static NETClassMetaClass inner;

		return inner;
	}

	template <typename T>
	const NEClassBase& NETClassBase<T>::getClass() const
	{
		return getClassStatically();
	}

	template <typename T>
	NEObject& NETClassBase<T>::clone() const
	{
		return *(new This(*this));
	}

	template <typename T>
	const NETString& NETClassBase<T>::getName() const
	{
		return getNameStatically();
	}

	template <typename T>
	const type_bool& NETClassBase<T>::isRegistered() const
	{
		return isRegisteredStatically();
	}

	template <typename T>
	const NEClassBaseList& NETClassBase<T>::getSuperClasses() const
	{
		return getSuperClassesStatically();
	}

	template <typename T>
	const NEClassBaseList& NETClassBase<T>::getChildrenClasses() const
	{
		return getChildrenClassesStatically();
	}

	template <typename T>
	type_bool NETClassBase<T>::isMetaClassDefined() const
	{
		return isMetaClassDefinedStatically();
	}

	template <typename T>
	type_bool NETClassBase<T>::isInstantiable() const
	{
		return isInstantiableStatically();
	}

	template <typename T>
	type_bool NETClassBase<T>::isTemplate() const
	{
		return isTemplateStatically();
	}

	template <typename T>
	type_bool NETClassBase<T>::isBuiltInClass() const
	{
		return isBuiltInClassStatically();
	}

	template <typename T>
	const NEClassBase& NETClassBase<T>::getTraitClass() const
	{
		return getTraitClassStatically();
	}

	template <typename T>
	const NETString& NETClassBase<T>::getNameStatically()
	{
		static NETString _inner;

		if (_inner.getLength() <= 0)
			_inner = typeid(T).name();

		return _inner;
	}

	template <typename T>
	const NEHeader& NETClassBase<T>::getHeader() const
	{
		return getHeaderStatically();
	}

	template <typename T>
	const NEHeader& NETClassBase<T>::getHeaderStatically()
	{
		static NEHeader _inner;

		return _inner;
	}

	template <typename T>
	const type_bool& NETClassBase<T>::isRegisteredStatically()
	{
		static type_bool _inner;

		return _inner;
	}

	template <typename T>
	const NEClassBaseList& NETClassBase<T>::getSuperClassesStatically()
	{
		static NEClassBaseList _inner;

		return _inner;
	}
	template <typename T>
	const NEClassBaseList& NETClassBase<T>::getChildrenClassesStatically()
	{
		static NEClassBaseList _inner;

		return _inner;
	}

	template <typename T>
	const type_id& NETClassBase<T>::getId() const
	{
		return getIdStatically();
	}

	template <typename T>
	const type_id& NETClassBase<T>::getIdStatically()
	{
		static type_id _inner;

		return _inner;
	}

	template <typename T>
	const NEClassBase& NETClassBase<T>::getTraitClassStatically()
	{
		static NETClass<Trait> _inner;

		return _inner;
	}

	template <typename T>
	type_bool NETClassBase<T>::isBuiltInClassStatically()
	{
		return NETDerivedClassChecker<T, NEObject>::IS_DERIVED_OF;
	}

	template <typename T>
	type_bool NETClassBase<T>::isTemplateStatically()
	{
		return NETTemplateChecker<T>::IS_TEMPLATE;
	}

	template <typename T>
	type_bool NETClassBase<T>::isInstantiableStatically()
	{
		return NETADTChecker<T>::IS_ADT;
	}

	template <typename T>
	type_bool NETClassBase<T>::isMetaClassDefinedStatically()
	{
		return NETMetaClassChecker<T>::IS_METACLASS_DEFINED;
	}

	template <typename T>
	const NEPackagePtr& NETClassBase<T>::_getPackage() const
	{
		static NEPackagePtr _inner = NE_NULL;

		return _inner;
	}
}<commit_msg>- NETClassBase misses header file "NEHeader.hpp"<commit_after>#pragma once

#pragma message("NETClassBase.hpp - 1")
#include "NETClassBase.inl"
#pragma message("NETClassBase.hpp - 2")
#include "NETClass.hpp"
#pragma message("NETClassBase.hpp - 3")
#include "../NEHeader/NEHeader.hpp"
#pragma message("NETClassBase.hpp - 4")
#include "../NETDerivedClassChecker/NETDerivedClassChecker.hpp"
#pragma message("NETClassBase.hpp - 5")
#include "../NETTemplateChecker/NETTemplateChecker.hpp"
#pragma message("NETClassBase.hpp - 6")
//	We must include ADTChecker after loaded TClass declarations and its
//	implementations(= TClass.hpp).
//	Why do we have to keep this sequence:
//		in order to use ADTChecker including TClass must be predeterminded first.
//		because ADTChecker can checks whether T is kind of Interface Class by
//		applying SFINAE with TInterfaceClass(is part of TClass.hpp)
#pragma message("NETClassBase.hpp - 7")
#include "../NETADTChecker/NETADTChecker.hpp"
#pragma message("NETClassBase.hpp - 8")
//	Following one is just same as above.
#include "../NETUnknownMetaClass/NETUnknownMetaClass.hpp"
#pragma message("NETClassBase.hpp - 9")

namespace NE
{
	template <typename T>
	const NEClassBase& NETClassBase<T>::getClassStatically()
	{
		//	What is this:
		//		When NETClass is templated with some parameter type T,
		//		it's a problem to provide metaclass of NETClass. (of course,
		//		because NETClass is a kind of metaclass, giving metaclass of
		//		metaclass is the problem mentioned above)
		//		The reason which this going to be a problem is templating reculsively.
		//		Just imagine NETClass<T> that is returning NETClassMetaClass as
		//		its metaclass.
		//		so, this get crack the codes. to prevent this, we replace metaclass
		//		to NETMetaClass. Dummy.
		//		All NETClass<T> will return NETClassMetaClass at getClass()
		//		method.
		static NETClassMetaClass inner;

		return inner;
	}

	template <typename T>
	const NEClassBase& NETClassBase<T>::getClass() const
	{
		return getClassStatically();
	}

	template <typename T>
	NEObject& NETClassBase<T>::clone() const
	{
		return *(new This(*this));
	}

	template <typename T>
	const NETString& NETClassBase<T>::getName() const
	{
		return getNameStatically();
	}

	template <typename T>
	const type_bool& NETClassBase<T>::isRegistered() const
	{
		return isRegisteredStatically();
	}

	template <typename T>
	const NEClassBaseList& NETClassBase<T>::getSuperClasses() const
	{
		return getSuperClassesStatically();
	}

	template <typename T>
	const NEClassBaseList& NETClassBase<T>::getChildrenClasses() const
	{
		return getChildrenClassesStatically();
	}

	template <typename T>
	type_bool NETClassBase<T>::isMetaClassDefined() const
	{
		return isMetaClassDefinedStatically();
	}

	template <typename T>
	type_bool NETClassBase<T>::isInstantiable() const
	{
		return isInstantiableStatically();
	}

	template <typename T>
	type_bool NETClassBase<T>::isTemplate() const
	{
		return isTemplateStatically();
	}

	template <typename T>
	type_bool NETClassBase<T>::isBuiltInClass() const
	{
		return isBuiltInClassStatically();
	}

	template <typename T>
	const NEClassBase& NETClassBase<T>::getTraitClass() const
	{
		return getTraitClassStatically();
	}

	template <typename T>
	const NETString& NETClassBase<T>::getNameStatically()
	{
		static NETString _inner;

		if (_inner.getLength() <= 0)
			_inner = typeid(T).name();

		return _inner;
	}

	template <typename T>
	const NEHeader& NETClassBase<T>::getHeader() const
	{
		return getHeaderStatically();
	}

	template <typename T>
	const NEHeader& NETClassBase<T>::getHeaderStatically()
	{
		static NEHeader _inner;

		return _inner;
	}

	template <typename T>
	const type_bool& NETClassBase<T>::isRegisteredStatically()
	{
		static type_bool _inner;

		return _inner;
	}

	template <typename T>
	const NEClassBaseList& NETClassBase<T>::getSuperClassesStatically()
	{
		static NEClassBaseList _inner;

		return _inner;
	}
	template <typename T>
	const NEClassBaseList& NETClassBase<T>::getChildrenClassesStatically()
	{
		static NEClassBaseList _inner;

		return _inner;
	}

	template <typename T>
	const type_id& NETClassBase<T>::getId() const
	{
		return getIdStatically();
	}

	template <typename T>
	const type_id& NETClassBase<T>::getIdStatically()
	{
		static type_id _inner;

		return _inner;
	}

	template <typename T>
	const NEClassBase& NETClassBase<T>::getTraitClassStatically()
	{
		static NETClass<Trait> _inner;

		return _inner;
	}

	template <typename T>
	type_bool NETClassBase<T>::isBuiltInClassStatically()
	{
		return NETDerivedClassChecker<T, NEObject>::IS_DERIVED_OF;
	}

	template <typename T>
	type_bool NETClassBase<T>::isTemplateStatically()
	{
		return NETTemplateChecker<T>::IS_TEMPLATE;
	}

	template <typename T>
	type_bool NETClassBase<T>::isInstantiableStatically()
	{
		return NETADTChecker<T>::IS_ADT;
	}

	template <typename T>
	type_bool NETClassBase<T>::isMetaClassDefinedStatically()
	{
		return NETMetaClassChecker<T>::IS_METACLASS_DEFINED;
	}

	template <typename T>
	const NEPackagePtr& NETClassBase<T>::_getPackage() const
	{
		static NEPackagePtr _inner = NE_NULL;

		return _inner;
	}
}<|endoftext|>