<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
        ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
        ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
        (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97"))
        (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe"))
        (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763"))
        (193000, uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317"))
        (210000, uint256("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e"))
        (216116, uint256("0x00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e"))
        (225430, uint256("0x00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1363044259, // * UNIX timestamp of last checkpoint block
        14264869,   // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        60000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1338180505,
        16341,
        300
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET)
            return dataTestnet;
        else if (Params().NetworkID() == CChainParams::MAIN)
            return data;
        else
            return dataRegtest;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>Checkpoint at block 250,000<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
        ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
        ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
        (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97"))
        (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe"))
        (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763"))
        (193000, uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317"))
        (210000, uint256("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e"))
        (216116, uint256("0x00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e"))
        (225430, uint256("0x00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932"))
        (250000, uint256("0x000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1375533383, // * UNIX timestamp of last checkpoint block
        21491097,   // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        60000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1338180505,
        16341,
        300
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET)
            return dataTestnet;
        else if (Params().NetworkID() == CChainParams::MAIN)
            return data;
        else
            return dataRegtest;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<|endoftext|>


<commit_before>#include<iostream>
#include<math.h>
#include<stdlib.h>

using namespace std;

int prime[10000],primes;

//find all the primes between 2 and sqrt(10000)
void init_primes(){
     static bool isprime[32000];
     int i,j;
     for(i=2;i<32000;i++) isprime[i]=true;
     for(i=2;i*i < 32000;i++)if(isprime[i])
     {
         for(j=2*i;j<32000;j+=i) isprime[j]=false;
     }
     primes=0;
     for(i=2;i<32000;i++)
        if(isprime[i])
            prime[primes++]=i;
}

bool seive[100001];

void find_seive(int lo, int hi){
   int i,j,p,n;
   for(i=0; i<=hi-lo; i++)
       seive[i]=true;
   for(j=0;;j++){
       p=prime[j];
       if(p*p > hi) break; //stop at the hi
       n = (lo/p)*p; //nearest composite to lo for that prime
       if(n<lo) n+=p;
       if(n==p) n+=p;
       for(;n<=hi; n+=p)
          seive[n-lo]=false;
   }
}

void generatePrimeBetween(int lower, const int upper){
	if(lower<2) lower=2;
	find_seive(lower,upper);
         for(int i=0; i<=upper-lower; i++)
            if(seive[i]){
               cout << lower+i << endl;
            }
}

int main(){
	init_primes();
	int noOfTestCases;
	scanf("%d", &noOfTestCases);
	int num1; //smaller number
	int num2; // larger number
	while (noOfTestCases--) {
		scanf("%d %d",&num1,&num2);
		generatePrimeBetween(num1, num2);
		cout << endl;
	}
	return 0;
}
<commit_msg>Update main.cpp<commit_after>#include<iostream>
#include<math.h>
#include<stdlib.h>

using namespace std;

int prime[10000],primes;

//find all the primes between 2 and sqrt(10000)
void init_primes(){
     static bool isprime[32000];
     int i,j;
     for(i=2;i<32000;i++) isprime[i]=true;
     for(i=2;i*i < 32000;i++)
     	if(isprime[i])
         	for(j=2*i;j<32000;j+=i)
         		isprime[j]=false;
     primes=0;
     for(i=2;i<32000;i++)
        if(isprime[i])
            prime[primes++]=i;
}

bool seive[100001];

void find_seive(int lo, int hi){
   int i,j,p,n;
   for(i=0; i<=hi-lo; i++)
       seive[i]=true;
   for(j=0;;j++){
       p=prime[j];
       if(p*p > hi) break; //stop at the hi
       n = (lo/p)*p; //nearest composite to lo for that prime
       if(n<lo) n+=p;
       if(n==p) n+=p;
       for(;n<=hi; n+=p)
          seive[n-lo]=false;
   }
}

void generatePrimeBetween(int lower, const int upper){
	if(lower<2) lower=2;
	find_seive(lower,upper);
         for(int i=0; i<=upper-lower; i++)
            if(seive[i]){
               cout << lower+i << endl;
            }
}

int main(){
	init_primes();
	int noOfTestCases;
	scanf("%d", &noOfTestCases);
	int num1; //smaller number
	int num2; // larger number
	while (noOfTestCases--) {
		scanf("%d %d",&num1,&num2);
		generatePrimeBetween(num1, num2);
		cout << endl;
	}
	return 0;
}
<|endoftext|>


<commit_before>#include "init.hpp"

#include "DiscardRule"
#include "TokenRule"
#include "MultipleRule"
#include "AlternativeRule"
#include "SequenceRule"
#include "ProxyRule"

using namespace sprout;

BOOST_AUTO_TEST_CASE(testTrivialProxy)
{
    ProxyRule<char, std::string> rule(
        OrderedTokenRule<char, std::string>("Cat", "Animal")
    );
}

BOOST_AUTO_TEST_CASE(testSplittingByWhitespace)
{
    auto rule = makeMultiple(
        SequenceRule<ProxyRule<char, std::string>>()
        << makeAlternate(
            OrderedTokenRule<char, std::string>("Cat", "Heathen"),
            OrderedTokenRule<char, std::string>("Dog", "Civilized"),
            OrderedTokenRule<char, std::string>("Calf", "Cow")
        )
        << sprout::Optional
        << makeDiscard(makeMultiple(
            AnyTokenRule<char, std::string>("_")
        ))
        << sprout::Required
        << OrderedTokenRule<char, std::string>(",", "Comma")
        << sprout::Optional
        << makeDiscard(makeMultiple(
            AnyTokenRule<char, std::string>("_")
        ))
    );

    std::stringstream str("Dog,_Cat,_Calf,_Cat,");
    auto cursor = makeCursor<char>(str);

    auto tokens = rule.parse(cursor);
    BOOST_REQUIRE(tokens);
    BOOST_CHECK_EQUAL("Civilized", *tokens++);
    BOOST_CHECK_EQUAL("Comma", *tokens++);
    BOOST_CHECK_EQUAL("Heathen", *tokens++);
    BOOST_CHECK_EQUAL("Comma", *tokens++);
    BOOST_CHECK_EQUAL("Cow", *tokens++);
    BOOST_CHECK_EQUAL("Comma", *tokens++);
    BOOST_CHECK_EQUAL("Heathen", *tokens++);
    BOOST_CHECK_EQUAL("Comma", *tokens++);
    BOOST_CHECK(!tokens);
}
<commit_msg>Remove now-unnecessary manipulators (since DiscardRule is always optional)<commit_after>#include "init.hpp"

#include "DiscardRule"
#include "TokenRule"
#include "MultipleRule"
#include "AlternativeRule"
#include "SequenceRule"
#include "ProxyRule"

using namespace sprout;

BOOST_AUTO_TEST_CASE(testTrivialProxy)
{
    ProxyRule<char, std::string> rule(
        OrderedTokenRule<char, std::string>("Cat", "Animal")
    );
}

BOOST_AUTO_TEST_CASE(testSplittingByWhitespace)
{
    auto rule = makeMultiple(
        SequenceRule<ProxyRule<char, std::string>>()
        << makeDiscard(makeMultiple(
            AnyTokenRule<char, std::string>("_")
        ))
        << makeAlternate(
            OrderedTokenRule<char, std::string>("Cat", "Heathen"),
            OrderedTokenRule<char, std::string>("Dog", "Civilized"),
            OrderedTokenRule<char, std::string>("Calf", "Cow")
        )
        << makeDiscard(makeMultiple(
            AnyTokenRule<char, std::string>("_")
        ))
        << OrderedTokenRule<char, std::string>(",", "Comma")
        << makeDiscard(makeMultiple(
            AnyTokenRule<char, std::string>("_")
        ))
    );

    std::stringstream str("Dog,_Cat,_Calf,_Cat,");
    auto cursor = makeCursor<char>(str);

    auto tokens = rule.parse(cursor);
    BOOST_REQUIRE(tokens);
    BOOST_CHECK_EQUAL("Civilized", *tokens++);
    BOOST_CHECK_EQUAL("Comma", *tokens++);
    BOOST_CHECK_EQUAL("Heathen", *tokens++);
    BOOST_CHECK_EQUAL("Comma", *tokens++);
    BOOST_CHECK_EQUAL("Cow", *tokens++);
    BOOST_CHECK_EQUAL("Comma", *tokens++);
    BOOST_CHECK_EQUAL("Heathen", *tokens++);
    BOOST_CHECK_EQUAL("Comma", *tokens++);
    BOOST_CHECK(!tokens);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2013 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#if SK_SUPPORT_GPU
#include "GrTexture.h"
#include "SkImageFilterUtils.h"
#include "SkBitmap.h"
#include "SkMatrix.h"
#include "SkGrPixelRef.h"
#include "SkGr.h"

bool SkImageFilterUtils::WrapTexture(GrTexture* texture, int width, int height, SkBitmap* result) {
    SkASSERT(texture->config() == kSkia8888_GrPixelConfig);
    result->setConfig(SkBitmap::kARGB_8888_Config, width, height);
    result->setPixelRef(SkNEW_ARGS(SkGrPixelRef, (texture)))->unref();
    return true;
}

bool SkImageFilterUtils::GetInputResultGPU(SkImageFilter* filter, SkImageFilter::Proxy* proxy, const SkBitmap& src, SkBitmap* result) {
    if (!filter) {
        *result = src;
        return true;
    } else if (filter->canFilterImageGPU()) {
        return filter->filterImageGPU(proxy, src, result);
    } else {
        SkIPoint offset;
        if (filter->filterImage(proxy, src, SkMatrix(), result, &offset)) {
            if (!result->getTexture()) {
                GrContext* context = ((GrTexture *) src.getTexture())->getContext();
                GrTexture* resultTex = GrLockAndRefCachedBitmapTexture(context,
                    *result, NULL);
                result->setPixelRef(new SkGrPixelRef(resultTex))->unref();
                GrUnlockAndUnrefCachedBitmapTexture(resultTex);
            }
            return true;
        } else {
            return false;
        }
    }
}
#endif
<commit_msg>Speculative change to SkImageFilterUtils.cpp to try to get compiling in Chrome<commit_after>/*
 * Copyright 2013 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkMatrix.h"

#if SK_SUPPORT_GPU
#include "GrTexture.h"
#include "SkImageFilterUtils.h"
#include "SkBitmap.h"
#include "SkGrPixelRef.h"
#include "SkGr.h"

bool SkImageFilterUtils::WrapTexture(GrTexture* texture, int width, int height, SkBitmap* result) {
    SkASSERT(texture->config() == kSkia8888_GrPixelConfig);
    result->setConfig(SkBitmap::kARGB_8888_Config, width, height);
    result->setPixelRef(SkNEW_ARGS(SkGrPixelRef, (texture)))->unref();
    return true;
}

bool SkImageFilterUtils::GetInputResultGPU(SkImageFilter* filter, SkImageFilter::Proxy* proxy, const SkBitmap& src, SkBitmap* result) {
    if (!filter) {
        *result = src;
        return true;
    } else if (filter->canFilterImageGPU()) {
        return filter->filterImageGPU(proxy, src, result);
    } else {
        SkIPoint offset;
        if (filter->filterImage(proxy, src, SkMatrix(), result, &offset)) {
            if (!result->getTexture()) {
                GrContext* context = ((GrTexture *) src.getTexture())->getContext();
                GrTexture* resultTex = GrLockAndRefCachedBitmapTexture(context,
                    *result, NULL);
                result->setPixelRef(new SkGrPixelRef(resultTex))->unref();
                GrUnlockAndUnrefCachedBitmapTexture(resultTex);
            }
            return true;
        } else {
            return false;
        }
    }
}
#endif
<|endoftext|>


<commit_before>#include "Renderer.hpp"

#define QUOTE(x) #x
#define STR(x) QUOTE(x)

Renderer::Renderer(CubemapSource* cubemapSource)
    :
    al::OmniApp("AlloPlayer", false, 2048), resizeCtx(nullptr), cubemapSource(cubemapSource),
    cubemap(nullptr), newCubemap(false)
{
    nav().smooth(0.8);

    // set up cube
    cube.color(1,1,1,1);
    cube.primitive(al::Graphics::TRIANGLES);
    addCube(cube);
    for (int i = 0; i < cube.vertices().size(); ++i) {
        float f = (float)i / cube.vertices().size();
        cube.color(al::Color(al::HSV(f, 1 - f, 1), 1));
    }
    cube.generateNormals();

    // set up sphere
    sphere.primitive(al::Graphics::TRIANGLES);
    addSphere(sphere, 1.0, 32, 32);
    for (int i = 0; i < sphere.vertices().size(); ++i) {
        float f = (float)i / sphere.vertices().size();
        sphere.color(al::Color(al::HSV(f, 1 - f, 1), 1));
    }
    sphere.generateNormals();

    // set up light
    light.ambient(al::Color(0.4, 0.4, 0.4, 1.0));
    light.pos(5, 5, 5);

    std::function<StereoCubemap* (CubemapSource*, StereoCubemap*)> callback = boost::bind(&Renderer::onNextCubemap,
                                                                                this,
                                                                                _1,
                                                                                _2);
    cubemapSource->setOnNextCubemap(callback);
}

Renderer::~Renderer()
{
}

bool Renderer::onCreate()
{
    std::cout << "OpenGL version: " << glGetString(GL_VERSION) << ", GLSL version " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
    return OmniApp::onCreate();
}

bool Renderer::onFrame()
{
    now = al::MainLoop::now();

    bool result;
    {
        boost::mutex::scoped_lock lock(nextCubemapMutex);
        result = OmniApp::onFrame();
        newCubemap = false;
    }
    if (onDisplayedFrame) onDisplayedFrame(this);
    return result;
}

StereoCubemap* Renderer::onNextCubemap(CubemapSource* source, StereoCubemap* cubemap)
{
    boost::mutex::scoped_lock lock(nextCubemapMutex);
    StereoCubemap* oldCubemap = this->cubemap;
    this->cubemap = cubemap;
    newCubemap = true;
    return oldCubemap;
}

void Renderer::onDraw(al::Graphics& gl)
{
    int faceIndex = mOmni.face();

    {

        // render cubemap
        if (cubemap && cubemap->getEyesCount() > 0)
        {
            Cubemap* eye = cubemap->getEye(0);
            if (eye->getFacesCount() > faceIndex)
            {
                // Choose right face for flipping
                CubemapFace* face;
                if (faceIndex == 0)
                {
                    face = eye->getFace(1);
                }
                else if (faceIndex == 1)
                {
                    face = eye->getFace(0);
                }
                else
                {
                    face = eye->getFace(faceIndex);
                }

                glUseProgram(0);
                glDepthMask(GL_FALSE);

                // flip face
                glPixelZoom(-1.0, 1.0);
                glRasterPos2d(1.0, -1.0);

                // draw the background
                glDrawPixels(face->getContent()->getWidth(),
                             face->getContent()->getHeight(),
                             GL_RGBA,
                             GL_UNSIGNED_BYTE,
                             (GLvoid*)face->getContent()->getPixels());

                glDepthMask(GL_TRUE);

                if(newCubemap)
                {
                    if (onDisplayedCubemapFace) onDisplayedCubemapFace(this, faceIndex);
                }
            }
        }
    }

    light();
    mShader.begin();
    mOmni.uniforms(mShader);

    gl.pushMatrix();

    //gl.draw(cube);

    gl.pushMatrix();
    // rotate over time:
    gl.rotate(now*30., 0.707, 0.707, 0.);
    gl.translate(1., 1., 1.);
    //gl.draw(sphere);
    gl.popMatrix();

    gl.popMatrix();

    mShader.end();
}

void Renderer::onAnimate(al_sec dt)
{
    pose = nav();
}

void Renderer::onMessage(al::osc::Message& m)
{
    OmniApp::onMessage(m);
}

bool Renderer::onKeyDown(const al::Keyboard& k)
{
    return true;
}

void Renderer::setOnDisplayedFrame(std::function<void (Renderer*)>& callback)
{
    onDisplayedFrame = callback;
}

void Renderer::setOnDisplayedCubemapFace(std::function<void (Renderer*, int)>& callback)
{
    onDisplayedCubemapFace = callback;
}
<commit_msg>AlloPlayer stereo ready<commit_after>#include "Renderer.hpp"

#define QUOTE(x) #x
#define STR(x) QUOTE(x)

Renderer::Renderer(CubemapSource* cubemapSource)
    :
    al::OmniApp("AlloPlayer", false, 2048), resizeCtx(nullptr), cubemapSource(cubemapSource),
    cubemap(nullptr), newCubemap(false)
{
    nav().smooth(0.8);

    // set up cube
    cube.color(1,1,1,1);
    cube.primitive(al::Graphics::TRIANGLES);
    addCube(cube);
    for (int i = 0; i < cube.vertices().size(); ++i) {
        float f = (float)i / cube.vertices().size();
        cube.color(al::Color(al::HSV(f, 1 - f, 1), 1));
    }
    cube.generateNormals();

    // set up sphere
    sphere.primitive(al::Graphics::TRIANGLES);
    addSphere(sphere, 1.0, 32, 32);
    for (int i = 0; i < sphere.vertices().size(); ++i) {
        float f = (float)i / sphere.vertices().size();
        sphere.color(al::Color(al::HSV(f, 1 - f, 1), 1));
    }
    sphere.generateNormals();

    // set up light
    light.ambient(al::Color(0.4, 0.4, 0.4, 1.0));
    light.pos(5, 5, 5);

    std::function<StereoCubemap* (CubemapSource*, StereoCubemap*)> callback = boost::bind(&Renderer::onNextCubemap,
                                                                                this,
                                                                                _1,
                                                                                _2);
    cubemapSource->setOnNextCubemap(callback);
}

Renderer::~Renderer()
{
}

bool Renderer::onCreate()
{
    std::cout << "OpenGL version: " << glGetString(GL_VERSION) << ", GLSL version " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
    return OmniApp::onCreate();
}

bool Renderer::onFrame()
{
    now = al::MainLoop::now();

    bool result;
    {
        boost::mutex::scoped_lock lock(nextCubemapMutex);
        result = OmniApp::onFrame();
        newCubemap = false;
    }
    if (onDisplayedFrame) onDisplayedFrame(this);
    return result;
}

StereoCubemap* Renderer::onNextCubemap(CubemapSource* source, StereoCubemap* cubemap)
{
    boost::mutex::scoped_lock lock(nextCubemapMutex);
    StereoCubemap* oldCubemap = this->cubemap;
    this->cubemap = cubemap;
    newCubemap = true;
    return oldCubemap;
}

void Renderer::onDraw(al::Graphics& gl)
{
    int faceIndex = mOmni.face();
    int eyeIndex = (mOmni.eye() <= 0.0f) ? 0 : 1;

    {

        // render cubemap
        if (cubemap && cubemap->getEyesCount() > eyeIndex)
        {
            Cubemap* eye = cubemap->getEye(eyeIndex);
            if (eye->getFacesCount() > faceIndex)
            {
                // Choose right face for flipping
                CubemapFace* face;
                if (faceIndex == 0)
                {
                    face = eye->getFace(1);
                }
                else if (faceIndex == 1)
                {
                    face = eye->getFace(0);
                }
                else
                {
                    face = eye->getFace(faceIndex);
                }

                glUseProgram(0);
                glDepthMask(GL_FALSE);

                // flip face
                glPixelZoom(-1.0, 1.0);
                glRasterPos2d(1.0, -1.0);

                // draw the background
                glDrawPixels(face->getContent()->getWidth(),
                             face->getContent()->getHeight(),
                             GL_RGBA,
                             GL_UNSIGNED_BYTE,
                             (GLvoid*)face->getContent()->getPixels());

                glDepthMask(GL_TRUE);

                if(newCubemap)
                {
                    if (onDisplayedCubemapFace) onDisplayedCubemapFace(this, faceIndex + eyeIndex * Cubemap::MAX_FACES_COUNT);
                }
            }
        }
    }

    light();
    mShader.begin();
    mOmni.uniforms(mShader);

    gl.pushMatrix();

    //gl.draw(cube);

    gl.pushMatrix();
    // rotate over time:
    gl.rotate(now*30., 0.707, 0.707, 0.);
    gl.translate(1., 1., 1.);
    //gl.draw(sphere);
    gl.popMatrix();

    gl.popMatrix();

    mShader.end();
}

void Renderer::onAnimate(al_sec dt)
{
    pose = nav();
}

void Renderer::onMessage(al::osc::Message& m)
{
    OmniApp::onMessage(m);
}

bool Renderer::onKeyDown(const al::Keyboard& k)
{
    return true;
}

void Renderer::setOnDisplayedFrame(std::function<void (Renderer*)>& callback)
{
    onDisplayedFrame = callback;
}

void Renderer::setOnDisplayedCubemapFace(std::function<void (Renderer*, int)>& callback)
{
    onDisplayedCubemapFace = callback;
}
<|endoftext|>


<commit_before>#include "cocl/cocl_device.h"

#include "cocl/cocl_context.h"

#include "EasyCL/EasyCL.h"

#include <iostream>
using namespace std;

namespace cocl {
    // int currentDevice = 0;
}

using namespace cocl;

namespace cocl {
    template<typename T>
    static std::string toString(T val) {
       std::ostringstream myostringstream;
       myostringstream << val;
       return myostringstream.str();
    }

    cl_device_id getDeviceByIdx(int gpu) {
        cl_int error;
        int currentGpuIndex = 0;
        cl_platform_id platform_ids[10];
        cl_uint num_platforms;
        // error = clGetPlatformIDs(0, 0, &num_platforms);
        // cout << "Num OpenCL platforms: " << num_platforms << endl;
        error = clGetPlatformIDs(10, platform_ids, &num_platforms);
        if (error != CL_SUCCESS) {
           throw std::runtime_error("Error getting OpenCL platforms ids, OpenCL errorcode: opencl error " + toString(error));
        }
        if(num_platforms == 0) {
           throw std::runtime_error("Error: no OpenCL platforms available");
        }
        for(int platform =  0; platform < (int)num_platforms; platform++) {
            cl_platform_id platform_id = platform_ids[platform];
    //        cout << "checking platform id " << platform_id << endl;
            cl_device_id device_ids[100];
            cl_uint num_devices;
            error = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR , 100, device_ids, &num_devices);
            if (error != CL_SUCCESS) {
                continue;
    //           throw std::runtime_error("Error getting device ids for platform " + toString(platform) + ": " + errorMessage(error));
            }
    //        cout << "gpu=" << gpu << " currentGpuIndex=" << currentGpuIndex << " num_devices=" << num_devices << endl;
            if(( gpu - currentGpuIndex) < (int)num_devices) {
                return device_ids[(gpu - currentGpuIndex)];
                // return new EasyCL(platform_id, device_ids[(gpu - currentGpuIndex)], verbose);
            } else {
                currentGpuIndex += num_devices;
            }
        }
        if(gpu == 0) {
            throw std::runtime_error("No OpenCL-enabled GPUs found");
        } else {
            throw std::runtime_error("Not enough OpenCL-enabled GPUs found to satisfy gpu index: " + toString(gpu) );
        }
    }
}

size_t cuDeviceGet (CUdevice *device, int ordinal) {
    COCL_PRINT(cout << "cuDeviceGet redirected" << endl);
    ThreadVars *v = getThreadVars();
    *(int *)device = v->currentDevice;
    return 0;
}

size_t cuDeviceGetCount (int *count) {
    return cudaGetDeviceCount(count);
}

size_t cudaGetDevice(CUdevice *device) {
    COCL_PRINT(cout << "cudaGetDevice" << endl);
    ThreadVars *v = getThreadVars();
    *device = v->currentDevice;
    return 0;
}

size_t cudaGetDeviceCount (int *count) {
    COCL_PRINT(cout << "cudaGetDeviceCount" << endl);
    *count = easycl::DevicesInfo::getNumGpus();
    // *count = 1;  // we need a bunch of work to iplement more thna 1 device...
    return 0;
}

size_t cudaSetDevice (CUdevice device) {
    COCL_PRINT(cout << "cudaSetDevice stub device=" << device << endl);
    ThreadVars *v = getThreadVars();
    if(device < 0) {
        throw runtime_error("Cannot set device less than 0");
    }
    if(device >= easycl::DevicesInfo::getNumGpus()) {
    //if(device > 0) {
        throw runtime_error("Cannot set device to outside of range 0 to " + toString(easycl::DevicesInfo::getNumGpus() - 1));
        //throw runtime_error("Not yet implemented: switching to non-zero device");
    }
    v->currentDevice = device;
    return 0;
}

size_t cudaDeviceReset() {
    //throw runtime_error("Not yet implemented, please raise an issue at https://github.com/hughperkins/cuda-on-cl/issues");
}

size_t cudaDeviceSynchronize() {
    throw runtime_error("Not yet implemented, please raise an issue at https://github.com/hughperkins/cuda-on-cl/issues");
}
<commit_msg>let cudaDeviceSynrhonize through for now<commit_after>#include "cocl/cocl_device.h"

#include "cocl/cocl_context.h"

#include "EasyCL/EasyCL.h"

#include <iostream>
using namespace std;

namespace cocl {
    // int currentDevice = 0;
}

using namespace cocl;

namespace cocl {
    template<typename T>
    static std::string toString(T val) {
       std::ostringstream myostringstream;
       myostringstream << val;
       return myostringstream.str();
    }

    cl_device_id getDeviceByIdx(int gpu) {
        cl_int error;
        int currentGpuIndex = 0;
        cl_platform_id platform_ids[10];
        cl_uint num_platforms;
        // error = clGetPlatformIDs(0, 0, &num_platforms);
        // cout << "Num OpenCL platforms: " << num_platforms << endl;
        error = clGetPlatformIDs(10, platform_ids, &num_platforms);
        if (error != CL_SUCCESS) {
           throw std::runtime_error("Error getting OpenCL platforms ids, OpenCL errorcode: opencl error " + toString(error));
        }
        if(num_platforms == 0) {
           throw std::runtime_error("Error: no OpenCL platforms available");
        }
        for(int platform =  0; platform < (int)num_platforms; platform++) {
            cl_platform_id platform_id = platform_ids[platform];
    //        cout << "checking platform id " << platform_id << endl;
            cl_device_id device_ids[100];
            cl_uint num_devices;
            error = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU | CL_DEVICE_TYPE_ACCELERATOR , 100, device_ids, &num_devices);
            if (error != CL_SUCCESS) {
                continue;
    //           throw std::runtime_error("Error getting device ids for platform " + toString(platform) + ": " + errorMessage(error));
            }
    //        cout << "gpu=" << gpu << " currentGpuIndex=" << currentGpuIndex << " num_devices=" << num_devices << endl;
            if(( gpu - currentGpuIndex) < (int)num_devices) {
                return device_ids[(gpu - currentGpuIndex)];
                // return new EasyCL(platform_id, device_ids[(gpu - currentGpuIndex)], verbose);
            } else {
                currentGpuIndex += num_devices;
            }
        }
        if(gpu == 0) {
            throw std::runtime_error("No OpenCL-enabled GPUs found");
        } else {
            throw std::runtime_error("Not enough OpenCL-enabled GPUs found to satisfy gpu index: " + toString(gpu) );
        }
    }
}

size_t cuDeviceGet (CUdevice *device, int ordinal) {
    COCL_PRINT(cout << "cuDeviceGet redirected" << endl);
    ThreadVars *v = getThreadVars();
    *(int *)device = v->currentDevice;
    return 0;
}

size_t cuDeviceGetCount (int *count) {
    return cudaGetDeviceCount(count);
}

size_t cudaGetDevice(CUdevice *device) {
    COCL_PRINT(cout << "cudaGetDevice" << endl);
    ThreadVars *v = getThreadVars();
    *device = v->currentDevice;
    return 0;
}

size_t cudaGetDeviceCount (int *count) {
    COCL_PRINT(cout << "cudaGetDeviceCount" << endl);
    *count = easycl::DevicesInfo::getNumGpus();
    // *count = 1;  // we need a bunch of work to iplement more thna 1 device...
    return 0;
}

size_t cudaSetDevice (CUdevice device) {
    COCL_PRINT(cout << "cudaSetDevice stub device=" << device << endl);
    ThreadVars *v = getThreadVars();
    if(device < 0) {
        throw runtime_error("Cannot set device less than 0");
    }
    if(device >= easycl::DevicesInfo::getNumGpus()) {
    //if(device > 0) {
        throw runtime_error("Cannot set device to outside of range 0 to " + toString(easycl::DevicesInfo::getNumGpus() - 1));
        //throw runtime_error("Not yet implemented: switching to non-zero device");
    }
    v->currentDevice = device;
    return 0;
}

size_t cudaDeviceReset() {
    cout << "ignoring cudaDeviceReset for now" << endl;
    return 0;
    //throw runtime_error("Not yet implemented, please raise an issue at https://github.com/hughperkins/cuda-on-cl/issues");
}

size_t cudaDeviceSynchronize() {
    cout << "ignoring cudaDeviceSynchronize for now" << endl;
    return 0;
}
<|endoftext|>


<commit_before>#include "path.hpp"
#include "configfile.hpp"
#include "stringarray.hpp"
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>

#ifdef PACKAGE_NAME
#define SUBDIR ("/" PACKAGE_NAME)
#else
#error "No PACKAGE_NAME defined"
#endif

namespace Path {

std::string userConfig;
std::vector<std::string> globalConfig;
std::string userData;
std::vector<std::string> globalData;

static std::string exeDir()
{
    char buf[PATH_MAX + 1];
    ssize_t sz = readlink("/proc/self/exe", buf, sizeof(buf));
    if (sz > 0) {
        unsigned int p = sz;
        while (p && buf[p - 1] != '/')
            --p;
        if (p) {
            if (p > 1)
                --p;
            return std::string(buf, p);
        }
    }
    return std::string();
}

/* The "dev config" is a file named "config.ini" in the same path as
   the executable.  It is used to allow a development executable to
   find resources that have not been installed yet.  The dev config is
   only used for setting paths and other variables are ignored.  */
static void loadDevConfig()
{
    std::string path = exeDir();
    if (path.empty())
        return;
    path += "/config.ini";
    ConfigFile config;
    config.read(path.c_str());
    config.getString("path", "config.user", userConfig);
    config.getString("path", "data.user", userData);
    config.getStringArray("path", "config.global", globalConfig);
    config.getStringArray("path", "data.global", globalData);
}

void init()
{
    static bool initted = false;
    if (initted)
        return;
    initted = true;

    // The dev config file has highest precedence
    loadDevConfig();

    std::vector<std::string>::iterator i, e;
    char const *env;
    std::string home;
    env = getenv("HOME");
    if (env) home = env;

    // XDG data locations

    if (userConfig.empty()) {
        // User config $XDG_CONFIG_HOME, otherwise $HOME/.config
        env = getenv("XDG_CONFIG_HOME");
        if (env)
            userConfig = env;
        else if (!home.empty())
            userConfig = home + "/.config";
        if (!userConfig.empty())
            userConfig += SUBDIR;
    }

    if (globalConfig.empty()) {
        // Global config $XDG_CONFIG_DIRS, otherwise /etc/xdg
        env = getenv("XDG_CONFIG_DIRS");
        if (env)
            parseStringArray(globalConfig, env);
        else
            globalConfig.push_back("/etc/xdg");
        i = globalConfig.begin();
        e = globalConfig.end();
        for (; i != e; ++i) *i += SUBDIR;
    }

    if (userData.empty()) {
        // User data $XDG_DATA_HOME, otherwise $HOME/.local/share
        env = getenv("XDG_DATA_HOME");
        if (env)
            userData = env;
        else if (!home.empty())
            userData = home + "/.local/share";
        if (!userData.empty())
            userData += SUBDIR;
    }

    if (globalData.empty()) {
        // Global data $XDG_DATA_DIRS,
        // otherwise /usr/local/share/:/usr/share/
        env = getenv("XDG_DATA_DIRS");
        if (env)
            parseStringArray(globalData, env);
        else {
            globalData.push_back("/usr/local/share");
            globalData.push_back("/usr/share");
        }
        i = globalData.begin();
        e = globalData.end();
        for (; i != e; ++i) *i += SUBDIR;
    }
}

}
<commit_msg>Changed search path fallback code.<commit_after>#include "path.hpp"
#include "configfile.hpp"
#include "stringarray.hpp"
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>

#ifdef PACKAGE_NAME
#define SUBDIR ("/" PACKAGE_NAME)
#else
#error "No PACKAGE_NAME defined"
#endif

namespace Path {

std::string userConfig;
std::vector<std::string> globalConfig;
std::string userData;
std::vector<std::string> globalData;

static std::string exeDir()
{
    char buf[PATH_MAX + 1];
    ssize_t sz = readlink("/proc/self/exe", buf, sizeof(buf));
    if (sz > 0) {
        unsigned int p = sz;
        while (p && buf[p - 1] != '/')
            --p;
        if (p) {
            if (p > 1)
                --p;
            return std::string(buf, p);
        }
    }
    return std::string();
}

/* The "dev config" is a file named "config.ini" in the same path as
   the executable.  It is used to allow a development executable to
   find resources that have not been installed yet.  The dev config is
   only used for setting paths and other variables are ignored.  */
static void loadDevConfig()
{
    std::string path = exeDir();
    if (path.empty())
        return;
    path += "/config.ini";
    ConfigFile config;
    config.read(path.c_str());
    config.getString("path", "config.user", userConfig);
    config.getString("path", "data.user", userData);
    config.getStringArray("path", "config.global", globalConfig);
    config.getStringArray("path", "data.global", globalData);
}

void init()
{
    static bool initted = false;
    if (initted)
        return;
    initted = true;

    // The dev config file has highest precedence
    loadDevConfig();

    std::vector<std::string>::iterator i, e;
    char const *env;
    std::string home;
    env = getenv("HOME");
    if (env) home = env;

    // XDG data locations

    if (userConfig.empty()) {
        // User config $XDG_CONFIG_HOME, otherwise $HOME/.config
        env = getenv("XDG_CONFIG_HOME");
        if (env)
            userConfig = env;
        if (userConfig.empty() && !home.empty())
            userConfig = home + "/.config";
        if (!userConfig.empty())
            userConfig += SUBDIR;
    }

    if (globalConfig.empty()) {
        // Global config $XDG_CONFIG_DIRS, otherwise /etc/xdg
        env = getenv("XDG_CONFIG_DIRS");
        if (env)
            parseStringArray(globalConfig, env);
        if (globalConfig.empty())
            globalConfig.push_back("/etc/xdg");
        i = globalConfig.begin();
        e = globalConfig.end();
        for (; i != e; ++i) *i += SUBDIR;
    }

    if (userData.empty()) {
        // User data $XDG_DATA_HOME, otherwise $HOME/.local/share
        env = getenv("XDG_DATA_HOME");
        if (env)
            userData = env;
        if (userData.empty() && !home.empty())
            userData = home + "/.local/share";
        if (!userData.empty())
            userData += SUBDIR;
    }

    if (globalData.empty()) {
        // Global data $XDG_DATA_DIRS,
        // otherwise /usr/local/share/:/usr/share/
        env = getenv("XDG_DATA_DIRS");
        if (env)
            parseStringArray(globalData, env);
        if (globalData.empty()) {
            globalData.push_back("/usr/local/share");
            globalData.push_back("/usr/share");
        }
        i = globalData.begin();
        e = globalData.end();
        for (; i != e; ++i) *i += SUBDIR;
    }
}

}
<|endoftext|>


<commit_before>#include <miopen/convolution.hpp>
#include <miopen/errors.hpp>

namespace miopen {

ConvolutionDescriptor::ConvolutionDescriptor(int p_pad_h, int p_pad_w, int p_u, int p_v, int p_dilation_h, int p_dilation_w)
: mode(miopenConvolution), pad_h(p_pad_h), pad_w(p_pad_w), u(p_u), v(p_v), dilation_h(p_dilation_h), dilation_w(p_dilation_w)
{
	if(pad_h < 0 || pad_w < 0 || u < 0 || v < 0 || dilation_h < 0 || dilation_w < 0) {
		MIOPEN_THROW(miopenStatusBadParm, "Parameters to filter cannot be negative");
	}
}

ConvolutionDescriptor::ConvolutionDescriptor(miopenConvolutionMode_t p_mode, int p_pad_h, int p_pad_w, int p_u, int p_v, int p_dilation_h, int p_dilation_w)
: mode(p_mode), pad_h(p_pad_h), pad_w(p_pad_w), u(p_u), v(p_v), dilation_h(p_dilation_h), dilation_w(p_dilation_w)
{
	if(pad_h < 0 || pad_w < 0 || u < 0 || v < 0 || dilation_h < 0 || dilation_w < 0) {
		MIOPEN_THROW(miopenStatusBadParm, "Parameters to filter cannot be negative");
	}
}

std::tuple<int, int, int, int> ConvolutionDescriptor::GetForwardOutputDim(
	const TensorDescriptor& inputTensorDesc,
	const TensorDescriptor& filterDesc)
const
{
	assert(inputTensorDesc.GetLengths().size() == 4);
	assert(filterDesc.GetLengths().size() == 4);

	if (inputTensorDesc.GetType() != filterDesc.GetType()) {
		MIOPEN_THROW(miopenStatusBadParm, "Types do not match for the filter");
	}

	int input_n;
	int input_c;
	int input_h;
	int input_w;

	std::tie(input_n, input_c, input_h, input_w) = miopen::tie4(inputTensorDesc.GetLengths());

	int filter_k;
	int filter_c;
	int filter_h;
	int filter_w;

	std::tie(filter_k, filter_c, filter_h, filter_w) = miopen::tie4(filterDesc.GetLengths());

	if(input_c != filter_c) {
		MIOPEN_THROW(miopenStatusBadParm, "Channels do not match for the filter");
	}

	int output_c;
	int output_h;
	int output_w;
	if (mode == miopenConvolution) {
		output_c = filter_k;
		output_h = std::max(1, (input_h - filter_h + 2 * pad_h) / u + 1);
		output_w = std::max(1, (input_w - filter_w + 2 * pad_w) / v + 1);
	}
	else if (mode == miopenDeconvolution) {
		output_c = filter_c;
		output_h = std::max(1, u * (input_h - 1) + filter_h - 2 * pad_h );
		output_w = std::max(1, v * (input_w - 1) + filter_w - 2 * pad_w );
	}

	return std::make_tuple(
		input_n,
		output_c,
		output_h,
		output_w
	);

//	return std::make_tuple(
//		input_n,
//		filter_k,
//		std::max(1, (input_h - filter_h + 2*pad_h) / u + 1),
//		std::max(1, (input_w - filter_w + 2*pad_w) / v + 1)
//	);
}

size_t ConvolutionDescriptor::ForwardGetWorkSpaceSizeGEMM(
        Handle&                 handle,
		const TensorDescriptor& wDesc,
		const TensorDescriptor& yDesc) const
{
	int out_h, out_w;
	std::tie(std::ignore, std::ignore, out_h, out_w) = miopen::tie4(yDesc.GetLengths());

	int wei_c, wei_h, wei_w;
	std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(wDesc.GetLengths());

	size_t workspace_size = wei_c*wei_h*wei_w * out_h*out_w * sizeof(yDesc.GetType());

    // gfx803 devices have 4gb-6gb memory
    if(workspace_size > (1 << 30) && handle.GetDeviceName() == "gfx803")
        workspace_size = 0;

	return (wei_h == 1 && wei_w == 1 && v == 1 && u == 1) ? 0 : workspace_size;
}

size_t ConvolutionDescriptor::ForwardGetWorkSpaceSize(
        Handle&                 handle,
		const TensorDescriptor& wDesc,
		const TensorDescriptor& xDesc,
		const TensorDescriptor& yDesc) const
{
	size_t workspace_size_gemm = ForwardGetWorkSpaceSizeGEMM(handle, wDesc, yDesc);
	size_t workspace_size_fft  = ForwardGetWorkSpaceSizeFFT (wDesc, xDesc, yDesc);

	return (workspace_size_fft > workspace_size_gemm ? workspace_size_fft : workspace_size_gemm);
}

size_t ConvolutionDescriptor::BackwardDataGetWorkSpaceSize(
        Handle&                 handle,
		const TensorDescriptor& wDesc,
		const TensorDescriptor& dyDesc,
		const TensorDescriptor& dxDesc) const
{
	(void)handle; // suppress warning
	size_t workspace_size_gemm = BackwardDataGetWorkSpaceSizeGEMM(handle, wDesc, dyDesc);
	size_t workspace_size_fft  = BackwardGetWorkSpaceSizeFFT (wDesc, dyDesc, dxDesc);

	return (workspace_size_fft > workspace_size_gemm ? workspace_size_fft : workspace_size_gemm);
}

// weights_n = output_c
// weights_c = input_c
// weights_h = 2*pad_h + input_h - u*(output_h - 1)
// weights_w = 2*pad_w + input_w - v*(output_w - 1)
std::tuple<int, int, int, int> ConvolutionDescriptor::GetBackwardsWeightsDim(
	const TensorDescriptor& inputTensorDesc,
	const TensorDescriptor& outputTensorDesc)
const
{
	assert(inputTensorDesc.GetLengths().size() == 4);
	assert(outputTensorDesc.GetLengths().size() == 4);

	if (inputTensorDesc.GetType() != outputTensorDesc.GetType()) {
		MIOPEN_THROW(miopenStatusBadParm, "Types do not match for the filter");
	}

	int input_n;
	int input_c;
	int input_h;
	int input_w;

	std::tie(input_n, input_c, input_h, input_w) = miopen::tie4(inputTensorDesc.GetLengths());

	int output_n;
	int output_c;
	int output_h;
	int output_w;

	std::tie(output_n, output_c, output_h, output_w) = miopen::tie4(outputTensorDesc.GetLengths());

	// if(input_c != filter_c) {
	// 	MIOPEN_THROW(miopenStatusBadParm, "Channels do not match for the filter");
	// }

	return std::make_tuple(
		output_c,
		input_c,
		2*pad_h + input_h - u*(output_h - 1),
		2*pad_w + input_w - v*(output_w - 1)
	);
}

std::tuple<int, int, int, int> ConvolutionDescriptor::GetBackwardOutputDim(
	const TensorDescriptor& outputTensorDesc,
	const TensorDescriptor& filterDesc)
const
{
	assert(outputTensorDesc.GetLengths().size() == 4);
	assert(filterDesc.GetLengths().size() == 4);

	if (outputTensorDesc.GetType() != filterDesc.GetType()) {
		MIOPEN_THROW(miopenStatusBadParm, "Types do not match for the filter");
	}

	int output_n;
	int output_c;
	int output_h;
	int output_w;

	std::tie(output_n, output_c, output_h, output_w) = miopen::tie4(outputTensorDesc.GetLengths());

	int filter_k;
	int filter_c;
	int filter_h;
	int filter_w;

	std::tie(filter_k, filter_c, filter_h, filter_w) = miopen::tie4(filterDesc.GetLengths());

	if(output_c != filter_k) {
		MIOPEN_THROW(miopenStatusBadParm, "Channels do not match for the filter");
	}

	return std::make_tuple(
		output_n,
		filter_c,
		u * (output_h - 1) - 2*pad_h + filter_h,
		v * (output_w - 1) - 2*pad_w + filter_w
	);
}

TensorDescriptor ConvolutionDescriptor::GetForwardOutputTensor(
	const TensorDescriptor& inputTensorDesc,
	const TensorDescriptor& filterDesc) const
{
	auto dims = this->GetForwardOutputDim(inputTensorDesc, filterDesc);
	return TensorDescriptor(inputTensorDesc.GetType(), {
		std::get<0>(dims),
		std::get<1>(dims),
		std::get<2>(dims),
		std::get<3>(dims)});
}

TensorDescriptor ConvolutionDescriptor::GetBackwardOutputTensor(
	const TensorDescriptor& outputTensorDesc,
	const TensorDescriptor& filterDesc) const
{
	auto dims = this->GetBackwardOutputDim(outputTensorDesc, filterDesc);
	return TensorDescriptor(outputTensorDesc.GetType(), {
		std::get<0>(dims),
		std::get<1>(dims),
		std::get<2>(dims),
		std::get<3>(dims)});
}

TensorDescriptor ConvolutionDescriptor::GetBackwardWeightsTensor(
	const TensorDescriptor& inputTensorDesc,
	const TensorDescriptor& outputTensorDesc) const
{
	auto dims = this->GetBackwardsWeightsDim(inputTensorDesc, outputTensorDesc);
	return TensorDescriptor(outputTensorDesc.GetType(), {
		std::get<0>(dims),
		std::get<1>(dims),
		std::get<2>(dims),
		std::get<3>(dims)});
}

size_t ConvolutionDescriptor::BackwardDataGetWorkSpaceSizeGEMM(
	Handle&                     handle,
	const TensorDescriptor&     wDesc,
	const TensorDescriptor&		dyDesc) const
{
	int out_h, out_w;
	std::tie(std::ignore, std::ignore, out_h, out_w) = miopen::tie4(dyDesc.GetLengths());
	int wei_c, wei_h, wei_w;
	std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(wDesc.GetLengths());
	size_t gemm_size = wei_c*wei_h*wei_w * out_h*out_w * sizeof(dyDesc.GetType());

	// gfx803 devices have limited memory
	// TODO: be graceful, need to ensure we can execute a config on the GPU
	// what if both the algos require > (1 << 30) memory
	if (handle.GetDeviceName() == "gfx803" && gemm_size > (1 << 30))
		gemm_size = 0;

	return (wei_h == 1 && wei_w == 1 && v == 1 && u == 1) ? 0 : gemm_size;

}

size_t ConvolutionDescriptor::BackwardWeightsGetWorkSpaceSizeGEMM(
    Handle&                     handle,
    const TensorDescriptor&     dyDesc,
	const TensorDescriptor&		dwDesc) const
{
    int out_h, out_w;
    std::tie(std::ignore, std::ignore, out_h, out_w) = miopen::tie4(dyDesc.GetLengths());
    int wei_c, wei_h, wei_w;
    std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(dwDesc.GetLengths());
    size_t gemm_size = wei_c*wei_h*wei_w * out_h*out_w * sizeof(dyDesc.GetType());

    // gfx803 devices have limited memory
    // TODO: be graceful, need to ensure we can execute a config on the GPU
    // what if both the algos require > (1 << 30) memory
    if(handle.GetDeviceName() == "gfx803" && gemm_size > (1 << 30))
        gemm_size = 0;

    return gemm_size;
}

size_t ConvolutionDescriptor::BackwardWeightsGetWorkSpaceSizeDirect(
    Handle&                     handle,
    const TensorDescriptor&     dyDesc,
    const TensorDescriptor&     xDesc,
    const TensorDescriptor&     dwDesc) const
{
    mlo_construct_BwdWrW2D construct_params(0); // backward with regards to weights
    construct_params.doSearch(false);
    construct_params.setStream(&handle);
    construct_params.setOutputDescFromMLDesc(dyDesc);
    construct_params.setInputDescFromMLDesc(xDesc);
    construct_params.setWeightDescFromMLDesc(dwDesc);
    construct_params.setConvDescr(pad_h, pad_w, u, v, dilation_h, dilation_w);
    construct_params.mloConstruct();

    return construct_params.getWorkSpaceSzBytes();
}

size_t ConvolutionDescriptor::ConvolutionBackwardWeightsGetWorkSpaceSize(
    Handle&                     handle,
    const TensorDescriptor&      dyDesc,
	const TensorDescriptor&		 xDesc,
	const TensorDescriptor&		 dwDesc) const
{
    return std::max(
            BackwardWeightsGetWorkSpaceSizeDirect(handle, dyDesc, xDesc, dwDesc),
            BackwardWeightsGetWorkSpaceSizeGEMM(handle, dyDesc, dwDesc)
        );
}
std::ostream& operator<< (std::ostream& stream, const ConvolutionDescriptor& c)
{
	stream << c.pad_h << ", ";
	stream << c.pad_w << ", ";
	stream << c.u << ", ";
	stream << c.v << ", ";
	stream << c.dilation_h << ", ";
	stream << c.dilation_w << ", ";
	return stream;
}

} // namespace miopen
<commit_msg>deconv forward change1<commit_after>#include <miopen/convolution.hpp>
#include <miopen/errors.hpp>

namespace miopen {

ConvolutionDescriptor::ConvolutionDescriptor(int p_pad_h, int p_pad_w, int p_u, int p_v, int p_dilation_h, int p_dilation_w)
: mode(miopenConvolution), pad_h(p_pad_h), pad_w(p_pad_w), u(p_u), v(p_v), dilation_h(p_dilation_h), dilation_w(p_dilation_w)
{
	if(pad_h < 0 || pad_w < 0 || u < 0 || v < 0 || dilation_h < 0 || dilation_w < 0) {
		MIOPEN_THROW(miopenStatusBadParm, "Parameters to filter cannot be negative");
	}
}

ConvolutionDescriptor::ConvolutionDescriptor(miopenConvolutionMode_t p_mode, int p_pad_h, int p_pad_w, int p_u, int p_v, int p_dilation_h, int p_dilation_w)
: mode(p_mode), pad_h(p_pad_h), pad_w(p_pad_w), u(p_u), v(p_v), dilation_h(p_dilation_h), dilation_w(p_dilation_w)
{
	if(pad_h < 0 || pad_w < 0 || u < 0 || v < 0 || dilation_h < 0 || dilation_w < 0) {
		MIOPEN_THROW(miopenStatusBadParm, "Parameters to filter cannot be negative");
	}
}

std::tuple<int, int, int, int> ConvolutionDescriptor::GetForwardOutputDim(
	const TensorDescriptor& inputTensorDesc,
	const TensorDescriptor& filterDesc)
const
{
	assert(inputTensorDesc.GetLengths().size() == 4);
	assert(filterDesc.GetLengths().size() == 4);

	if (inputTensorDesc.GetType() != filterDesc.GetType()) {
		MIOPEN_THROW(miopenStatusBadParm, "Types do not match for the filter");
	}

	int input_n;
	int input_c;
	int input_h;
	int input_w;

	std::tie(input_n, input_c, input_h, input_w) = miopen::tie4(inputTensorDesc.GetLengths());

	int filter_k;
	int filter_c;
	int filter_h;
	int filter_w;

	std::tie(filter_k, filter_c, filter_h, filter_w) = miopen::tie4(filterDesc.GetLengths());

	if(input_c != filter_c) {
		MIOPEN_THROW(miopenStatusBadParm, "Channels do not match for the filter");
	}

	int output_c;
	int output_h;
	int output_w;
	if (mode == miopenConvolution) {
		output_c = filter_k;
		output_h = std::max(1, (input_h - filter_h + 2 * pad_h) / u + 1);
		output_w = std::max(1, (input_w - filter_w + 2 * pad_w) / v + 1);
	}
	else if (mode == miopenDeconvolution) {
		output_c = filter_c;
		output_h = std::max(1, u * (input_h - 1) + filter_h - 2 * pad_h );
		output_w = std::max(1, v * (input_w - 1) + filter_w - 2 * pad_w );
	}

	return std::make_tuple(
		input_n,
		output_c,
		output_h,
		output_w
	);

//	return std::make_tuple(
//		input_n,
//		filter_k,
//		std::max(1, (input_h - filter_h + 2*pad_h) / u + 1),
//		std::max(1, (input_w - filter_w + 2*pad_w) / v + 1)
//	);
}

size_t ConvolutionDescriptor::ForwardGetWorkSpaceSizeGEMM(
        Handle&                 handle,
		const TensorDescriptor& wDesc,
		const TensorDescriptor& yDesc) const
{
	int out_h, out_w;
	std::tie(std::ignore, std::ignore, out_h, out_w) = miopen::tie4(yDesc.GetLengths());

	int wei_c, wei_h, wei_w;
	std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(wDesc.GetLengths());

	size_t workspace_size = wei_c*wei_h*wei_w * out_h*out_w * sizeof(yDesc.GetType());

    // gfx803 devices have 4gb-6gb memory
    if(workspace_size > (1 << 30) && handle.GetDeviceName() == "gfx803")
        workspace_size = 0;

	return (wei_h == 1 && wei_w == 1 && v == 1 && u == 1) ? 0 : workspace_size;
}

size_t ConvolutionDescriptor::ForwardGetWorkSpaceSize(
        Handle&                 handle,
		const TensorDescriptor& wDesc,
		const TensorDescriptor& xDesc,
		const TensorDescriptor& yDesc) const
{
	size_t workspace_size_gemm = ForwardGetWorkSpaceSizeGEMM(handle, wDesc, yDesc);
	size_t workspace_size_fft;
	if (mode == miopenDeconvolution)
	    workspace_size_fft = 0;
	else
	    workspace_size_fft  = ForwardGetWorkSpaceSizeFFT (wDesc, xDesc, yDesc);

	return (workspace_size_fft > workspace_size_gemm ? workspace_size_fft : workspace_size_gemm);
}

size_t ConvolutionDescriptor::BackwardDataGetWorkSpaceSize(
        Handle&                 handle,
		const TensorDescriptor& wDesc,
		const TensorDescriptor& dyDesc,
		const TensorDescriptor& dxDesc) const
{
	(void)handle; // suppress warning
	size_t workspace_size_gemm = BackwardDataGetWorkSpaceSizeGEMM(handle, wDesc, dyDesc);
	size_t workspace_size_fft  = BackwardGetWorkSpaceSizeFFT (wDesc, dyDesc, dxDesc);

	return (workspace_size_fft > workspace_size_gemm ? workspace_size_fft : workspace_size_gemm);
}

// weights_n = output_c
// weights_c = input_c
// weights_h = 2*pad_h + input_h - u*(output_h - 1)
// weights_w = 2*pad_w + input_w - v*(output_w - 1)
std::tuple<int, int, int, int> ConvolutionDescriptor::GetBackwardsWeightsDim(
	const TensorDescriptor& inputTensorDesc,
	const TensorDescriptor& outputTensorDesc)
const
{
	assert(inputTensorDesc.GetLengths().size() == 4);
	assert(outputTensorDesc.GetLengths().size() == 4);

	if (inputTensorDesc.GetType() != outputTensorDesc.GetType()) {
		MIOPEN_THROW(miopenStatusBadParm, "Types do not match for the filter");
	}

	int input_n;
	int input_c;
	int input_h;
	int input_w;

	std::tie(input_n, input_c, input_h, input_w) = miopen::tie4(inputTensorDesc.GetLengths());

	int output_n;
	int output_c;
	int output_h;
	int output_w;

	std::tie(output_n, output_c, output_h, output_w) = miopen::tie4(outputTensorDesc.GetLengths());

	// if(input_c != filter_c) {
	// 	MIOPEN_THROW(miopenStatusBadParm, "Channels do not match for the filter");
	// }

	return std::make_tuple(
		output_c,
		input_c,
		2*pad_h + input_h - u*(output_h - 1),
		2*pad_w + input_w - v*(output_w - 1)
	);
}

std::tuple<int, int, int, int> ConvolutionDescriptor::GetBackwardOutputDim(
	const TensorDescriptor& outputTensorDesc,
	const TensorDescriptor& filterDesc)
const
{
	assert(outputTensorDesc.GetLengths().size() == 4);
	assert(filterDesc.GetLengths().size() == 4);

	if (outputTensorDesc.GetType() != filterDesc.GetType()) {
		MIOPEN_THROW(miopenStatusBadParm, "Types do not match for the filter");
	}

	int output_n;
	int output_c;
	int output_h;
	int output_w;

	std::tie(output_n, output_c, output_h, output_w) = miopen::tie4(outputTensorDesc.GetLengths());

	int filter_k;
	int filter_c;
	int filter_h;
	int filter_w;

	std::tie(filter_k, filter_c, filter_h, filter_w) = miopen::tie4(filterDesc.GetLengths());

	if(output_c != filter_k) {
		MIOPEN_THROW(miopenStatusBadParm, "Channels do not match for the filter");
	}

	return std::make_tuple(
		output_n,
		filter_c,
		u * (output_h - 1) - 2*pad_h + filter_h,
		v * (output_w - 1) - 2*pad_w + filter_w
	);
}

TensorDescriptor ConvolutionDescriptor::GetForwardOutputTensor(
	const TensorDescriptor& inputTensorDesc,
	const TensorDescriptor& filterDesc) const
{
	auto dims = this->GetForwardOutputDim(inputTensorDesc, filterDesc);
	return TensorDescriptor(inputTensorDesc.GetType(), {
		std::get<0>(dims),
		std::get<1>(dims),
		std::get<2>(dims),
		std::get<3>(dims)});
}

TensorDescriptor ConvolutionDescriptor::GetBackwardOutputTensor(
	const TensorDescriptor& outputTensorDesc,
	const TensorDescriptor& filterDesc) const
{
	auto dims = this->GetBackwardOutputDim(outputTensorDesc, filterDesc);
	return TensorDescriptor(outputTensorDesc.GetType(), {
		std::get<0>(dims),
		std::get<1>(dims),
		std::get<2>(dims),
		std::get<3>(dims)});
}

TensorDescriptor ConvolutionDescriptor::GetBackwardWeightsTensor(
	const TensorDescriptor& inputTensorDesc,
	const TensorDescriptor& outputTensorDesc) const
{
	auto dims = this->GetBackwardsWeightsDim(inputTensorDesc, outputTensorDesc);
	return TensorDescriptor(outputTensorDesc.GetType(), {
		std::get<0>(dims),
		std::get<1>(dims),
		std::get<2>(dims),
		std::get<3>(dims)});
}

size_t ConvolutionDescriptor::BackwardDataGetWorkSpaceSizeGEMM(
	Handle&                     handle,
	const TensorDescriptor&     wDesc,
	const TensorDescriptor&		dyDesc) const
{
	int out_h, out_w;
	std::tie(std::ignore, std::ignore, out_h, out_w) = miopen::tie4(dyDesc.GetLengths());
	int wei_c, wei_h, wei_w;
	std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(wDesc.GetLengths());
	size_t gemm_size = wei_c*wei_h*wei_w * out_h*out_w * sizeof(dyDesc.GetType());

	// gfx803 devices have limited memory
	// TODO: be graceful, need to ensure we can execute a config on the GPU
	// what if both the algos require > (1 << 30) memory
	if (handle.GetDeviceName() == "gfx803" && gemm_size > (1 << 30))
		gemm_size = 0;

	return (wei_h == 1 && wei_w == 1 && v == 1 && u == 1) ? 0 : gemm_size;

}

size_t ConvolutionDescriptor::BackwardWeightsGetWorkSpaceSizeGEMM(
    Handle&                     handle,
    const TensorDescriptor&     dyDesc,
	const TensorDescriptor&		dwDesc) const
{
    int out_h, out_w;
    std::tie(std::ignore, std::ignore, out_h, out_w) = miopen::tie4(dyDesc.GetLengths());
    int wei_c, wei_h, wei_w;
    std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(dwDesc.GetLengths());
    size_t gemm_size = wei_c*wei_h*wei_w * out_h*out_w * sizeof(dyDesc.GetType());

    // gfx803 devices have limited memory
    // TODO: be graceful, need to ensure we can execute a config on the GPU
    // what if both the algos require > (1 << 30) memory
    if(handle.GetDeviceName() == "gfx803" && gemm_size > (1 << 30))
        gemm_size = 0;

    return gemm_size;
}

size_t ConvolutionDescriptor::BackwardWeightsGetWorkSpaceSizeDirect(
    Handle&                     handle,
    const TensorDescriptor&     dyDesc,
    const TensorDescriptor&     xDesc,
    const TensorDescriptor&     dwDesc) const
{
    mlo_construct_BwdWrW2D construct_params(0); // backward with regards to weights
    construct_params.doSearch(false);
    construct_params.setStream(&handle);
    construct_params.setOutputDescFromMLDesc(dyDesc);
    construct_params.setInputDescFromMLDesc(xDesc);
    construct_params.setWeightDescFromMLDesc(dwDesc);
    construct_params.setConvDescr(pad_h, pad_w, u, v, dilation_h, dilation_w);
    construct_params.mloConstruct();

    return construct_params.getWorkSpaceSzBytes();
}

size_t ConvolutionDescriptor::ConvolutionBackwardWeightsGetWorkSpaceSize(
    Handle&                     handle,
    const TensorDescriptor&      dyDesc,
	const TensorDescriptor&		 xDesc,
	const TensorDescriptor&		 dwDesc) const
{
    return std::max(
            BackwardWeightsGetWorkSpaceSizeDirect(handle, dyDesc, xDesc, dwDesc),
            BackwardWeightsGetWorkSpaceSizeGEMM(handle, dyDesc, dwDesc)
        );
}
std::ostream& operator<< (std::ostream& stream, const ConvolutionDescriptor& c)
{
	stream << c.pad_h << ", ";
	stream << c.pad_w << ", ";
	stream << c.u << ", ";
	stream << c.v << ", ";
	stream << c.dilation_h << ", ";
	stream << c.dilation_w << ", ";
	return stream;
}

} // namespace miopen
<|endoftext|>


<commit_before>#include "core/Genome.hpp"
#include "core/genes/Gene.t.hpp"
#include "core/FakeGenome.hpp"
#include "core/Locus.hpp"
#include "loci/PopulationLocus.hpp"
#include "loci/FakePopulationLocus.hpp"
#include "exception/ValueOutOfRangeException.hpp"
#include "exception/ComponentNotPresentException.hpp"
#include <cmath>
#include <sstream>

using namespace std;

Genome::Genome(std::vector<Locus*> loci, std::string speciesNode) {
	this->speciesNode = speciesNode;
	this->generateRandomGenes(loci);
}

Genome::Genome(
	std::vector<double> genes,
	std::vector<Locus*> loci,
	std::string speciesNode
) {
	std::vector<Gene*> completeGenes;
	for (unsigned int i = 0; i < genes.size(); i++)
		completeGenes.push_back(loci[i]->getGene(genes[i]));
	this->genes = completeGenes;
	this->speciesNode = speciesNode;
}

Genome::Genome(std::vector<Gene*> genes, std::string speciesNode) {
	this->genes = genes;
	this->speciesNode = speciesNode;
}

Genome::Genome(GenomeTemplate geneTemplate, std::string speciesNode) {
	this->setGenes(geneTemplate.getGenes());
	this->speciesNode = speciesNode;
}

Genome::Genome(Genome* other) {
	this->setGenes(other->getGenome());
	this->speciesNode = other->getSpeciesNode();
}

Genome::Genome(Genome* other, bool randomize) {
	this->speciesNode = other->getSpeciesNode();
	if (randomize) {
		this->generateRandomGenes(other->getLoci());
	} else {
		this->setGenes(other->getGenome());
	}
}

Genome::~Genome() {
	for (unsigned int i = 0; i < this->genes.size(); i++)
		delete(this->genes[i]);
}

void Genome::setGenes(std::vector<Gene*> genes) {
	this->genes.clear();
	for (unsigned int i = 0; i < genes.size(); i++)
		this->genes.push_back(genes[i]->copy());
}

void Genome::generateRandomGenes(std::vector<Locus*> loci) {
	this->clearGenome();
	for (unsigned int i = 0; i < loci.size(); i++)
		this->genes.push_back(loci[i]->getGene());
}

void Genome::clearGenome() {
	for (unsigned int i = 0; i < this->genes.size(); i++)
		delete(this->genes[i]);
}

std::vector<Gene*> Genome::getGenome() {
	return this->genes;
}

unsigned int Genome::genomeLength() {
	return this->genes.size();
}

std::vector<Locus*> Genome::getLoci() {
	std::vector<Locus*> loci;
	for (unsigned int i = 0; i < this->genes.size(); i++)
		loci.push_back(this->genes[i]->getLocus());
	return loci;
}

std::string Genome::getSpeciesNode() {
	return this->speciesNode;
}

double Genome::difference(Genome* otherGenome) {
	std::vector<Gene*> otherGenes = otherGenome->getGenome();
	double difference = 0;
	unsigned int shorterGenome = fmin(
		this->genes.size(),
		otherGenes.size()
	);
	unsigned int longerGenome = fmax(
		this->genes.size(),
		otherGenes.size()
	);

	for (unsigned int i = 0; i < shorterGenome; i++)
		difference += std::abs(
			this->genes[i]->getIndex() - otherGenes[i]->getIndex()
		);

	// We want to account for genes of different lengths somehow
	if (longerGenome != shorterGenome)
		difference += longerGenome - shorterGenome;

	return difference;
}

std::string Genome::flatten() {
	stringstream ss;

	for (unsigned int i = 0; i < this->genes.size(); i++)
		ss << this->genes[i]->flatten() << " ";

	return ss.str();
}

Genome Genome::flattenGenome(Genome* target, bool exclude) {
	std::vector<Gene*> rawGenome;

	for (unsigned int i = 0; i < this->genomeLength(); i++) {
		Gene* temp = this->genes[i];
		if (!temp->isConstructive()) {
			rawGenome.push_back(this->genes[i]->copy());
		} else {
			Genome* tempGenome = temp->getValue<Genome*>();

			if (tempGenome == target) {
				if (!exclude)
					rawGenome.push_back(
						this->genes[i]->copy()
					);
			} else {
				std::vector<Gene*> tempGenes =
					tempGenome->flattenGenome().getGenome();

				for (
					unsigned int k = 0;
					k < tempGenes.size();
					k++
				) rawGenome.push_back(tempGenes[k]->copy());
			}
		}
	}

	return Genome(rawGenome, this->speciesNode);
}

Genome Genome::flattenGenome() {
	return this->flattenGenome(NULL, false);
}

Genome Genome::flattenExceptFor(Genome* target) {
	return this->flattenGenome(target, false);
}

Genome Genome::flattenWithout(Genome* target) {
	return this->flattenGenome(target, true);
}

Genome* Genome::replaceComponent(Genome* target) {
	std::vector<Gene*> newGenes;
	for (unsigned int i = 0; i < this->genes.size(); i++) {
		if (this->genes[i]->isConstructive()) {
			PopulationLocus* temp =
				(PopulationLocus*)this->genes[i]->getLocus();

			if (temp->usesSpecies(target)) {
				newGenes.push_back((new FakePopulationLocus(
					target,
					temp,
					false
				))->getGene());
			} else {
				Genome* replaced = this->getIndex<Genome*>(i)
					->replaceComponent(target);
				newGenes.push_back((new FakePopulationLocus(
					replaced,
					temp,
					true
				))->getGene());
				delete(replaced);
			}
		} else {
			newGenes.push_back(this->genes[i]->copy());
		}
	}
	return new FakeGenome(newGenes, this->speciesNode);
}

std::vector<unsigned int> Genome::getFlattenedIndices(
	Genome* target,
	std::function<bool(Genome*, Genome*)> compare
) {
	std::vector<unsigned int> indices;
	unsigned int currentIndex = 0;

	for (unsigned int i = 0; i < this->genes.size(); i++) {
		if (this->genes[i]->isConstructive()) {
			Genome* temp = this->genes[i]->getValue<Genome*>();
			if (compare(target, temp)) {
				indices.push_back(currentIndex);
			} else {
				std::vector<unsigned int> componentIndices =
					temp->getFlattenedIndices(target);

				for (
					unsigned int k = 0;
					k < componentIndices.size();
					k++
				) {
					indices.push_back(
						componentIndices[k]
							+ currentIndex
					);
				}
			}
			currentIndex += temp->flattenedGenomeLength();
		} else {
			currentIndex++;
		}
	}

	return indices;
}

std::vector<unsigned int> Genome::getFlattenedIndices(Genome* target) {
	return this->getFlattenedIndices(
		target,
		[] (Genome* target, Genome* compare) -> bool {
			return target == compare;
		}
	);
}

std::vector<unsigned int> Genome::getFlattenedSpeciesIndices(Genome* target) {
	return this->getFlattenedIndices(
		target,
		[] (Genome* target, Genome* compare) -> bool {
			return target->getSpeciesNode()
				== compare->getSpeciesNode();
		}
	);
}

unsigned int Genome::flattenedGenomeLength() {
	return this->flattenGenome().genomeLength();
}

bool Genome::isSameSpecies(Genome* target) {
	return this->speciesNode == target->getSpeciesNode();
}

bool Genome::usesComponent(Genome* component) {
	for (unsigned int i = 0; i < this->genes.size(); i++) {
		if (this->genes[i]->isConstructive()) {
			Genome* temp = this->genes[i]->getValue<Genome*>();

			if (
				temp == component
				|| temp->usesComponent(component)
			) return true;
		}
	}

	return false;
}

std::set<Locus*> Genome::getConstructiveLoci() {
	std::set<Locus*> constructiveLoci;
	for (unsigned int i = 0; i < this->genes.size(); i++)
		if (this->genes[i]->isConstructive())
			constructiveLoci.insert(this->genes[i]->getLocus());

	return constructiveLoci;
}

GenomeTemplate Genome::getTemplate() {
	return GenomeTemplate(this->genes);
}
<commit_msg>[Genome]: Slight refactor<commit_after>#include "core/Genome.hpp"
#include "core/genes/Gene.t.hpp"
#include "core/FakeGenome.hpp"
#include "core/Locus.hpp"
#include "loci/PopulationLocus.hpp"
#include "loci/FakePopulationLocus.hpp"
#include "exception/ValueOutOfRangeException.hpp"
#include "exception/ComponentNotPresentException.hpp"
#include <cmath>
#include <sstream>

using namespace std;

Genome::Genome(std::vector<Locus*> loci, std::string speciesNode) {
	this->speciesNode = speciesNode;
	this->generateRandomGenes(loci);
}

Genome::Genome(
	std::vector<double> genes,
	std::vector<Locus*> loci,
	std::string speciesNode
) {
	std::vector<Gene*> completeGenes;
	for (unsigned int i = 0; i < genes.size(); i++)
		completeGenes.push_back(loci[i]->getGene(genes[i]));
	this->genes = completeGenes;
	this->speciesNode = speciesNode;
}

Genome::Genome(std::vector<Gene*> genes, std::string speciesNode) {
	this->genes = genes;
	this->speciesNode = speciesNode;
}

Genome::Genome(GenomeTemplate geneTemplate, std::string speciesNode) {
	this->setGenes(geneTemplate.getGenes());
	this->speciesNode = speciesNode;
}

Genome::Genome(Genome* other) {
	this->setGenes(other->getGenome());
	this->speciesNode = other->getSpeciesNode();
}

Genome::Genome(Genome* other, bool randomize) {
	this->speciesNode = other->getSpeciesNode();
	if (randomize) {
		this->generateRandomGenes(other->getLoci());
	} else {
		this->setGenes(other->getGenome());
	}
}

Genome::~Genome() {
	for (unsigned int i = 0; i < this->genes.size(); i++)
		delete(this->genes[i]);
}

void Genome::setGenes(std::vector<Gene*> genes) {
	this->genes.clear();
	for (unsigned int i = 0; i < genes.size(); i++)
		this->genes.push_back(genes[i]->copy());
}

void Genome::generateRandomGenes(std::vector<Locus*> loci) {
	this->clearGenome();
	for (unsigned int i = 0; i < loci.size(); i++)
		this->genes.push_back(loci[i]->getGene());
}

void Genome::clearGenome() {
	for (unsigned int i = 0; i < this->genes.size(); i++)
		delete(this->genes[i]);
}

std::vector<Gene*> Genome::getGenome() {
	return this->genes;
}

unsigned int Genome::genomeLength() {
	return this->genes.size();
}

std::vector<Locus*> Genome::getLoci() {
	std::vector<Locus*> loci;
	for (unsigned int i = 0; i < this->genes.size(); i++)
		loci.push_back(this->genes[i]->getLocus());
	return loci;
}

std::string Genome::getSpeciesNode() {
	return this->speciesNode;
}

double Genome::difference(Genome* otherGenome) {
	std::vector<Gene*> otherGenes = otherGenome->getGenome();
	double difference = 0;
	unsigned int shorterGenome = fmin(
		this->genes.size(),
		otherGenes.size()
	);
	unsigned int longerGenome = fmax(
		this->genes.size(),
		otherGenes.size()
	);

	for (unsigned int i = 0; i < shorterGenome; i++)
		difference += std::abs(
			this->genes[i]->getIndex() - otherGenes[i]->getIndex()
		);

	// We want to account for genes of different lengths somehow
	if (longerGenome != shorterGenome)
		difference += longerGenome - shorterGenome;

	return difference;
}

std::string Genome::flatten() {
	stringstream ss;

	for (unsigned int i = 0; i < this->genes.size(); i++)
		ss << this->genes[i]->flatten() << " ";

	return ss.str();
}

Genome Genome::flattenGenome(Genome* target, bool exclude) {
	std::vector<Gene*> rawGenome;

	for (unsigned int i = 0; i < this->genomeLength(); i++) {
		Gene* temp = this->genes[i];
		if (!temp->isConstructive()) {
			rawGenome.push_back(temp->copy());
		} else {
			Genome* tempGenome = temp->getValue<Genome*>();

			if (tempGenome == target) {
				if (!exclude) rawGenome.push_back(temp->copy());
			} else {
				std::vector<Gene*> tempGenes =
					tempGenome->flattenGenome().getGenome();

				for (
					unsigned int k = 0;
					k < tempGenes.size();
					k++
				) rawGenome.push_back(tempGenes[k]->copy());
			}
		}
	}

	return Genome(rawGenome, this->speciesNode);
}

Genome Genome::flattenGenome() {
	return this->flattenGenome(NULL, false);
}

Genome Genome::flattenExceptFor(Genome* target) {
	return this->flattenGenome(target, false);
}

Genome Genome::flattenWithout(Genome* target) {
	return this->flattenGenome(target, true);
}

Genome* Genome::replaceComponent(Genome* target) {
	std::vector<Gene*> newGenes;
	for (unsigned int i = 0; i < this->genes.size(); i++) {
		if (this->genes[i]->isConstructive()) {
			PopulationLocus* temp =
				(PopulationLocus*)this->genes[i]->getLocus();

			if (temp->usesSpecies(target)) {
				newGenes.push_back((new FakePopulationLocus(
					target,
					temp,
					false
				))->getGene());
			} else {
				Genome* replaced = this->getIndex<Genome*>(i)
					->replaceComponent(target);
				newGenes.push_back((new FakePopulationLocus(
					replaced,
					temp,
					true
				))->getGene());
				delete(replaced);
			}
		} else {
			newGenes.push_back(this->genes[i]->copy());
		}
	}
	return new FakeGenome(newGenes, this->speciesNode);
}

std::vector<unsigned int> Genome::getFlattenedIndices(
	Genome* target,
	std::function<bool(Genome*, Genome*)> compare
) {
	std::vector<unsigned int> indices;
	unsigned int currentIndex = 0;

	for (unsigned int i = 0; i < this->genes.size(); i++) {
		if (this->genes[i]->isConstructive()) {
			Genome* temp = this->genes[i]->getValue<Genome*>();
			if (compare(target, temp)) {
				indices.push_back(currentIndex);
			} else {
				std::vector<unsigned int> componentIndices =
					temp->getFlattenedIndices(target);

				for (
					unsigned int k = 0;
					k < componentIndices.size();
					k++
				) {
					indices.push_back(
						componentIndices[k]
							+ currentIndex
					);
				}
			}
			currentIndex += temp->flattenedGenomeLength();
		} else {
			currentIndex++;
		}
	}

	return indices;
}

std::vector<unsigned int> Genome::getFlattenedIndices(Genome* target) {
	return this->getFlattenedIndices(
		target,
		[] (Genome* target, Genome* compare) -> bool {
			return target == compare;
		}
	);
}

std::vector<unsigned int> Genome::getFlattenedSpeciesIndices(Genome* target) {
	return this->getFlattenedIndices(
		target,
		[] (Genome* target, Genome* compare) -> bool {
			return target->getSpeciesNode()
				== compare->getSpeciesNode();
		}
	);
}

unsigned int Genome::flattenedGenomeLength() {
	return this->flattenGenome().genomeLength();
}

bool Genome::isSameSpecies(Genome* target) {
	return this->speciesNode == target->getSpeciesNode();
}

bool Genome::usesComponent(Genome* component) {
	for (unsigned int i = 0; i < this->genes.size(); i++) {
		if (this->genes[i]->isConstructive()) {
			Genome* temp = this->genes[i]->getValue<Genome*>();

			if (
				temp == component
				|| temp->usesComponent(component)
			) return true;
		}
	}

	return false;
}

std::set<Locus*> Genome::getConstructiveLoci() {
	std::set<Locus*> constructiveLoci;
	for (unsigned int i = 0; i < this->genes.size(); i++)
		if (this->genes[i]->isConstructive())
			constructiveLoci.insert(this->genes[i]->getLocus());

	return constructiveLoci;
}

GenomeTemplate Genome::getTemplate() {
	return GenomeTemplate(this->genes);
}
<|endoftext|>


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

  Program:   NeuroLib (DTI command line tools)
  Language:  C++
  Date:      $Date: 2009/01/09 15:39:51 $
  Version:   $Revision: 1.3 $
  Author:    Casey Goodlett (gcasey@sci.utah.edu)

  Copyright (c)  Casey Goodlett. All rights reserved.
  See NeuroLibCopyright.txt or http://www.ia.unc.edu/dev/Copyright.htm for details.

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

=========================================================================*/
// STL includes
#include <string>
#include <iostream>
#include <numeric>
#include <set>
#include <vector>

// ITK includes
#include <itkVersion.h>
#include <itkIndex.h>
#include "fiberio.h"
#include "dtitypes.h"
#include "pomacros.h"
#include "fiberstatsCLP.h"

int main(int argc, char* argv[])
{
  PARSE_ARGS;
  // End option reading configuration
  const bool         VERBOSE = verbose;
  GroupType::Pointer group = readFiberFile(fiberFile);

  verboseMessage("Getting spacing");

  // Get Spacing and offset from group
  const double* spacing = group->GetSpacing();

  typedef itk::Index<3>                              IndexType;
  typedef itk::Functor::IndexLexicographicCompare<3> IndexCompare;
  typedef std::set<IndexType, IndexCompare>          VoxelSet;
  typedef std::list<float>                           MeasureSample;
  typedef std::map<std::string, MeasureSample>       SampleMap;

  VoxelSet  seenvoxels;
  SampleMap bundlestats;
  bundlestats["fa"] = MeasureSample();
  bundlestats["md"] = MeasureSample();
  bundlestats["fro"] = MeasureSample();

  // For each fiber
  std::vector<double> FiberLengthsVector;
  ChildrenListType*          children = group->GetChildren(0);
  ChildrenListType::iterator it;
  for( it = children->begin(); it != children->end(); it++ )
    {
    DTIPointListType pointlist =
      dynamic_cast<DTITubeType *>( (*it).GetPointer() )->GetPoints();
    DTITubeType::Pointer newtube = DTITubeType::New();
    // For each point along the fiber
    double FiberLength=0;// Added by Adrien Kaiser 04-03-2013
    typedef DTIPointType::PointType PointType;
    PointType Previousp = pointlist.begin()->GetPosition();// Added by Adrien Kaiser 04-03-2013
    for( DTIPointListType::iterator pit = pointlist.begin();
         pit != pointlist.end(); ++pit )
      {
      PointType p = pit->GetPosition();

      // Added by Adrien Kaiser 04-03-2013: Compute length between 2 points
      if(pit != pointlist.begin()) // no previous for the first one
      {
        double length = sqrt( (Previousp[0]-p[0])*(Previousp[0]-p[0]) + (Previousp[1]-p[1])*(Previousp[1]-p[1]) +(Previousp[2]-p[2])*(Previousp[2]-p[2]) );
        FiberLength = FiberLength + length;
      }
      Previousp = p;
      //

      IndexType i;
      i[0] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[0]) );
      i[1] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[1]) );
      i[2] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[2]) );

      seenvoxels.insert(i);

      typedef DTIPointType::FieldListType FieldList;
      const FieldList & fl = pit->GetFields();
      for( FieldList::const_iterator flit = fl.begin();
           flit != fl.end(); ++flit )
        {
        if( bundlestats.count(flit->first) )
          {
          bundlestats[flit->first].push_back(flit->second);
          }
        }

      } // end point loop
    FiberLengthsVector.push_back(FiberLength);// Added by Adrien Kaiser 04-03-2013
    }   // end fiber loop

  // Added by Adrien Kaiser 04-03-2013: compute average fiber length and quantiles
  std::cout<< FiberLengthsVector.size() <<" fibers found"<<std::endl;

  if( FiberLengthsVector.empty() )
  {
    std::cout<<"This fiber file is empty. ABORT."<<std::endl;
    return EXIT_FAILURE;
  }

  double AverageFiberLength = 0;
  for(unsigned int AFLVecIter=0; AFLVecIter < FiberLengthsVector.size();AFLVecIter++)
  {
     AverageFiberLength = AverageFiberLength + FiberLengthsVector[AFLVecIter];
  }
  AverageFiberLength = AverageFiberLength / FiberLengthsVector.size();
  std::cout<<"Average Fiber Length: "<<AverageFiberLength<<std::endl;

  sort( FiberLengthsVector.begin(), FiberLengthsVector.end() );
  std::cout<<"Minimum Fiber Length: "<< FiberLengthsVector[0] <<std::endl;
  std::cout<<"Maximum Fiber Length: "<< FiberLengthsVector[FiberLengthsVector.size()-1] <<std::endl;
  std::cout<<"75 percentile Fiber Length: "<< FiberLengthsVector[ (int)(0.75*FiberLengthsVector.size()) ] <<std::endl;
  std::cout<<"90 percentile Fiber Length: "<< FiberLengthsVector[ (int)(0.9*FiberLengthsVector.size()) ] <<std::endl;
  double Average75PercFiberLength = 0;
  for(unsigned int AFLVecIter=(int)(0.75*FiberLengthsVector.size()); AFLVecIter < FiberLengthsVector.size();AFLVecIter++)
  {
     Average75PercFiberLength = Average75PercFiberLength + FiberLengthsVector[AFLVecIter];
  }
  Average75PercFiberLength = Average75PercFiberLength / (FiberLengthsVector.size() - (int)(0.75*FiberLengthsVector.size())) ;
  std::cout<<"Average 75 Percentile Fiber Length: "<<Average75PercFiberLength<<std::endl;
  //

  double voxelsize = spacing[0] * spacing[1] * spacing[2];
  std::cout << "Volume (mm^3): " << seenvoxels.size() * voxelsize << std::endl;
  // std::cout << "Measure statistics" << std::endl;
/*  for( SampleMap::const_iterator smit = bundlestats.begin();
       smit != bundlestats.end(); ++smit )
    {
    const std::string statname = smit->first;

    double mean = std::accumulate(smit->second.begin(), smit->second.end(), 0.0) / smit->second.size();
    std::cout << statname << " mean: " << mean << std::endl;
    double var = 0.0; // = std::accumulate(smit->second.begin(), smit->second.end(), 0.0,
    //                                 (_1 - mean)*(_1 - mean)) / (smit->second.size() - 1);
    for( MeasureSample::const_iterator it2 = smit->second.begin();
         it2 != smit->second.end(); it2++ )
      {
      double minusMean( (*it2) - mean);
      var += (minusMean * minusMean) / (smit->second.size() - 1);
      }
    std::cout << statname << " std: " << std::sqrt(var) << std::endl;
    }
*/
  delete children;
  return EXIT_SUCCESS;
}
<commit_msg>ENH: Conditional code for ITKv5<commit_after>/*=========================================================================

  Program:   NeuroLib (DTI command line tools)
  Language:  C++
  Date:      $Date: 2009/01/09 15:39:51 $
  Version:   $Revision: 1.3 $
  Author:    Casey Goodlett (gcasey@sci.utah.edu)

  Copyright (c)  Casey Goodlett. All rights reserved.
  See NeuroLibCopyright.txt or http://www.ia.unc.edu/dev/Copyright.htm for details.

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

=========================================================================*/
// STL includes
#include <string>
#include <iostream>
#include <numeric>
#include <set>
#include <vector>

// ITK includes
#include <itkVersion.h>
#include <itkIndex.h>
#include "fiberio.h"
#include "dtitypes.h"
#include "pomacros.h"
#include "fiberstatsCLP.h"

#if ITK_VERSION_MAJOR >= 5
#include <itkLexicographicCompare.h>
#endif

int main(int argc, char* argv[])
{
  PARSE_ARGS;
  // End option reading configuration
  const bool         VERBOSE = verbose;
  GroupType::Pointer group = readFiberFile(fiberFile);

  verboseMessage("Getting spacing");

  // Get Spacing and offset from group
  const double* spacing = group->GetSpacing();

  typedef itk::Index<3>                              IndexType;
#if ITK_VERSION_MAJOR >= 5
  typedef itk::Functor::LexicographicCompare<itk::Index<3>, itk::Index<3> > IndexCompare;
#else
  typedef itk::Functor::IndexLexicographicCompare<3> IndexCompare;
#endif
  typedef std::set<IndexType, IndexCompare>          VoxelSet;
  typedef std::list<float>                           MeasureSample;
  typedef std::map<std::string, MeasureSample>       SampleMap;

  VoxelSet  seenvoxels;
  SampleMap bundlestats;
  bundlestats["fa"] = MeasureSample();
  bundlestats["md"] = MeasureSample();
  bundlestats["fro"] = MeasureSample();

  // For each fiber
  std::vector<double> FiberLengthsVector;
  ChildrenListType*          children = group->GetChildren(0);
  ChildrenListType::iterator it;
  for( it = children->begin(); it != children->end(); it++ )
    {
    DTIPointListType pointlist =
      dynamic_cast<DTITubeType *>( (*it).GetPointer() )->GetPoints();
    DTITubeType::Pointer newtube = DTITubeType::New();
    // For each point along the fiber
    double FiberLength=0;// Added by Adrien Kaiser 04-03-2013
    typedef DTIPointType::PointType PointType;
    PointType Previousp = pointlist.begin()->GetPosition();// Added by Adrien Kaiser 04-03-2013
    for( DTIPointListType::iterator pit = pointlist.begin();
         pit != pointlist.end(); ++pit )
      {
      PointType p = pit->GetPosition();

      // Added by Adrien Kaiser 04-03-2013: Compute length between 2 points
      if(pit != pointlist.begin()) // no previous for the first one
      {
        double length = sqrt( (Previousp[0]-p[0])*(Previousp[0]-p[0]) + (Previousp[1]-p[1])*(Previousp[1]-p[1]) +(Previousp[2]-p[2])*(Previousp[2]-p[2]) );
        FiberLength = FiberLength + length;
      }
      Previousp = p;
      //

      IndexType i;
      i[0] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[0]) );
      i[1] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[1]) );
      i[2] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[2]) );

      seenvoxels.insert(i);

      typedef DTIPointType::FieldListType FieldList;
      const FieldList & fl = pit->GetFields();
      for( FieldList::const_iterator flit = fl.begin();
           flit != fl.end(); ++flit )
        {
        if( bundlestats.count(flit->first) )
          {
          bundlestats[flit->first].push_back(flit->second);
          }
        }

      } // end point loop
    FiberLengthsVector.push_back(FiberLength);// Added by Adrien Kaiser 04-03-2013
    }   // end fiber loop

  // Added by Adrien Kaiser 04-03-2013: compute average fiber length and quantiles
  std::cout<< FiberLengthsVector.size() <<" fibers found"<<std::endl;

  if( FiberLengthsVector.empty() )
  {
    std::cout<<"This fiber file is empty. ABORT."<<std::endl;
    return EXIT_FAILURE;
  }

  double AverageFiberLength = 0;
  for(unsigned int AFLVecIter=0; AFLVecIter < FiberLengthsVector.size();AFLVecIter++)
  {
     AverageFiberLength = AverageFiberLength + FiberLengthsVector[AFLVecIter];
  }
  AverageFiberLength = AverageFiberLength / FiberLengthsVector.size();
  std::cout<<"Average Fiber Length: "<<AverageFiberLength<<std::endl;

  sort( FiberLengthsVector.begin(), FiberLengthsVector.end() );
  std::cout<<"Minimum Fiber Length: "<< FiberLengthsVector[0] <<std::endl;
  std::cout<<"Maximum Fiber Length: "<< FiberLengthsVector[FiberLengthsVector.size()-1] <<std::endl;
  std::cout<<"75 percentile Fiber Length: "<< FiberLengthsVector[ (int)(0.75*FiberLengthsVector.size()) ] <<std::endl;
  std::cout<<"90 percentile Fiber Length: "<< FiberLengthsVector[ (int)(0.9*FiberLengthsVector.size()) ] <<std::endl;
  double Average75PercFiberLength = 0;
  for(unsigned int AFLVecIter=(int)(0.75*FiberLengthsVector.size()); AFLVecIter < FiberLengthsVector.size();AFLVecIter++)
  {
     Average75PercFiberLength = Average75PercFiberLength + FiberLengthsVector[AFLVecIter];
  }
  Average75PercFiberLength = Average75PercFiberLength / (FiberLengthsVector.size() - (int)(0.75*FiberLengthsVector.size())) ;
  std::cout<<"Average 75 Percentile Fiber Length: "<<Average75PercFiberLength<<std::endl;
  //

  double voxelsize = spacing[0] * spacing[1] * spacing[2];
  std::cout << "Volume (mm^3): " << seenvoxels.size() * voxelsize << std::endl;
  // std::cout << "Measure statistics" << std::endl;
/*  for( SampleMap::const_iterator smit = bundlestats.begin();
       smit != bundlestats.end(); ++smit )
    {
    const std::string statname = smit->first;

    double mean = std::accumulate(smit->second.begin(), smit->second.end(), 0.0) / smit->second.size();
    std::cout << statname << " mean: " << mean << std::endl;
    double var = 0.0; // = std::accumulate(smit->second.begin(), smit->second.end(), 0.0,
    //                                 (_1 - mean)*(_1 - mean)) / (smit->second.size() - 1);
    for( MeasureSample::const_iterator it2 = smit->second.begin();
         it2 != smit->second.end(); it2++ )
      {
      double minusMean( (*it2) - mean);
      var += (minusMean * minusMean) / (smit->second.size() - 1);
      }
    std::cout << statname << " std: " << std::sqrt(var) << std::endl;
    }
*/
  delete children;
  return EXIT_SUCCESS;
}
<|endoftext|>