<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Machinecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <protocol.h>

#include <util.h>
#include <utilstrencodings.h>

#ifndef WIN32
# include <arpa/inet.h>
#endif

namespace NetMsgType {
const char *VERSION="version";
const char *VERACK="verack";
const char *ADDR="addr";
const char *INV="inv";
const char *GETDATA="getdata";
const char *MERKLEBLOCK="merkleblock";
const char *GETBLOCKS="getblocks";
const char *GETHEADERS="getheaders";
const char *TX="tx";
const char *HEADERS="headers";
const char *BLOCK="block";
const char *GETADDR="getaddr";
const char *MEMPOOL="mempool";
const char *PING="ping";
const char *PONG="pong";
const char *NOTFOUND="notfound";
const char *FILTERLOAD="filterload";
const char *FILTERADD="filteradd";
const char *FILTERCLEAR="filterclear";
const char *REJECT="reject";
const char *SENDHEADERS="sendheaders";
const char *FEEFILTER="feefilter";
const char *SENDCMPCT="sendcmpct";
const char *CMPCTBLOCK="cmpctblock";
const char *GETBLOCKTXN="getblocktxn";
const char *BLOCKTXN="blocktxn";
// Machinecoin message types
const char *MASTERNODEPAYMENTVOTE="mnw";
const char *MASTERNODEPAYMENTBLOCK="mnwb";
const char *MASTERNODEPAYMENTSYNC="mnget";
const char *MNQUORUM="mn quorum"; // not implemented
const char *MNANNOUNCE="mnb";
const char *MNPING="mnp";
const char *DSEG="dseg";
const char *SYNCSTATUSCOUNT="ssc";
const char *MNGOVERNANCESYNC="govsync";
const char *MNGOVERNANCEOBJECT="govobj";
const char *MNGOVERNANCEOBJECTVOTE="govobjvote";
const char *MNVERIFY="mnv";
} // namespace NetMsgType

/** All known message types. Keep this in the same order as the list of
 * messages above and in protocol.h.
 */
const static std::string allNetMessageTypes[] = {
    NetMsgType::VERSION,
    NetMsgType::VERACK,
    NetMsgType::ADDR,
    NetMsgType::INV,
    NetMsgType::GETDATA,
    NetMsgType::MERKLEBLOCK,
    NetMsgType::GETBLOCKS,
    NetMsgType::GETHEADERS,
    NetMsgType::TX,
    NetMsgType::HEADERS,
    NetMsgType::BLOCK,
    NetMsgType::GETADDR,
    NetMsgType::MEMPOOL,
    NetMsgType::PING,
    NetMsgType::PONG,
    NetMsgType::NOTFOUND,
    NetMsgType::FILTERLOAD,
    NetMsgType::FILTERADD,
    NetMsgType::FILTERCLEAR,
    NetMsgType::REJECT,
    NetMsgType::SENDHEADERS,
    NetMsgType::FEEFILTER,
    NetMsgType::SENDCMPCT,
    NetMsgType::CMPCTBLOCK,
    NetMsgType::GETBLOCKTXN,
    NetMsgType::BLOCKTXN,
    // Machinecoin message types
    // NOTE: do NOT include non-implmented here, we want them to be "Unknown command" in ProcessMessage()
    NetMsgType::MASTERNODEPAYMENTVOTE,
    // NetMsgType::MASTERNODEPAYMENTBLOCK, // there is no message for this, only inventory
    NetMsgType::MASTERNODEPAYMENTSYNC,
    NetMsgType::MNANNOUNCE,
    NetMsgType::MNPING,
    NetMsgType::DSEG,
    NetMsgType::SYNCSTATUSCOUNT,
    NetMsgType::MNGOVERNANCESYNC,
    NetMsgType::MNGOVERNANCEOBJECT,
    NetMsgType::MNGOVERNANCEOBJECTVOTE,
    NetMsgType::MNVERIFY,
};
const static std::vector<std::string> allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes));

CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)
{
    memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    nMessageSize = -1;
    memset(pchChecksum, 0, CHECKSUM_SIZE);
}

CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
{
    memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    strncpy(pchCommand, pszCommand, COMMAND_SIZE);
    nMessageSize = nMessageSizeIn;
    memset(pchChecksum, 0, CHECKSUM_SIZE);
}

std::string CMessageHeader::GetCommand() const
{
    return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));
}

bool CMessageHeader::IsValid(const MessageStartChars& pchMessageStartIn) const
{
    // Check start string
    if (memcmp(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE) != 0)
        return false;

    // Check the command string for errors
    for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
    {
        if (*p1 == 0)
        {
            // Must be all zeros after the first zero
            for (; p1 < pchCommand + COMMAND_SIZE; p1++)
                if (*p1 != 0)
                    return false;
        }
        else if (*p1 < ' ' || *p1 > 0x7E)
            return false;
    }

    // Message size
    if (nMessageSize > MAX_SIZE)
    {
        LogPrintf("CMessageHeader::IsValid(): (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
        return false;
    }

    return true;
}

CAddress::CAddress() : CService()
{
    Init();
}

CAddress::CAddress(CService ipIn, ServiceFlags nServicesIn) : CService(ipIn)
{
    Init();
    nServices = nServicesIn;
}

void CAddress::Init()
{
    nServices = NODE_NONE;
    nTime = 100000000;
}

CInv::CInv()
{
    type = 0;
    hash.SetNull();
}

CInv::CInv(int typeIn, const uint256& hashIn) : type(typeIn), hash(hashIn) {}

bool operator<(const CInv& a, const CInv& b)
{
    return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
}

bool IsKnownType(int typeIn)
{
    LogPrintf("TYPEIN %s\n", typeIn);
    return (typeIn >= 1 && typeIn < (int)ARRAYLEN(allNetMessageTypes));
}

std::string CInv::GetCommand() const
{
    //IsKnownType();
    std::string cmd;
    if (type & MSG_WITNESS_FLAG)
        cmd.append("witness-");
    int masked = type & MSG_TYPE_MASK;
    switch (masked)
    {
    case MSG_TX:             return cmd.append(NetMsgType::TX);
    case MSG_BLOCK:          return cmd.append(NetMsgType::BLOCK);
    case MSG_FILTERED_BLOCK: return cmd.append(NetMsgType::MERKLEBLOCK);
    case MSG_CMPCT_BLOCK:    return cmd.append(NetMsgType::CMPCTBLOCK);
    default:
        LogPrintf("TYPE %s\n", type);
        if (!IsKnownType(type))
            throw std::out_of_range(strprintf("CInv::GetCommand(): type=%d unknown type", type));
        else
            return allNetMessageTypes[type];
    }
}

std::string CInv::ToString() const
{
    try {
        return strprintf("%s %s", GetCommand(), hash.ToString());
    } catch(const std::out_of_range &) {
        return strprintf("0x%08x %s", type, hash.ToString());
    }
}

const std::vector<std::string> &getAllNetMessageTypes()
{
    return allNetMessageTypesVec;
}
<commit_msg>Added ppszTypes again<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Machinecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <protocol.h>

#include <util.h>
#include <utilstrencodings.h>

#ifndef WIN32
# include <arpa/inet.h>
#endif

namespace NetMsgType {
const char *VERSION="version";
const char *VERACK="verack";
const char *ADDR="addr";
const char *INV="inv";
const char *GETDATA="getdata";
const char *MERKLEBLOCK="merkleblock";
const char *GETBLOCKS="getblocks";
const char *GETHEADERS="getheaders";
const char *TX="tx";
const char *HEADERS="headers";
const char *BLOCK="block";
const char *GETADDR="getaddr";
const char *MEMPOOL="mempool";
const char *PING="ping";
const char *PONG="pong";
const char *NOTFOUND="notfound";
const char *FILTERLOAD="filterload";
const char *FILTERADD="filteradd";
const char *FILTERCLEAR="filterclear";
const char *REJECT="reject";
const char *SENDHEADERS="sendheaders";
const char *FEEFILTER="feefilter";
const char *SENDCMPCT="sendcmpct";
const char *CMPCTBLOCK="cmpctblock";
const char *GETBLOCKTXN="getblocktxn";
const char *BLOCKTXN="blocktxn";
// Machinecoin message types
const char *MASTERNODEPAYMENTVOTE="mnw";
const char *MASTERNODEPAYMENTBLOCK="mnwb";
const char *MASTERNODEPAYMENTSYNC="mnget";
const char *MNQUORUM="mn quorum"; // not implemented
const char *MNANNOUNCE="mnb";
const char *MNPING="mnp";
const char *DSEG="dseg";
const char *SYNCSTATUSCOUNT="ssc";
const char *MNGOVERNANCESYNC="govsync";
const char *MNGOVERNANCEOBJECT="govobj";
const char *MNGOVERNANCEOBJECTVOTE="govobjvote";
const char *MNVERIFY="mnv";
} // namespace NetMsgType

const static std::string ppszTypeName[] =
{
    "ERROR", // Should never occur
    NetMsgType::TX,
    NetMsgType::BLOCK,
    NetMsgType::MERKLEBLOCK,
    NetMsgType::CMPCTBLOCK,
    // Machinecoin message types
    // NOTE: include non-implmented here, we must keep this list in sync with enum in protocol.h
    NetMsgType::MASTERNODEPAYMENTVOTE,
    NetMsgType::MASTERNODEPAYMENTBLOCK, // reusing, was MNSCANERROR previousely, was NOT used in 12.0, we need this for inv
    NetMsgType::MNQUORUM, // not implemented
    NetMsgType::MNANNOUNCE,
    NetMsgType::MNPING,
    NetMsgType::MNGOVERNANCEOBJECT,
    NetMsgType::MNGOVERNANCEOBJECTVOTE,
    NetMsgType::MNVERIFY,
};

/** All known message types. Keep this in the same order as the list of
 * messages above and in protocol.h.
 */
const static std::string allNetMessageTypes[] = {
    NetMsgType::VERSION,
    NetMsgType::VERACK,
    NetMsgType::ADDR,
    NetMsgType::INV,
    NetMsgType::GETDATA,
    NetMsgType::MERKLEBLOCK,
    NetMsgType::GETBLOCKS,
    NetMsgType::GETHEADERS,
    NetMsgType::TX,
    NetMsgType::HEADERS,
    NetMsgType::BLOCK,
    NetMsgType::GETADDR,
    NetMsgType::MEMPOOL,
    NetMsgType::PING,
    NetMsgType::PONG,
    NetMsgType::NOTFOUND,
    NetMsgType::FILTERLOAD,
    NetMsgType::FILTERADD,
    NetMsgType::FILTERCLEAR,
    NetMsgType::REJECT,
    NetMsgType::SENDHEADERS,
    NetMsgType::FEEFILTER,
    NetMsgType::SENDCMPCT,
    NetMsgType::CMPCTBLOCK,
    NetMsgType::GETBLOCKTXN,
    NetMsgType::BLOCKTXN,
    // Machinecoin message types
    // NOTE: do NOT include non-implmented here, we want them to be "Unknown command" in ProcessMessage()
    NetMsgType::MASTERNODEPAYMENTVOTE,
    // NetMsgType::MASTERNODEPAYMENTBLOCK, // there is no message for this, only inventory
    NetMsgType::MASTERNODEPAYMENTSYNC,
    NetMsgType::MNANNOUNCE,
    NetMsgType::MNPING,
    NetMsgType::DSEG,
    NetMsgType::SYNCSTATUSCOUNT,
    NetMsgType::MNGOVERNANCESYNC,
    NetMsgType::MNGOVERNANCEOBJECT,
    NetMsgType::MNGOVERNANCEOBJECTVOTE,
    NetMsgType::MNVERIFY,
};
const static std::vector<std::string> allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes));

CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)
{
    memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    nMessageSize = -1;
    memset(pchChecksum, 0, CHECKSUM_SIZE);
}

CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
{
    memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    strncpy(pchCommand, pszCommand, COMMAND_SIZE);
    nMessageSize = nMessageSizeIn;
    memset(pchChecksum, 0, CHECKSUM_SIZE);
}

std::string CMessageHeader::GetCommand() const
{
    return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));
}

bool CMessageHeader::IsValid(const MessageStartChars& pchMessageStartIn) const
{
    // Check start string
    if (memcmp(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE) != 0)
        return false;

    // Check the command string for errors
    for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
    {
        if (*p1 == 0)
        {
            // Must be all zeros after the first zero
            for (; p1 < pchCommand + COMMAND_SIZE; p1++)
                if (*p1 != 0)
                    return false;
        }
        else if (*p1 < ' ' || *p1 > 0x7E)
            return false;
    }

    // Message size
    if (nMessageSize > MAX_SIZE)
    {
        LogPrintf("CMessageHeader::IsValid(): (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
        return false;
    }

    return true;
}

CAddress::CAddress() : CService()
{
    Init();
}

CAddress::CAddress(CService ipIn, ServiceFlags nServicesIn) : CService(ipIn)
{
    Init();
    nServices = nServicesIn;
}

void CAddress::Init()
{
    nServices = NODE_NONE;
    nTime = 100000000;
}

CInv::CInv()
{
    type = 0;
    hash.SetNull();
}

CInv::CInv(int typeIn, const uint256& hashIn) : type(typeIn), hash(hashIn) {}

bool operator<(const CInv& a, const CInv& b)
{
    return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
}

bool IsKnownType(int typeIn)
{
    LogPrintf("TYPEIN %s\n", typeIn);
    return (typeIn >= 1 && typeIn < (int)ARRAYLEN(ppszTypeName));
}

std::string CInv::GetCommand() const
{
    std::string cmd;
    if (type & MSG_WITNESS_FLAG)
        cmd.append("witness-");
    int masked = type & MSG_TYPE_MASK;
    switch (masked)
    {
    case MSG_TX:             return cmd.append(NetMsgType::TX);
    case MSG_BLOCK:          return cmd.append(NetMsgType::BLOCK);
    case MSG_FILTERED_BLOCK: return cmd.append(NetMsgType::MERKLEBLOCK);
    case MSG_CMPCT_BLOCK:    return cmd.append(NetMsgType::CMPCTBLOCK);
    default:
        LogPrintf("TYPE %s\n",s type);
        if (!IsKnownType(type))
            throw std::out_of_range(strprintf("CInv::GetCommand(): type=%d unknown type", type));
        else
            return ppszTypeName[type];
    }
}

std::string CInv::ToString() const
{
    try {
        return strprintf("%s %s", GetCommand(), hash.ToString());
    } catch(const std::out_of_range &) {
        return strprintf("0x%08x %s", type, hash.ToString());
    }
}

const std::vector<std::string> &getAllNetMessageTypes()
{
    return allNetMessageTypesVec;
}
<|endoftext|>


<commit_before>/* -----------------------------------------------------------------------------

	Copyright (c) 2006 Simon Brown                          si@sjbrown.co.uk

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

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

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

   -------------------------------------------------------------------------- */

#include "maths.h"
#include <cfloat>

namespace nvsquish {

Sym3x3 ComputeWeightedCovariance( int n, Vec3 const* points, float const* weights, Vec3::Arg metric )
{
	// compute the centroid
	float total = 0.0f;
	Vec3 centroid( 0.0f );
	for( int i = 0; i < n; ++i )
	{
		total += weights[i];
		centroid += weights[i]*points[i];
	}
	centroid /= total;

	// accumulate the covariance matrix
	Sym3x3 covariance( 0.0f );
	for( int i = 0; i < n; ++i )
	{
		Vec3 a = (points[i] - centroid) * metric;
		Vec3 b = weights[i]*a;

		covariance[0] += a.X()*b.X();
		covariance[1] += a.X()*b.Y();
		covariance[2] += a.X()*b.Z();
		covariance[3] += a.Y()*b.Y();
		covariance[4] += a.Y()*b.Z();
		covariance[5] += a.Z()*b.Z();
	}

	// return it
	return covariance;
}

#if 1

Vec3 ComputePrincipleComponent( Sym3x3 const& matrix )
{
	const int NUM = 8;

	Vec3 v(1, 1, 1);
	for (int i = 0; i < NUM; i++)
    {
		float x = v.X() * matrix[0] + v.Y() * matrix[1] + v.Z() * matrix[2];
		float y = v.X() * matrix[1] + v.Y() * matrix[3] + v.Z() * matrix[4];
		float z = v.X() * matrix[2] + v.Y() * matrix[4] + v.Z() * matrix[5];

		float norm = std::max(std::max(x, y), z);

		float iv = 1.0f / norm;
		v = Vec3(x*iv, y*iv, z*iv);
	}

	return v;
}

#else

static Vec3 GetMultiplicity1Evector( Sym3x3 const& matrix, float evalue )
{
        // compute M
        Sym3x3 m;
        m[0] = matrix[0] - evalue;
        m[1] = matrix[1];
        m[2] = matrix[2];
        m[3] = matrix[3] - evalue;
        m[4] = matrix[4];
        m[5] = matrix[5] - evalue;

        // compute U
        Sym3x3 u;
        u[0] = m[3]*m[5] - m[4]*m[4];
        u[1] = m[2]*m[4] - m[1]*m[5];
        u[2] = m[1]*m[4] - m[2]*m[3];
        u[3] = m[0]*m[5] - m[2]*m[2];
        u[4] = m[1]*m[2] - m[4]*m[0];
        u[5] = m[0]*m[3] - m[1]*m[1];

        // find the largest component
        float mc = std::fabs( u[0] );
        int mi = 0;
        for( int i = 1; i < 6; ++i )
        {
                float c = std::fabs( u[i] );
                if( c > mc )
                {
                        mc = c;
                        mi = i;
                }
        }

        // pick the column with this component
        switch( mi )
        {
        case 0:
                return Vec3( u[0], u[1], u[2] );

        case 1:
        case 3:
                return Vec3( u[1], u[3], u[4] );

        default:
                return Vec3( u[2], u[4], u[5] );
        }
}

static Vec3 GetMultiplicity2Evector( Sym3x3 const& matrix, float evalue )
{
        // compute M
        Sym3x3 m;
        m[0] = matrix[0] - evalue;
        m[1] = matrix[1];
        m[2] = matrix[2];
        m[3] = matrix[3] - evalue;
        m[4] = matrix[4];
        m[5] = matrix[5] - evalue;

        // find the largest component
        float mc = std::fabs( m[0] );
        int mi = 0;
        for( int i = 1; i < 6; ++i )
        {
                float c = std::fabs( m[i] );
                if( c > mc )
                {
                        mc = c;
                        mi = i;
                }
        }

        // pick the first eigenvector based on this index
        switch( mi )
        {
        case 0:
        case 1:
                return Vec3( -m[1], m[0], 0.0f );

        case 2:
                return Vec3( m[2], 0.0f, -m[0] );

        case 3:
        case 4:
                return Vec3( 0.0f, -m[4], m[3] );

        default:
                return Vec3( 0.0f, -m[5], m[4] );
        }
}

Vec3 ComputePrincipleComponent( Sym3x3 const& matrix )
{
        // compute the cubic coefficients
        float c0 = matrix[0]*matrix[3]*matrix[5]
                + 2.0f*matrix[1]*matrix[2]*matrix[4]
                - matrix[0]*matrix[4]*matrix[4]
                - matrix[3]*matrix[2]*matrix[2]
                - matrix[5]*matrix[1]*matrix[1];
        float c1 = matrix[0]*matrix[3] + matrix[0]*matrix[5] + matrix[3]*matrix[5]
                - matrix[1]*matrix[1] - matrix[2]*matrix[2] - matrix[4]*matrix[4];
        float c2 = matrix[0] + matrix[3] + matrix[5];

        // compute the quadratic coefficients
        float a = c1 - ( 1.0f/3.0f )*c2*c2;
        float b = ( -2.0f/27.0f )*c2*c2*c2 + ( 1.0f/3.0f )*c1*c2 - c0;

        // compute the root count check
        float Q = 0.25f*b*b + ( 1.0f/27.0f )*a*a*a;

        // test the multiplicity
        if( FLT_EPSILON < Q )
        {
                // only one root, which implies we have a multiple of the identity
        return Vec3( 1.0f );
        }
        else if( Q < -FLT_EPSILON )
        {
                // three distinct roots
                float theta = std::atan2( std::sqrt( -Q ), -0.5f*b );
                float rho = std::sqrt( 0.25f*b*b - Q );

                float rt = std::pow( rho, 1.0f/3.0f );
                float ct = std::cos( theta/3.0f );
                float st = std::sin( theta/3.0f );

                float l1 = ( 1.0f/3.0f )*c2 + 2.0f*rt*ct;
                float l2 = ( 1.0f/3.0f )*c2 - rt*( ct + ( float )sqrt( 3.0f )*st );
                float l3 = ( 1.0f/3.0f )*c2 - rt*( ct - ( float )sqrt( 3.0f )*st );

                // pick the larger
                if( std::fabs( l2 ) > std::fabs( l1 ) )
                        l1 = l2;
                if( std::fabs( l3 ) > std::fabs( l1 ) )
                        l1 = l3;

                // get the eigenvector
                return GetMultiplicity1Evector( matrix, l1 );
        }
        else // if( -FLT_EPSILON <= Q && Q <= FLT_EPSILON )
        {
                // two roots
                float rt;
                if( b < 0.0f )
                        rt = -std::pow( -0.5f*b, 1.0f/3.0f );
                else
                        rt = std::pow( 0.5f*b, 1.0f/3.0f );

                float l1 = ( 1.0f/3.0f )*c2 + rt;               // repeated
                float l2 = ( 1.0f/3.0f )*c2 - 2.0f*rt;

                // get the eigenvector
                if( std::fabs( l1 ) > std::fabs( l2 ) )
                        return GetMultiplicity2Evector( matrix, l1 );
                else
                        return GetMultiplicity1Evector( matrix, l2 );
        }
}
#endif

} // namespace squish
<commit_msg>Add simd power solver.<commit_after>/* -----------------------------------------------------------------------------

	Copyright (c) 2006 Simon Brown                          si@sjbrown.co.uk

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

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

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

   -------------------------------------------------------------------------- */

#include "maths.h"
#include "simd.h"
#include <cfloat>

namespace nvsquish {

Sym3x3 ComputeWeightedCovariance( int n, Vec3 const* points, float const* weights, Vec3::Arg metric )
{
	// compute the centroid
	float total = 0.0f;
	Vec3 centroid( 0.0f );
	for( int i = 0; i < n; ++i )
	{
		total += weights[i];
		centroid += weights[i]*points[i];
	}
	centroid /= total;

	// accumulate the covariance matrix
	Sym3x3 covariance( 0.0f );
	for( int i = 0; i < n; ++i )
	{
		Vec3 a = (points[i] - centroid) * metric;
		Vec3 b = weights[i]*a;

		covariance[0] += a.X()*b.X();
		covariance[1] += a.X()*b.Y();
		covariance[2] += a.X()*b.Z();
		covariance[3] += a.Y()*b.Y();
		covariance[4] += a.Y()*b.Z();
		covariance[5] += a.Z()*b.Z();
	}

	// return it
	return covariance;
}

#define POWER_ITERATION_COUNT   8

#if SQUISH_USE_SIMD

Vec3 ComputePrincipleComponent( Sym3x3 const& matrix )
{
	Vec4 const row0( matrix[0], matrix[1], matrix[2], 0.0f );
	Vec4 const row1( matrix[1], matrix[3], matrix[4], 0.0f );
	Vec4 const row2( matrix[2], matrix[4], matrix[5], 0.0f );
	Vec4 v = VEC4_CONST( 1.0f );
	for( int i = 0; i < POWER_ITERATION_COUNT; ++i )
	{
		// matrix multiply
		Vec4 w = row0*v.SplatX();
		w = MultiplyAdd(row1, v.SplatY(), w);
		w = MultiplyAdd(row2, v.SplatZ(), w);

		// get max component from xyz in all channels
		Vec4 a = Max(w.SplatX(), Max(w.SplatY(), w.SplatZ()));

		// divide through and advance
		v = w*Reciprocal(a);
	}
	return v.GetVec3();
}

#else

Vec3 ComputePrincipleComponent( Sym3x3 const& matrix )
{
	Vec3 v(1, 1, 1);
	for (int i = 0; i < POWER_ITERATION_COUNT; i++)
	{
		float x = v.X() * matrix[0] + v.Y() * matrix[1] + v.Z() * matrix[2];
		float y = v.X() * matrix[1] + v.Y() * matrix[3] + v.Z() * matrix[4];
		float z = v.X() * matrix[2] + v.Y() * matrix[4] + v.Z() * matrix[5];

		float norm = std::max(std::max(x, y), z);
		float iv = 1.0f / norm;
		if (norm == 0.0f) {		// @@ I think this is not necessary in this case!!
			return Vec3(0.0f);
		}

		v = Vec3(x*iv, y*iv, z*iv);
	}

	return v;
}

#endif

} // namespace nvsquish
<|endoftext|>


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

#include <nvtt/nvtt.h>
#include <nvimage/Image.h>
#include <nvimage/ImageIO.h>
#include <nvimage/BlockDXT.h>
#include <nvimage/ColorBlock.h>
#include <nvcore/Ptr.h>
#include <nvcore/Debug.h>
#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>
#include <nvcore/TextWriter.h>

#include <stdlib.h> // free
#include <string.h> // memcpy
#include <time.h> // clock

using namespace nv;

static const char * s_fileNames[] = {
	// Kodak image set
	"kodim01.png",
	"kodim02.png",
	"kodim03.png",
	"kodim04.png",
	"kodim05.png",
	"kodim06.png",
	"kodim07.png",
	"kodim08.png",
	"kodim09.png",
	"kodim10.png",
	"kodim11.png",
	"kodim12.png",
	"kodim13.png",
	"kodim14.png",
	"kodim15.png",
	"kodim16.png",
	"kodim17.png",
	"kodim18.png",
	"kodim19.png",
	"kodim20.png",
	"kodim21.png",
	"kodim22.png",
	"kodim23.png",
	"kodim24.png",
	// Waterloo image set
	"clegg.png",
	"frymire.png",
	"lena.png",
	"monarch.png",
	"peppers.png",
	"sail.png",
	"serrano.png",
	"tulips.png",
	// Epic image set
	"Bradley1.png",
	"Gradient.png",
	"MoreRocks.png",
	"Wall.png",
	"Rainbow.png",
	"Text.png",
};
const int s_fileCount = sizeof(s_fileNames)/sizeof(s_fileNames[0]);

struct MyOutputHandler : public nvtt::OutputHandler
{
	MyOutputHandler() : m_data(NULL), m_ptr(NULL) {}
	~MyOutputHandler()
	{
		free(m_data);
	}

	virtual void beginImage(int size, int width, int height, int depth, int face, int miplevel)
	{
		m_size = size;
		m_width = width;
		m_height = height;
		free(m_data);
		m_data = (unsigned char *)malloc(size);
		m_ptr = m_data;
	}

	virtual bool writeData(const void * data, int size)
	{
		memcpy(m_ptr, data, size);
		m_ptr += size;
		return true;
	}

	Image * decompress(nvtt::Format format)
	{
		int bw = (m_width + 3) / 4;
		int bh = (m_height + 3) / 4;

		AutoPtr<Image> img( new Image() );
		img->allocate(m_width, m_height);

		if (format == nvtt::Format_BC1)
		{
			BlockDXT1 * block = (BlockDXT1 *)m_data;

			for (int y = 0; y < bh; y++)
			{
				for (int x = 0; x < bw; x++)
				{
					ColorBlock colors;
					block->decodeBlock(&colors);

					for (int yy = 0; yy < 4; yy++)
					{
						for (int xx = 0; xx < 4; xx++)
						{
							Color32 c = colors.color(xx, yy);

							if (x * 4 + xx < m_width && y * 4 + yy < m_height)
							{
								img->pixel(x * 4 + xx, y * 4 + yy) = c;
							}
						}
					}

					block++;
				}
			}
		}

		return img.release();
	}

	int m_size;
	int m_width;
	int m_height;
	unsigned char * m_data;
	unsigned char * m_ptr;
};

float rmsError(const Image * a, const Image * b)
{
	nvCheck(a != NULL);
	nvCheck(b != NULL);
	nvCheck(a->width() == b->width());
	nvCheck(a->height() == b->height());

	float mse = 0;

	const uint count = a->width() * a->height();

	for (uint i = 0; i < count; i++)
	{
		Color32 c0 = a->pixel(i);
		Color32 c1 = b->pixel(i);

		int r = c0.r - c1.r;
		int g = c0.g - c1.g;
		int b = c0.b - c1.b;
		//int a = c0.a - c1.a;

		mse += r * r;
		mse += g * g;
		mse += b * b;
	}

	mse /= count;

	return sqrtf(mse);
}

int main(int argc, char *argv[])
{
	const uint version = nvtt::version();
	const uint major = version / 100;
	const uint minor = version % 100;

	printf("NVIDIA Texture Tools %u.%u - Copyright NVIDIA Corporation 2007 - 2008\n\n", major, minor);

	bool fast = false;
	bool nocuda = false;
	bool showHelp = false;
	const char * outPath = "output";
	const char * regressPath = NULL;

	// Parse arguments.
	for (int i = 1; i < argc; i++)
	{
		if (strcmp("-fast", argv[i]) == 0)
		{
			fast = true;
		}
		else if (strcmp("-nocuda", argv[i]) == 0)
		{
			nocuda = true;
		}
		else if (strcmp("-help", argv[i]) == 0)
		{
			showHelp = true;
		}
		else if (strcmp("-out", argv[i]) == 0)
		{
			if (i+1 < argc && argv[i+1][0] != '-') outPath = argv[i+1];
		}
		else if (strcmp("-regress", argv[i]) == 0)
		{
			if (i+1 < argc && argv[i+1][0] != '-') regressPath = argv[i+1];
		}
	}

	if (showHelp)
	{
		printf("usage: nvtestsuite [options]\n\n");

		printf("Input options:\n");
		printf("  -regress <path>\tRegression directory.\n");

		printf("Compression options:\n");
		printf("  -fast          \tFast compression.\n");
		printf("  -nocuda        \tDo not use cuda compressor.\n");

		printf("Output options:\n");
		printf("  -out <path>    \tOutput directory.\n");

		return 1;
	}

	nvtt::InputOptions inputOptions;
	inputOptions.setMipmapGeneration(false);

	nvtt::CompressionOptions compressionOptions;
	compressionOptions.setFormat(nvtt::Format_BC1);
	if (fast)
	{
		compressionOptions.setQuality(nvtt::Quality_Fastest);
	}
	else
	{
		compressionOptions.setQuality(nvtt::Quality_Production);
	}

	nvtt::OutputOptions outputOptions;
	outputOptions.setOutputHeader(false);

	MyOutputHandler outputHandler;
	outputOptions.setOutputHandler(&outputHandler);

	nvtt::Compressor compressor;
	compressor.enableCudaAcceleration(!nocuda);

    // @@ Create outPath.

	Path csvFileName("%s/result.csv", outPath);
	StdOutputStream csvStream(csvFileName);
	TextWriter csvWriter(&csvStream);

	float totalTime = 0;
	float totalRMS = 0;
	int failedTests = 0;
	float totalDiff = 0;

	for (int i = 0; i < s_fileCount; i++)
	{
		AutoPtr<Image> img( new Image() );

		if (!img->load(s_fileNames[i]))
		{
			printf("Input image '%s' not found.\n", s_fileNames[i]);
			return EXIT_FAILURE;
		}

		inputOptions.setTextureLayout(nvtt::TextureType_2D, img->width(), img->height());
		inputOptions.setMipmapData(img->pixels(), img->width(), img->height());

		printf("Compressing: \t'%s'\n", s_fileNames[i]);

		clock_t start = clock();

		compressor.process(inputOptions, compressionOptions, outputOptions);

		clock_t end = clock();
		printf("  Time: \t%.3f sec\n", float(end-start) / CLOCKS_PER_SEC);
		totalTime += float(end-start);

		AutoPtr<Image> img_out( outputHandler.decompress(nvtt::Format_BC1) );

		Path outputFileName("%s/%s", outPath, s_fileNames[i]);
		outputFileName.stripExtension();
		outputFileName.append(".tga");
		if (!ImageIO::save(outputFileName, img_out.ptr()))
		{
			printf("Error saving file '%s'.\n", outputFileName.str());
		}

		float rms = rmsError(img.ptr(), img_out.ptr());
		totalRMS += rms;

		printf("  RMS:  \t%.4f\n", rms);

		// Output csv file
		csvWriter << "\"" << s_fileNames[i] << "\"," << rms << "\n";

		if (regressPath != NULL)
		{
			Path regressFileName("%s/%s", regressPath, s_fileNames[i]);
			regressFileName.stripExtension();
			regressFileName.append(".tga");

			AutoPtr<Image> img_reg( new Image() );
			if (!img_reg->load(regressFileName.str()))
			{
				printf("Regression image '%s' not found.\n", regressFileName.str());
				return EXIT_FAILURE;
			}

			float rms_reg = rmsError(img.ptr(), img_reg.ptr());

			float diff = rms_reg - rms;
			totalDiff += diff;

			const char * text = "PASSED";
			if (equal(diff, 0)) text = "PASSED";
			else if (diff < 0) {
				text = "FAILED";
				failedTests++;
			}

			printf("  Diff: \t%.4f (%s)\n", diff, text);
		}

        fflush(stdout);
	}

	totalRMS /= s_fileCount;
	totalDiff /= s_fileCount;

	printf("Total Results:\n");
	printf("  Total Time: \t%.3f sec\n", totalTime / CLOCKS_PER_SEC);
	printf("  Average RMS:\t%.4f\n", totalRMS);

	if (regressPath != NULL)
	{
		printf("Regression Results:\n");
		printf("  Diff: %.4f\n", totalDiff);
		printf("  %d/%d tests failed.\n", failedTests, s_fileCount);
	}

	return EXIT_SUCCESS;
}

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

#include <nvtt/nvtt.h>
#include <nvimage/Image.h>
#include <nvimage/ImageIO.h>
#include <nvimage/BlockDXT.h>
#include <nvimage/ColorBlock.h>
#include <nvcore/Ptr.h>
#include <nvcore/Debug.h>
#include <nvcore/StrLib.h>
#include <nvcore/StdStream.h>
#include <nvcore/TextWriter.h>
#include <nvcore/FileSystem.h>

#include <stdlib.h> // free
#include <string.h> // memcpy
#include <time.h> // clock

using namespace nv;

static const char * s_fileNames[] = {
	// Kodak image set
	"kodim01.png",
	"kodim02.png",
	"kodim03.png",
	"kodim04.png",
	"kodim05.png",
	"kodim06.png",
	"kodim07.png",
	"kodim08.png",
	"kodim09.png",
	"kodim10.png",
	"kodim11.png",
	"kodim12.png",
	"kodim13.png",
	"kodim14.png",
	"kodim15.png",
	"kodim16.png",
	"kodim17.png",
	"kodim18.png",
	"kodim19.png",
	"kodim20.png",
	"kodim21.png",
	"kodim22.png",
	"kodim23.png",
	"kodim24.png",
	// Waterloo image set
	"clegg.png",
	"frymire.png",
	"lena.png",
	"monarch.png",
	"peppers.png",
	"sail.png",
	"serrano.png",
	"tulips.png",
	// Epic image set
	"Bradley1.png",
	"Gradient.png",
	"MoreRocks.png",
	"Wall.png",
	"Rainbow.png",
	"Text.png",
};
const int s_fileCount = sizeof(s_fileNames)/sizeof(s_fileNames[0]);

struct MyOutputHandler : public nvtt::OutputHandler
{
	MyOutputHandler() : m_data(NULL), m_ptr(NULL) {}
	~MyOutputHandler()
	{
		free(m_data);
	}

	virtual void beginImage(int size, int width, int height, int depth, int face, int miplevel)
	{
		m_size = size;
		m_width = width;
		m_height = height;
		free(m_data);
		m_data = (unsigned char *)malloc(size);
		m_ptr = m_data;
	}

	virtual bool writeData(const void * data, int size)
	{
		memcpy(m_ptr, data, size);
		m_ptr += size;
		return true;
	}

	Image * decompress(nvtt::Format format)
	{
		int bw = (m_width + 3) / 4;
		int bh = (m_height + 3) / 4;

		AutoPtr<Image> img( new Image() );
		img->allocate(m_width, m_height);

		if (format == nvtt::Format_BC1)
		{
			BlockDXT1 * block = (BlockDXT1 *)m_data;

			for (int y = 0; y < bh; y++)
			{
				for (int x = 0; x < bw; x++)
				{
					ColorBlock colors;
					block->decodeBlock(&colors);

					for (int yy = 0; yy < 4; yy++)
					{
						for (int xx = 0; xx < 4; xx++)
						{
							Color32 c = colors.color(xx, yy);

							if (x * 4 + xx < m_width && y * 4 + yy < m_height)
							{
								img->pixel(x * 4 + xx, y * 4 + yy) = c;
							}
						}
					}

					block++;
				}
			}
		}

		return img.release();
	}

	int m_size;
	int m_width;
	int m_height;
	unsigned char * m_data;
	unsigned char * m_ptr;
};

float rmsError(const Image * a, const Image * b)
{
	nvCheck(a != NULL);
	nvCheck(b != NULL);
	nvCheck(a->width() == b->width());
	nvCheck(a->height() == b->height());

	float mse = 0;

	const uint count = a->width() * a->height();

	for (uint i = 0; i < count; i++)
	{
		Color32 c0 = a->pixel(i);
		Color32 c1 = b->pixel(i);

		int r = c0.r - c1.r;
		int g = c0.g - c1.g;
		int b = c0.b - c1.b;
		//int a = c0.a - c1.a;

		mse += r * r;
		mse += g * g;
		mse += b * b;
	}

	mse /= count;

	return sqrtf(mse);
}

int main(int argc, char *argv[])
{
	const uint version = nvtt::version();
	const uint major = version / 100;
	const uint minor = version % 100;

	printf("NVIDIA Texture Tools %u.%u - Copyright NVIDIA Corporation 2007 - 2008\n\n", major, minor);

	bool fast = false;
	bool nocuda = false;
	bool showHelp = false;
	const char * outPath = "output";
	const char * regressPath = NULL;

	// Parse arguments.
	for (int i = 1; i < argc; i++)
	{
		if (strcmp("-fast", argv[i]) == 0)
		{
			fast = true;
		}
		else if (strcmp("-nocuda", argv[i]) == 0)
		{
			nocuda = true;
		}
		else if (strcmp("-help", argv[i]) == 0)
		{
			showHelp = true;
		}
		else if (strcmp("-out", argv[i]) == 0)
		{
			if (i+1 < argc && argv[i+1][0] != '-') outPath = argv[i+1];
		}
		else if (strcmp("-regress", argv[i]) == 0)
		{
			if (i+1 < argc && argv[i+1][0] != '-') regressPath = argv[i+1];
		}
	}

	if (showHelp)
	{
		printf("usage: nvtestsuite [options]\n\n");

		printf("Input options:\n");
		printf("  -regress <path>\tRegression directory.\n");

		printf("Compression options:\n");
		printf("  -fast          \tFast compression.\n");
		printf("  -nocuda        \tDo not use cuda compressor.\n");

		printf("Output options:\n");
		printf("  -out <path>    \tOutput directory.\n");

		return 1;
	}

	nvtt::InputOptions inputOptions;
	inputOptions.setMipmapGeneration(false);

	nvtt::CompressionOptions compressionOptions;
	compressionOptions.setFormat(nvtt::Format_BC1);
	if (fast)
	{
		compressionOptions.setQuality(nvtt::Quality_Fastest);
	}
	else
	{
		compressionOptions.setQuality(nvtt::Quality_Production);
	}

	nvtt::OutputOptions outputOptions;
	outputOptions.setOutputHeader(false);

	MyOutputHandler outputHandler;
	outputOptions.setOutputHandler(&outputHandler);

	nvtt::Compressor compressor;
	compressor.enableCudaAcceleration(!nocuda);

	FileSystem::createDirectory(outPath);

	Path csvFileName("%s/result.csv", outPath);
	StdOutputStream csvStream(csvFileName);
	TextWriter csvWriter(&csvStream);

	float totalTime = 0;
	float totalRMS = 0;
	int failedTests = 0;
	float totalDiff = 0;

	for (int i = 0; i < s_fileCount; i++)
	{
		AutoPtr<Image> img( new Image() );

		if (!img->load(s_fileNames[i]))
		{
			printf("Input image '%s' not found.\n", s_fileNames[i]);
			return EXIT_FAILURE;
		}

		inputOptions.setTextureLayout(nvtt::TextureType_2D, img->width(), img->height());
		inputOptions.setMipmapData(img->pixels(), img->width(), img->height());

		printf("Compressing: \t'%s'\n", s_fileNames[i]);

		clock_t start = clock();

		compressor.process(inputOptions, compressionOptions, outputOptions);

		clock_t end = clock();
		printf("  Time: \t%.3f sec\n", float(end-start) / CLOCKS_PER_SEC);
		totalTime += float(end-start);

		AutoPtr<Image> img_out( outputHandler.decompress(nvtt::Format_BC1) );

		Path outputFileName("%s/%s", outPath, s_fileNames[i]);
		outputFileName.stripExtension();
		outputFileName.append(".tga");
		if (!ImageIO::save(outputFileName, img_out.ptr()))
		{
			printf("Error saving file '%s'.\n", outputFileName.str());
		}

		float rms = rmsError(img.ptr(), img_out.ptr());
		totalRMS += rms;

		printf("  RMS:  \t%.4f\n", rms);

		// Output csv file
		csvWriter << "\"" << s_fileNames[i] << "\"," << rms << "\n";

		if (regressPath != NULL)
		{
			Path regressFileName("%s/%s", regressPath, s_fileNames[i]);
			regressFileName.stripExtension();
			regressFileName.append(".tga");

			AutoPtr<Image> img_reg( new Image() );
			if (!img_reg->load(regressFileName.str()))
			{
				printf("Regression image '%s' not found.\n", regressFileName.str());
				return EXIT_FAILURE;
			}

			float rms_reg = rmsError(img.ptr(), img_reg.ptr());

			float diff = rms_reg - rms;
			totalDiff += diff;

			const char * text = "PASSED";
			if (equal(diff, 0)) text = "PASSED";
			else if (diff < 0) {
				text = "FAILED";
				failedTests++;
			}

			printf("  Diff: \t%.4f (%s)\n", diff, text);
		}

		fflush(stdout);
	}

	totalRMS /= s_fileCount;
	totalDiff /= s_fileCount;

	printf("Total Results:\n");
	printf("  Total Time: \t%.3f sec\n", totalTime / CLOCKS_PER_SEC);
	printf("  Average RMS:\t%.4f\n", totalRMS);

	if (regressPath != NULL)
	{
		printf("Regression Results:\n");
		printf("  Diff: %.4f\n", totalDiff);
		printf("  %d/%d tests failed.\n", failedTests, s_fileCount);
	}

	return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: KPreparedStatement.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2005-12-19 16:50:16 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_KAB_PREPAREDSTATEMENT_HXX_
#define _CONNECTIVITY_KAB_PREPAREDSTATEMENT_HXX_

#ifndef _CONNECTIVITY_KAB_STATEMENT_HXX_
#include "KStatement.hxx"
#endif

#ifndef _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_
#include "KResultSetMetaData.hxx"
#endif

#ifndef _COM_SUN_STAR_SDBC_XPARAMETERS_HPP_
#include <com/sun/star/sdbc/XParameters.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif

namespace connectivity
{
    namespace kab
    {

        class OBoundParam;
        typedef ::cppu::ImplInheritanceHelper4< KabCommonStatement,
                                                ::com::sun::star::sdbc::XPreparedStatement,
                                                ::com::sun::star::sdbc::XParameters,
                                                ::com::sun::star::sdbc::XResultSetMetaDataSupplier,
                                                ::com::sun::star::lang::XServiceInfo> KabPreparedStatement_BASE;

        class KabPreparedStatement : public  KabPreparedStatement_BASE
        {
        protected:
            struct Parameter
            {
                ::com::sun::star::uno::Any  aValue;
                sal_Int32                   nDataType;

                Parameter(const ::com::sun::star::uno::Any& rValue,
                          sal_Int32                         rDataType)
                    : aValue(rValue), nDataType(rDataType)
                { }
            };

//          ::std::vector< Parameter>       m_aParameters;
// Not used so far
            ::rtl::OUString                 m_sSqlStatement;
            ::rtl::Reference< KabResultSetMetaData >
                                            m_xMetaData;
            sal_Bool                        m_bPrepared;

            void checkParameterIndex(sal_Int32 _parameterIndex);
            void setKabFields() const throw(::com::sun::star::sdbc::SQLException);

        protected:
            virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
                    sal_Int32 nHandle,
                    const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::uno::Exception);
            virtual ~KabPreparedStatement();

        public:
            DECLARE_SERVICE_INFO();
            KabPreparedStatement(KabConnection* _pConnection, const ::rtl::OUString& sql);

            // XPreparedStatement
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL executeUpdate(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL execute(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // XParameters
            virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearParameters(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // XCloseable
            virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // XResultSetMetaDataSupplier
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }
}

#endif // _CONNECTIVITY_KAB_PREPAREDSTATEMENT_HXX_
<commit_msg>INTEGRATION: CWS kabparam (1.2.102); FILE MERGED 2006/06/29 08:15:22 ebischoff 1.2.102.1: #i66691# Support for parametrized queries in KDE address book connector<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: KPreparedStatement.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-06 14:17:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_KAB_PREPAREDSTATEMENT_HXX_
#define _CONNECTIVITY_KAB_PREPAREDSTATEMENT_HXX_

#ifndef _CONNECTIVITY_KAB_STATEMENT_HXX_
#include "KStatement.hxx"
#endif
#ifndef _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_
#include "KResultSetMetaData.hxx"
#endif

#ifndef _CONNECTIVITY_FILE_VALUE_HXX_
#include <connectivity/FValue.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XPARAMETERS_HPP_
#include <com/sun/star/sdbc/XParameters.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_
#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif

namespace connectivity
{
    namespace kab
    {

        class OBoundParam;
        typedef ::cppu::ImplInheritanceHelper4< KabCommonStatement,
                                                ::com::sun::star::sdbc::XPreparedStatement,
                                                ::com::sun::star::sdbc::XParameters,
                                                ::com::sun::star::sdbc::XResultSetMetaDataSupplier,
                                                ::com::sun::star::lang::XServiceInfo> KabPreparedStatement_BASE;

        class KabPreparedStatement : public  KabPreparedStatement_BASE
        {
        protected:
            ::rtl::OUString                 m_sSqlStatement;
            ::rtl::Reference< KabResultSetMetaData >
                                            m_xMetaData;
            sal_Bool                        m_bPrepared;
            mutable sal_Int32                   m_nParameterIndex;
            OValueRow                       m_aParameterRow;

            void checkAndResizeParameters(sal_Int32 nParams) throw(::com::sun::star::sdbc::SQLException);
            void setKabFields() const throw(::com::sun::star::sdbc::SQLException);

        protected:
            virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
                    sal_Int32 nHandle,
                    const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::uno::Exception);

            virtual void resetParameters() const throw(::com::sun::star::sdbc::SQLException);
            virtual void getNextParameter(::rtl::OUString &rParameter) const throw(::com::sun::star::sdbc::SQLException);
            virtual ~KabPreparedStatement();

        public:
            DECLARE_SERVICE_INFO();
            KabPreparedStatement(KabConnection* _pConnection, const ::rtl::OUString& sql);

            // OComponentHelper
            virtual void SAL_CALL disposing();

            // XPreparedStatement
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL executeUpdate(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL execute(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // XParameters
            virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearParameters(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // XCloseable
            virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            // XResultSetMetaDataSupplier
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }
}

#endif // _CONNECTIVITY_KAB_PREPAREDSTATEMENT_HXX_
<|endoftext|>


<commit_before>#include "catch/catch.hpp"
#include "RaZ/Entity.hpp"

namespace {

// Declaring entities to be tested
Raz::Entity entity0(0);
Raz::Entity entity1(1);
Raz::Entity entity2(2);

} // namespace

TEST_CASE("Entity base tests") {
  REQUIRE(entity0.getId() == 0);
  REQUIRE(entity1.getId() == 1);
  REQUIRE(entity2.getId() == 2);

  REQUIRE(entity0.isEnabled());

  entity0.disable();
  REQUIRE_FALSE(entity0.isEnabled());

  entity0.enable();
  REQUIRE(entity0.isEnabled());
}
<commit_msg>[Update] Added Entity-component manipulations test<commit_after>#include "catch/catch.hpp"
#include "RaZ/Entity.hpp"
#include "RaZ/Math/Transform.hpp"
#include "RaZ/Render/Mesh.hpp"

namespace {

// Declaring entities to be tested
Raz::Entity entity0(0);
Raz::Entity entity1(1);
Raz::Entity entity2(2);

} // namespace

TEST_CASE("Entity base tests") {
  REQUIRE(entity0.getId() == 0);
  REQUIRE(entity1.getId() == 1);
  REQUIRE(entity2.getId() == 2);

  REQUIRE(entity0.isEnabled());

  entity0.disable();
  REQUIRE_FALSE(entity0.isEnabled());

  entity0.enable();
  REQUIRE(entity0.isEnabled());
}

TEST_CASE("Entity-component manipulations") {
  REQUIRE(entity0.getComponents().empty());

  REQUIRE_FALSE(entity0.hasComponent<Raz::Mesh>());
  REQUIRE_FALSE(entity0.hasComponent<Raz::Transform>());

  entity0.addComponent<Raz::Transform>();
  REQUIRE(entity0.hasComponent<Raz::Transform>());
  REQUIRE_FALSE(entity0.hasComponent<Raz::Mesh>());

  REQUIRE(std::is_same<decltype(entity0.getComponent<Raz::Transform>()), Raz::Transform&>::value);
  REQUIRE_THROWS(entity0.getComponent<Raz::Mesh>());

  entity0.removeComponent<Raz::Transform>();
  REQUIRE_FALSE(entity0.hasComponent<Raz::Transform>());
  REQUIRE_THROWS(entity0.getComponent<Raz::Transform>());
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: UStringDescription_Impl.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 09:38:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX
#define CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX

#define IMPLEMENT_CONSTASCII_USTRING(name)  \
UStringDescription name(connectivity::dbtools::get##name)

UStringDescription::UStringDescription(PVFN _fCharFkt)
{
    pZeroTerminatedName = (*_fCharFkt)();
    nLength = 0;
    const sal_Char* pIter = pZeroTerminatedName;
    while((*pIter++) != '\0')
        ++nLength;
}
// -------------------------------------------------------------------------
UStringDescription::~UStringDescription()
{
}

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_QUERYTIMEOUT          );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_MAXFIELDSIZE          );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_MAXROWS               );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CURSORNAME            );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RESULTSETCONCURRENCY  );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RESULTSETTYPE         );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FETCHDIRECTION        );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FETCHSIZE             );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ESCAPEPROCESSING      );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_USEBOOKMARKS          );

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_NAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TYPE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TYPENAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_PRECISION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_SCALE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISNULLABLE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISAUTOINCREMENT);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISROWVERSION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DESCRIPTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DEFAULTVALUE);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_REFERENCEDTABLE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_UPDATERULE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DELETERULE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CATALOG);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISUNIQUE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISPRIMARYKEYINDEX);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISCLUSTERED);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISASCENDING);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_SCHEMANAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CATALOGNAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_COMMAND);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CHECKOPTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_PASSWORD);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RELATEDCOLUMN);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISSEARCHABLE);

IMPLEMENT_CONSTASCII_USTRING(STAT_INVALID_INDEX);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FUNCTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TABLENAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_REALNAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DBASEPRECISIONCHANGED);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISCURRENCY);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISBOOKMARKABLE);
//============================================================
//= error messages
//============================================================
IMPLEMENT_CONSTASCII_USTRING(ERRORMSG_SEQUENCE);
IMPLEMENT_CONSTASCII_USTRING(SQLSTATE_SEQUENCE);
IMPLEMENT_CONSTASCII_USTRING(SQLSTATE_GENERAL);
//============================================================
//= different
//============================================================
IMPLEMENT_CONSTASCII_USTRING(STR_DELIMITER);

#endif // CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.5.136); FILE MERGED 2008/03/28 15:24:05 rt 1.5.136.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: UStringDescription_Impl.hxx,v $
 * $Revision: 1.6 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX
#define CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX

#define IMPLEMENT_CONSTASCII_USTRING(name)  \
UStringDescription name(connectivity::dbtools::get##name)

UStringDescription::UStringDescription(PVFN _fCharFkt)
{
    pZeroTerminatedName = (*_fCharFkt)();
    nLength = 0;
    const sal_Char* pIter = pZeroTerminatedName;
    while((*pIter++) != '\0')
        ++nLength;
}
// -------------------------------------------------------------------------
UStringDescription::~UStringDescription()
{
}

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_QUERYTIMEOUT          );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_MAXFIELDSIZE          );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_MAXROWS               );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CURSORNAME            );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RESULTSETCONCURRENCY  );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RESULTSETTYPE         );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FETCHDIRECTION        );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FETCHSIZE             );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ESCAPEPROCESSING      );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_USEBOOKMARKS          );

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_NAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TYPE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TYPENAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_PRECISION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_SCALE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISNULLABLE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISAUTOINCREMENT);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISROWVERSION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DESCRIPTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DEFAULTVALUE);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_REFERENCEDTABLE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_UPDATERULE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DELETERULE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CATALOG);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISUNIQUE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISPRIMARYKEYINDEX);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISCLUSTERED);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISASCENDING);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_SCHEMANAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CATALOGNAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_COMMAND);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CHECKOPTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_PASSWORD);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RELATEDCOLUMN);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISSEARCHABLE);

IMPLEMENT_CONSTASCII_USTRING(STAT_INVALID_INDEX);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FUNCTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TABLENAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_REALNAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DBASEPRECISIONCHANGED);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISCURRENCY);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISBOOKMARKABLE);
//============================================================
//= error messages
//============================================================
IMPLEMENT_CONSTASCII_USTRING(ERRORMSG_SEQUENCE);
IMPLEMENT_CONSTASCII_USTRING(SQLSTATE_SEQUENCE);
IMPLEMENT_CONSTASCII_USTRING(SQLSTATE_GENERAL);
//============================================================
//= different
//============================================================
IMPLEMENT_CONSTASCII_USTRING(STR_DELIMITER);

#endif // CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX

<|endoftext|>


<commit_before>/** @file iterativeSolvers.cpp

    @brief Example on how the solve a system of linear equation with the MINRES, GMRes and CG method.

    This file is part of the G+Smo library.

    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this
    file, You can obtain one at http://mozilla.org/MPL/2.0/.

    Author(s): J. Sogn
*/

#include <iostream>
#include <gismo.h>

using namespace gismo;

//Create a tri-diagonal matrix with -1 of the off diagonals and 2 in the diagonal.
//This matrix is equivalent to discretizing the 1D Poisson equation with homogenius
//Dirichlet boundary condition using a finite difference method. It is a SPD matrix.
//The solution is sin(pi*x);
void poissonDiscretization(gsSparseMatrix<> &mat, gsMatrix<> &rhs, index_t N)
{
    rhs.setZero(N,1);

    mat.resize(N,N);
    mat.setZero();
    real_t meshSize = 1./(N+1);
    real_t pi = M_PI;

    //Reserving space in the sparse matrix (Speeds up the assemble time of the matrix)
    mat.reservePerColumn( 3 ); //Reserve 3 non-zero entry per column

    mat(0,0) = 2;
    mat(0,1) = -1;
    mat(N-1, N-1) = 2;
    mat(N-1, N-2) = -1;
    for (index_t k = 1; k < N-1; ++k)
    {
        mat(k,k) = 2;
        mat(k,k-1) = -1;
        mat(k,k+1) = -1;
    }
    for (index_t k = 0; k < N; ++k)
        rhs(k,0) = pi*pi*meshSize*meshSize*math::cos(meshSize*(1+k)*pi);

    //Compress the matrix
    mat.makeCompressed();
}

//Print out information of the iterative solver
template<typename SolverType>
void gsIterativeSolverInfo(const SolverType &method,
                           real_t error, double time, bool& succeeded )
{
    gsInfo << method.detail();
    gsInfo << " Computed res. error  : " << error << "\n";
    gsInfo << " Time to solve:       : " << time << "\n";
    if ( method.error() <= method.tolerance() && error <= method.tolerance() )
    {
        gsInfo <<" Test passed.\n";
    }
    else
    {
        gsInfo <<" TEST FAILED!\n";
        succeeded = false;
    }
}

int main(int argc, char *argv[])
{

    bool succeeded = true;

    index_t N = 100;
    //Tolerance
    real_t tol = std::pow(10.0, - REAL_DIG * 0.75);

    gsCmdLine cmd("Solves a 1D PDE with a Courant discretization with several solvers solver.");
    cmd.addInt("n", "number", "Number of unknowns", N);
    cmd.addReal("", "tol", "Tolerance for the solvers", tol);

    bool ok = cmd.getValues(argc,argv);
    if ( !ok )
    {
        gsInfo << "Something went wrong when reading the command line. Exiting.\n";
        return 1;
    }

    gsSparseMatrix<> mat;
    gsMatrix<>       rhs;

    //Assemble the 1D Poisson equation
    poissonDiscretization(mat, rhs, N);

    //The minimal residual implementation requires a preconditioner.
    //We initialize an identity preconditioner (does nothing).
    gsLinearOperator<>::Ptr preConMat = gsIdentityOp<>::make(N);

    gsStopwatch clock;

    //initial guess
    gsMatrix<> x0;
    x0.setZero(N,1);

#ifndef GISMO_WITH_MPQ

    //Maximum number of iterations
    index_t maxIters = 3*N;

    gsOptionList opt = gsIterativeSolver<real_t>::defaultOptions();
    opt.setInt ("MaxIterations", 3*N);
    opt.setReal("Tolerance"    , tol);

    ///----------------------GISMO-SOLVERS----------------------///
    gsInfo << "Testing G+Smo's solvers:\n";

    //Initialize the MinRes solver
    gsMinimalResidual MinRes(mat,preConMat);
    MinRes.setOptions(opt);

    //Solve system with given preconditioner (solution is stored in x0)
    gsInfo << "\nMinRes: Started solving... ";
    clock.restart();
    MinRes.solve(rhs, x0);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(MinRes, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    //Initialize the CG solver
    gsGMRes GMResSolver(mat,preConMat);
    GMResSolver.setOptions(opt);

    //Set the initial guess to zero
    x0.setZero(N,1);

    if (N < 200)
    {
        //Solve system with given preconditioner (solution is stored in x0)
        gsInfo << "\nGMRes: Started solving... ";
        clock.restart();
        GMResSolver.solve(rhs,x0);
        gsInfo << "done.\n";
        gsIterativeSolverInfo(GMResSolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);
    }
    else
        gsInfo << "\nSkipping GMRes due to high number of iterations...\n";

    //Initialize the CG solver
    gsConjugateGradient CGSolver(mat,preConMat);
    CGSolver.setOptions(opt);

    //Set the initial guess to zero
    x0.setZero(N,1);

    //Solve system with given preconditioner (solution is stored in x0)
    gsInfo << "\nCG: Started solving... ";
    clock.restart();
    CGSolver.solve(rhs,x0);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(CGSolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    ///----------------------EIGEN-ITERATIVE-SOLVERS----------------------///
    gsInfo << "\nTesting Eigen's interative solvers:\n";

    gsSparseSolver<>::CGIdentity EigenCGIsolver;
    EigenCGIsolver.setMaxIterations(maxIters);
    EigenCGIsolver.setTolerance(tol);
    gsInfo << "\nEigen's CG + identity prec.: Started solving... ";
    clock.restart();
    EigenCGIsolver.compute(mat);
    x0 = EigenCGIsolver.solve(rhs);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(EigenCGIsolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    gsSparseSolver<>::CGDiagonal EigenCGDsolver;
    EigenCGDsolver.setMaxIterations(maxIters);
    EigenCGDsolver.setTolerance(tol);
    gsInfo << "\nEigen's CG + diagonal prec.: Started solving... ";
    clock.restart();
    EigenCGDsolver.compute(mat);
    x0 = EigenCGDsolver.solve(rhs);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(EigenCGDsolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    gsSparseSolver<>::BiCGSTABIdentity EigenBCGIsolver;
    EigenBCGIsolver.setMaxIterations(maxIters);
    EigenBCGIsolver.setTolerance(tol);
    gsInfo << "\nEigen's bi conjugate gradient stabilized + identity prec.: Started solving... ";
    clock.restart();
    EigenBCGIsolver.compute(mat);
    x0 = EigenBCGIsolver.solve(rhs);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(EigenBCGIsolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    gsSparseSolver<>::BiCGSTABDiagonal EigenBCGDsolver;
    EigenBCGDsolver.setMaxIterations(maxIters);
    EigenBCGDsolver.setTolerance(tol);
    gsInfo << "\nEigen's bi conjugate gradient stabilized solver + diagonal prec.: Started solving... ";
    clock.restart();
    EigenBCGDsolver.compute(mat);
    x0 = EigenBCGDsolver.solve(rhs);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(EigenBCGDsolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    gsSparseSolver<>::BiCGSTABILUT EigenBCGILUsolver;
    //EigenBCGILUsolver.preconditioner().setFillfactor(1);
    EigenBCGILUsolver.setMaxIterations(maxIters);
    EigenBCGILUsolver.setTolerance(tol);
    gsInfo << "\nEigen's bi conjugate gradient stabilized solver + ILU prec.: Started solving... ";
    clock.restart();
    EigenBCGILUsolver.compute(mat);
    x0 = EigenBCGILUsolver.solve(rhs);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(EigenBCGILUsolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    ///----------------------EIGEN-DIRECT-SOLVERS----------------------///
    gsSparseSolver<>::SimplicialLDLT EigenSLDLTsolver;
    gsInfo << "\nEigen's Simplicial LDLT: Started solving... ";
    clock.restart();
    EigenSLDLTsolver.compute(mat);
    x0 = EigenSLDLTsolver.solve(rhs);
    gsInfo << "done.\n";
    gsInfo << "Eigen's Simplicial LDLT: Time to solve       : " << clock.stop() << "\n";

    gsSparseSolver<>::QR solverQR;
    gsInfo << "\nEigen's QR: Started solving... ";
    clock.restart();
    solverQR.compute(mat);
    x0 = solverQR.solve(rhs);
    gsInfo << "done.\n";
    gsInfo << "Eigen's QR: Time to solve       : " << clock.stop() << "\n";

#endif

    gsSparseSolver<>::LU solverLU;
    gsInfo << "\nEigen's LU: Started solving... ";
    clock.restart();
    solverLU.compute(mat);
    x0 = solverLU.solve(rhs);
    gsInfo << "done.\n";
    gsInfo << "Eigen's LU: Time to solve       : " << clock.stop() << "\n";

    return succeeded ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg><commit_after>/** @file iterativeSolvers.cpp

    @brief Example on how the solve a system of linear equation with the MINRES, GMRes and CG method.

    This file is part of the G+Smo library.

    This Source Code Form is subject to the terms of the Mozilla Public
    License, v. 2.0. If a copy of the MPL was not distributed with this
    file, You can obtain one at http://mozilla.org/MPL/2.0/.

    Author(s): J. Sogn
*/

#include <iostream>
#include <gismo.h>

using namespace gismo;

//Create a tri-diagonal matrix with -1 of the off diagonals and 2 in the diagonal.
//This matrix is equivalent to discretizing the 1D Poisson equation with homogenius
//Dirichlet boundary condition using a finite difference method. It is a SPD matrix.
//The solution is sin(pi*x);
void poissonDiscretization(gsSparseMatrix<> &mat, gsMatrix<> &rhs, index_t N)
{
    rhs.setZero(N,1);

    mat.resize(N,N);
    mat.setZero();
    real_t meshSize = 1./(N+1);
    real_t pi = M_PI;

    //Reserving space in the sparse matrix (Speeds up the assemble time of the matrix)
    mat.reservePerColumn( 3 ); //Reserve 3 non-zero entry per column

    mat(0,0) = 2;
    mat(0,1) = -1;
    mat(N-1, N-1) = 2;
    mat(N-1, N-2) = -1;
    for (index_t k = 1; k < N-1; ++k)
    {
        mat(k,k) = 2;
        mat(k,k-1) = -1;
        mat(k,k+1) = -1;
    }
    for (index_t k = 0; k < N; ++k)
        rhs(k,0) = pi*pi*meshSize*meshSize*math::cos(meshSize*(1+k)*pi);

    //Compress the matrix
    mat.makeCompressed();
}

//Print out information of the iterative solver
template<typename SolverType>
void gsIterativeSolverInfo(const SolverType &method,
                           real_t error, double time, bool& succeeded )
{
    gsInfo << method.detail();
    gsInfo << " Computed res. error  : " << error << "\n";
    gsInfo << " Time to solve:       : " << time << "\n";
    if ( method.error() <= method.tolerance() && error <= method.tolerance() )
    {
        gsInfo <<" Test passed.\n";
    }
    else
    {
        gsInfo <<" TEST FAILED!\n";
        succeeded = false;
    }
}

int main(int argc, char *argv[])
{

    bool succeeded = true;

    index_t N = 100;
    //Tolerance
    real_t tol = std::pow(10.0, - REAL_DIG * 0.75);

    gsCmdLine cmd("Solves a 1D PDE with a Courant discretization with several solvers solver.");
    cmd.addInt("n", "number", "Number of unknowns", N);
    cmd.addReal("", "tol", "Tolerance for the solvers", tol);

    bool ok = cmd.getValues(argc,argv);
    if ( !ok )
    {
        gsInfo << "Something went wrong when reading the command line. Exiting.\n";
        return 1;
    }

    gsSparseMatrix<> mat;
    gsMatrix<>       rhs;

    //Assemble the 1D Poisson equation
    poissonDiscretization(mat, rhs, N);

    //The minimal residual implementation requires a preconditioner.
    //We initialize an identity preconditioner (does nothing).
    gsLinearOperator<>::Ptr preConMat = gsIdentityOp<>::make(N);

    gsStopwatch clock;

    //initial guess
    gsMatrix<> x0;

#ifndef GISMO_WITH_MPQ

    //Maximum number of iterations
    index_t maxIters = 3*N;

    gsOptionList opt = gsIterativeSolver<real_t>::defaultOptions();
    opt.setInt ("MaxIterations", 3*N);
    opt.setReal("Tolerance"    , tol);

    ///----------------------GISMO-SOLVERS----------------------///
    gsInfo << "Testing G+Smo's solvers:\n";

    //Initialize the MinRes solver
    gsMinimalResidual MinRes(mat,preConMat);
    MinRes.setOptions(opt);

    //Set the initial guess to zero
    x0.setZero(N,1);

    //Solve system with given preconditioner (solution is stored in x0)
    gsInfo << "\nMinRes: Started solving... ";
    clock.restart();
    MinRes.solve(rhs, x0);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(MinRes, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    //Initialize the MinRes solver with inexact residual error norm
    gsMinimalResidual MinResIR(mat,preConMat);
    MinResIR.setOptions(opt);
    MinResIR.setInexactResidual(true);

    //Set the initial guess to zero
    x0.setZero(N,1);

    //Solve system with given preconditioner (solution is stored in x0)
    gsInfo << "\nMinResIR: Started solving... ";
    clock.restart();
    MinResIR.solve(rhs, x0);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(MinResIR, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    //Initialize the GMResSolver solver
    gsGMRes GMResSolver(mat,preConMat);
    GMResSolver.setOptions(opt);

    //Set the initial guess to zero
    x0.setZero(N,1);

    if (N < 200)
    {
        //Solve system with given preconditioner (solution is stored in x0)
        gsInfo << "\nGMRes: Started solving... ";
        clock.restart();
        GMResSolver.solve(rhs,x0);
        gsInfo << "done.\n";
        gsIterativeSolverInfo(GMResSolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);
    }
    else
        gsInfo << "\nSkipping GMRes due to high number of iterations...\n";

    //Initialize the CG solver
    gsConjugateGradient CGSolver(mat,preConMat);
    CGSolver.setOptions(opt);

    //Set the initial guess to zero
    x0.setZero(N,1);

    //Solve system with given preconditioner (solution is stored in x0)
    gsInfo << "\nCG: Started solving... ";
    clock.restart();
    CGSolver.solve(rhs,x0);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(CGSolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    ///----------------------EIGEN-ITERATIVE-SOLVERS----------------------///
    gsInfo << "\nTesting Eigen's interative solvers:\n";

    gsSparseSolver<>::CGIdentity EigenCGIsolver;
    EigenCGIsolver.setMaxIterations(maxIters);
    EigenCGIsolver.setTolerance(tol);
    gsInfo << "\nEigen's CG + identity prec.: Started solving... ";
    clock.restart();
    EigenCGIsolver.compute(mat);
    x0 = EigenCGIsolver.solve(rhs);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(EigenCGIsolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    gsSparseSolver<>::CGDiagonal EigenCGDsolver;
    EigenCGDsolver.setMaxIterations(maxIters);
    EigenCGDsolver.setTolerance(tol);
    gsInfo << "\nEigen's CG + diagonal prec.: Started solving... ";
    clock.restart();
    EigenCGDsolver.compute(mat);
    x0 = EigenCGDsolver.solve(rhs);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(EigenCGDsolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    gsSparseSolver<>::BiCGSTABIdentity EigenBCGIsolver;
    EigenBCGIsolver.setMaxIterations(maxIters);
    EigenBCGIsolver.setTolerance(tol);
    gsInfo << "\nEigen's bi conjugate gradient stabilized + identity prec.: Started solving... ";
    clock.restart();
    EigenBCGIsolver.compute(mat);
    x0 = EigenBCGIsolver.solve(rhs);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(EigenBCGIsolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    gsSparseSolver<>::BiCGSTABDiagonal EigenBCGDsolver;
    EigenBCGDsolver.setMaxIterations(maxIters);
    EigenBCGDsolver.setTolerance(tol);
    gsInfo << "\nEigen's bi conjugate gradient stabilized solver + diagonal prec.: Started solving... ";
    clock.restart();
    EigenBCGDsolver.compute(mat);
    x0 = EigenBCGDsolver.solve(rhs);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(EigenBCGDsolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    gsSparseSolver<>::BiCGSTABILUT EigenBCGILUsolver;
    //EigenBCGILUsolver.preconditioner().setFillfactor(1);
    EigenBCGILUsolver.setMaxIterations(maxIters);
    EigenBCGILUsolver.setTolerance(tol);
    gsInfo << "\nEigen's bi conjugate gradient stabilized solver + ILU prec.: Started solving... ";
    clock.restart();
    EigenBCGILUsolver.compute(mat);
    x0 = EigenBCGILUsolver.solve(rhs);
    gsInfo << "done.\n";
    gsIterativeSolverInfo(EigenBCGILUsolver, (mat*x0-rhs).norm()/rhs.norm(), clock.stop(), succeeded);

    ///----------------------EIGEN-DIRECT-SOLVERS----------------------///
    gsSparseSolver<>::SimplicialLDLT EigenSLDLTsolver;
    gsInfo << "\nEigen's Simplicial LDLT: Started solving... ";
    clock.restart();
    EigenSLDLTsolver.compute(mat);
    x0 = EigenSLDLTsolver.solve(rhs);
    gsInfo << "done.\n";
    gsInfo << "Eigen's Simplicial LDLT: Time to solve       : " << clock.stop() << "\n";

    gsSparseSolver<>::QR solverQR;
    gsInfo << "\nEigen's QR: Started solving... ";
    clock.restart();
    solverQR.compute(mat);
    x0 = solverQR.solve(rhs);
    gsInfo << "done.\n";
    gsInfo << "Eigen's QR: Time to solve       : " << clock.stop() << "\n";

#endif

    gsSparseSolver<>::LU solverLU;
    gsInfo << "\nEigen's LU: Started solving... ";
    clock.restart();
    solverLU.compute(mat);
    x0 = solverLU.solve(rhs);
    gsInfo << "done.\n";
    gsInfo << "Eigen's LU: Time to solve       : " << clock.stop() << "\n";

    return succeeded ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|>