<commit_before>#include <vector>
#include <cmath>

#include "ingameelements/character.h"
#include "gamestate.h"
#include "ingameelements/movingentity.h"
#include "player.h"
#include "global_constants.h"
#include "engine.h"
#include "ingameelements/weapon.h"

Character::Character(uint64_t id_, Gamestate *state, EntityPtr owner_, CharacterChildParameters parameters) : MovingEntity(id_, state),
            owner(owner_), weapon(parameters.weapon), pressed_keys(), held_keys()
{
    acceleration = 300;
    runpower = parameters.runpower;
    // friction factor per second of null movement; calculated directly from Gang Garrison 2
    // from pygg2
    friction = 0.01510305449388463132584804061124;
}

Character::~Character()
{
    ;
}

void Character::setinput(Gamestate *state, INPUT_CONTAINER pressed_keys_, INPUT_CONTAINER held_keys_, double mouse_x_, double mouse_y_)
{
    pressed_keys = pressed_keys_;
    held_keys = held_keys_;
    mouse_x = mouse_x_;
    mouse_y = mouse_y_;
    Weapon *w = state->get<Weapon>(weapon);
    w->setaim(mouse_x, mouse_y);
}

void Character::beginstep(Gamestate *state, double frametime)
{
    state->get<Weapon>(weapon)->beginstep(state, frametime);
}

void Character::midstep(Gamestate *state, double frametime)
{
    if (cangetinput(state))
    {
        double maxhspeed;
        if (animstate()->crouchanim.active())
        {
            maxhspeed = 60.0;
        }
        else
        {
            maxhspeed = 153.0;
        }

        if (held_keys.LEFT)
        {
            hspeed = std::max(hspeed - acceleration * runpower * frametime, -maxhspeed);
        }
        if (held_keys.RIGHT)
        {
            hspeed = std::min(hspeed + acceleration * runpower * frametime, maxhspeed);
        }
        if (held_keys.JUMP)
        {
            if (onground(state))
            {
                vspeed = -240.0;
            }
        }
        if (held_keys.CROUCH)
        {
            if (not animstate()->crouchanim.active())
            {
                animstate()->crouchanim.active(true);
                animstate()->crouchanim.reset();
            }
        }
        else if (animstate()->crouchanim.active())
        {
            // We're crouched and we'd like to uncrouch
            // Do so only if we have the room
            if (not state->currentmap->collides(getstandingcollisionrect(state)))
            {
                animstate()->crouchanim.active(false);
            }
        }

        if (held_keys.RELOAD)
        {
            Weapon *w = state->get<Weapon>(weapon);
            w->reload(state, frametime);
        }
        // Shooting
        if (held_keys.PRIMARY_FIRE)
        {
            Weapon *w = state->get<Weapon>(weapon);
            w->fireprimary(state, frametime);
        }
        if (held_keys.SECONDARY_FIRE)
        {
            Weapon *w = state->get<Weapon>(weapon);
            w->firesecondary(state, frametime);
        }

        if (animstate()->isflipped != (mouse_x < 0))
        {
            // Spinjumping (compensate for later gravity)
            vspeed -= 540.0*frametime*3.0/4.0;
            animstate()->isflipped = (mouse_x < 0);
        }
    }

    // Gravity
    vspeed += 540.0*frametime;

    // apply friction
    hspeed *= std::pow(friction, frametime);

    state->get<Weapon>(weapon)->midstep(state, frametime);
}

void Character::endstep(Gamestate *state, double frametime)
{
    MovingEntity::endstep(state, frametime);

    // Collision with wallmask
    if (state->currentmap->collides(getcollisionrect(state)))
    {
        // We collide, do collision handling
        double hs = hspeed*frametime, vs = vspeed*frametime;
        // Buffers for "undone" horizontal/vertical movement
        double xbuffer = 0.0, ybuffer = 0.0;
        int steps = std::ceil(std::fmax(std::abs(hs), std::abs(vs)));
        double xstep = hs/steps, ystep = vs/steps;
        // Pull us out of the wall
        for (int i=0; i<steps; ++i)
        {
            x -= xstep; y -= ystep;
            xbuffer += xstep; ybuffer += ystep;
            if (not state->currentmap->collides(getcollisionrect(state)))
            {
                break;
            }
        }
        // We're at the point where the character touched the wallmask for the first time
        // Now keep moving one unit in either direction until all possible movement is exhausted
        bool xblocked = false, yblocked = false;
        bool xfinished = false, yfinished = false;
        double oldxbuffer = xbuffer, oldybuffer = ybuffer;
        while (not xfinished or not yfinished)
        {
            oldxbuffer = xbuffer; oldybuffer = ybuffer;
            // Try first moving horizontally
            if (not xfinished)
            {
                if (not state->currentmap->collides(getcollisionrect(state).offset(xstep, 0)))
                {
                    x += xstep;
                    xbuffer -= xstep;
                    if (xbuffer == 0.0 or std::signbit(xbuffer) != std::signbit(oldxbuffer))
                    {
                        // We're done for this coordinate
                        xfinished = true;
                    }
                }
                else
                {
                    // There's the possibility we might have walked into a staircase
                    if (not state->currentmap->collides(getcollisionrect(state).offset(xstep, STAIRCASE_STEPSIZE)))
                    {
                        // Indeed we did. Move up
                        x += xstep;
                        y += STAIRCASE_STEPSIZE;
                        xbuffer -= xstep;
                        if (xbuffer == 0.0 or std::signbit(xbuffer) != std::signbit(oldxbuffer))
                        {
                            // We're done for this coordinate
                            xfinished = true;
                        }
                    }
                    else
                    {
                        // No more moving, we're blocked
                        xblocked = true;
                        xfinished = true;
                    }
                }
            }
            // Do the same vertically, but without stair code
            if (not yfinished)
            {
                if (not state->currentmap->collides(getcollisionrect(state).offset(0, ystep)))
                {
                    // We cam move through
                    y += ystep;
                    ybuffer -= ystep;
                    if (ybuffer == 0.0 or std::signbit(ybuffer) != std::signbit(oldybuffer))
                    {
                        // We're done for this coordinate
                        yfinished = true;
                    }
                }
                else
                {
                    // No more moving, we're blocked
                    yblocked = true;
                    yfinished = true;
                }
            }
        }
        // Set hspeed and vspeed to what they should be
        if (xblocked)
        {
            hspeed = 0;
        }
        if (yblocked)
        {
            vspeed = 0;
        }
        if (state->currentmap->collides(getcollisionrect(state)))
        {
            printf("\nError: Still in wallmask after collision handling.");
        }
    } // end collision with wallmask

    // Running animation
    if (onground(state))
    {
        if (animstate()->isflipped)
        {
            animstate()->runanim.update(state, -hspeed*frametime);
            animstate()->crouchanim.update(state, -hspeed*frametime);
        }
        else
        {
            animstate()->runanim.update(state, hspeed*frametime);
            animstate()->crouchanim.update(state, hspeed*frametime);
        }
    }
    if (hspeed == 0.0)
    {
        bool run=animstate()->runanim.active(), crouch=animstate()->crouchanim.active();
        animstate()->runanim.reset();
        animstate()->runanim.active(run);
        animstate()->crouchanim.reset();
        animstate()->crouchanim.active(crouch);
    }

    state->get<Weapon>(weapon)->endstep(state, frametime);
}

bool Character::onground(Gamestate *state)
{
    Rect r = getcollisionrect(state);
    return state->currentmap->collides(Rect(r.x, r.y+r.h, r.w, 1));
}

void Character::interpolate(Entity *prev_entity, Entity *next_entity, double alpha)
{
    MovingEntity::interpolate(prev_entity, next_entity, alpha);

    Character *prev_e = static_cast<Character*>(prev_entity);
    Character *next_e = static_cast<Character*>(next_entity);

    if (alpha < 0.5)
    {
        held_keys = prev_e->held_keys;
        pressed_keys = prev_e->pressed_keys;
        animstate()->crouchanim.active(prev_e->animstate()->crouchanim.active());
    }
    else
    {
        held_keys = next_e->held_keys;
        pressed_keys = next_e->pressed_keys;
        animstate()->crouchanim.active(prev_e->animstate()->crouchanim.active());
    }
    mouse_x = prev_e->mouse_x + alpha*(next_e->mouse_x - prev_e->mouse_x);
    mouse_y = prev_e->mouse_y + alpha*(next_e->mouse_y - prev_e->mouse_y);
    animstate()->runanim.interpolate(&(prev_e->animstate()->runanim), &(next_e->animstate()->runanim), alpha);
}
<commit_msg>Added teleport on right click.<commit_after>#include <vector>
#include <cmath>

#include "ingameelements/character.h"
#include "gamestate.h"
#include "ingameelements/movingentity.h"
#include "player.h"
#include "global_constants.h"
#include "engine.h"
#include "ingameelements/weapon.h"

Character::Character(uint64_t id_, Gamestate *state, EntityPtr owner_, CharacterChildParameters parameters) : MovingEntity(id_, state),
            owner(owner_), weapon(parameters.weapon), pressed_keys(), held_keys()
{
    acceleration = 300;
    runpower = parameters.runpower;
    // friction factor per second of null movement; calculated directly from Gang Garrison 2
    // from pygg2
    friction = 0.01510305449388463132584804061124;
}

Character::~Character()
{
    ;
}

void Character::setinput(Gamestate *state, INPUT_CONTAINER pressed_keys_, INPUT_CONTAINER held_keys_, double mouse_x_, double mouse_y_)
{
    pressed_keys = pressed_keys_;
    held_keys = held_keys_;
    mouse_x = mouse_x_;
    mouse_y = mouse_y_;
    Weapon *w = state->get<Weapon>(weapon);
    w->setaim(mouse_x, mouse_y);
}

void Character::beginstep(Gamestate *state, double frametime)
{
    state->get<Weapon>(weapon)->beginstep(state, frametime);
}

void Character::midstep(Gamestate *state, double frametime)
{
    if (cangetinput(state))
    {
        double maxhspeed;
        if (animstate()->crouchanim.active())
        {
            maxhspeed = 60.0;
        }
        else
        {
            maxhspeed = 153.0;
        }

        if (held_keys.LEFT)
        {
            hspeed = std::max(hspeed - acceleration * runpower * frametime, -maxhspeed);
        }
        if (held_keys.RIGHT)
        {
            hspeed = std::min(hspeed + acceleration * runpower * frametime, maxhspeed);
        }
        if (held_keys.JUMP)
        {
            if (onground(state))
            {
                vspeed = -240.0;
            }
        }
        if (held_keys.CROUCH)
        {
            if (not animstate()->crouchanim.active())
            {
                animstate()->crouchanim.active(true);
                animstate()->crouchanim.reset();
            }
        }
        else if (animstate()->crouchanim.active())
        {
            // We're crouched and we'd like to uncrouch
            // Do so only if we have the room
            if (not state->currentmap->collides(getstandingcollisionrect(state)))
            {
                animstate()->crouchanim.active(false);
            }
        }

        if (held_keys.RELOAD)
        {
            Weapon *w = state->get<Weapon>(weapon);
            w->reload(state, frametime);
        }
        // Shooting
        if (held_keys.PRIMARY_FIRE)
        {
            Weapon *w = state->get<Weapon>(weapon);
            w->fireprimary(state, frametime);
        }
        if (held_keys.SECONDARY_FIRE)
        {
            x = mouse_x;
            y = mouse_y;
            Weapon *w = state->get<Weapon>(weapon);
            w->firesecondary(state, frametime);
        }

        if (animstate()->isflipped != (mouse_x < 0))
        {
            // Spinjumping (compensate for later gravity)
            vspeed -= 540.0*frametime*3.0/4.0;
            animstate()->isflipped = (mouse_x < 0);
        }
    }

    // Gravity
    vspeed += 540.0*frametime;

    // apply friction
    hspeed *= std::pow(friction, frametime);

    state->get<Weapon>(weapon)->midstep(state, frametime);
}

void Character::endstep(Gamestate *state, double frametime)
{
    MovingEntity::endstep(state, frametime);

    // Collision with wallmask
    if (state->currentmap->collides(getcollisionrect(state)))
    {
        // We collide, do collision handling
        double hs = hspeed*frametime, vs = vspeed*frametime;
        // Buffers for "undone" horizontal/vertical movement
        double xbuffer = 0.0, ybuffer = 0.0;
        int steps = std::ceil(std::fmax(std::abs(hs), std::abs(vs)));
        double xstep = hs/steps, ystep = vs/steps;
        // Pull us out of the wall
        for (int i=0; i<steps; ++i)
        {
            x -= xstep; y -= ystep;
            xbuffer += xstep; ybuffer += ystep;
            if (not state->currentmap->collides(getcollisionrect(state)))
            {
                break;
            }
        }
        // We're at the point where the character touched the wallmask for the first time
        // Now keep moving one unit in either direction until all possible movement is exhausted
        bool xblocked = false, yblocked = false;
        bool xfinished = false, yfinished = false;
        double oldxbuffer = xbuffer, oldybuffer = ybuffer;
        while (not xfinished or not yfinished)
        {
            oldxbuffer = xbuffer; oldybuffer = ybuffer;
            // Try first moving horizontally
            if (not xfinished)
            {
                if (not state->currentmap->collides(getcollisionrect(state).offset(xstep, 0)))
                {
                    x += xstep;
                    xbuffer -= xstep;
                    if (xbuffer == 0.0 or std::signbit(xbuffer) != std::signbit(oldxbuffer))
                    {
                        // We're done for this coordinate
                        xfinished = true;
                    }
                }
                else
                {
                    // There's the possibility we might have walked into a staircase
                    if (not state->currentmap->collides(getcollisionrect(state).offset(xstep, STAIRCASE_STEPSIZE)))
                    {
                        // Indeed we did. Move up
                        x += xstep;
                        y += STAIRCASE_STEPSIZE;
                        xbuffer -= xstep;
                        if (xbuffer == 0.0 or std::signbit(xbuffer) != std::signbit(oldxbuffer))
                        {
                            // We're done for this coordinate
                            xfinished = true;
                        }
                    }
                    else
                    {
                        // No more moving, we're blocked
                        xblocked = true;
                        xfinished = true;
                    }
                }
            }
            // Do the same vertically, but without stair code
            if (not yfinished)
            {
                if (not state->currentmap->collides(getcollisionrect(state).offset(0, ystep)))
                {
                    // We cam move through
                    y += ystep;
                    ybuffer -= ystep;
                    if (ybuffer == 0.0 or std::signbit(ybuffer) != std::signbit(oldybuffer))
                    {
                        // We're done for this coordinate
                        yfinished = true;
                    }
                }
                else
                {
                    // No more moving, we're blocked
                    yblocked = true;
                    yfinished = true;
                }
            }
        }
        // Set hspeed and vspeed to what they should be
        if (xblocked)
        {
            hspeed = 0;
        }
        if (yblocked)
        {
            vspeed = 0;
        }
        if (state->currentmap->collides(getcollisionrect(state)))
        {
            printf("\nError: Still in wallmask after collision handling.");
        }
    } // end collision with wallmask

    // Running animation
    if (onground(state))
    {
        if (animstate()->isflipped)
        {
            animstate()->runanim.update(state, -hspeed*frametime);
            animstate()->crouchanim.update(state, -hspeed*frametime);
        }
        else
        {
            animstate()->runanim.update(state, hspeed*frametime);
            animstate()->crouchanim.update(state, hspeed*frametime);
        }
    }
    if (hspeed == 0.0)
    {
        bool run=animstate()->runanim.active(), crouch=animstate()->crouchanim.active();
        animstate()->runanim.reset();
        animstate()->runanim.active(run);
        animstate()->crouchanim.reset();
        animstate()->crouchanim.active(crouch);
    }

    state->get<Weapon>(weapon)->endstep(state, frametime);
}

bool Character::onground(Gamestate *state)
{
    Rect r = getcollisionrect(state);
    return state->currentmap->collides(Rect(r.x, r.y+r.h, r.w, 1));
}

void Character::interpolate(Entity *prev_entity, Entity *next_entity, double alpha)
{
    MovingEntity::interpolate(prev_entity, next_entity, alpha);

    Character *prev_e = static_cast<Character*>(prev_entity);
    Character *next_e = static_cast<Character*>(next_entity);

    if (alpha < 0.5)
    {
        held_keys = prev_e->held_keys;
        pressed_keys = prev_e->pressed_keys;
        animstate()->crouchanim.active(prev_e->animstate()->crouchanim.active());
    }
    else
    {
        held_keys = next_e->held_keys;
        pressed_keys = next_e->pressed_keys;
        animstate()->crouchanim.active(prev_e->animstate()->crouchanim.active());
    }
    mouse_x = prev_e->mouse_x + alpha*(next_e->mouse_x - prev_e->mouse_x);
    mouse_y = prev_e->mouse_y + alpha*(next_e->mouse_y - prev_e->mouse_y);
    animstate()->runanim.interpolate(&(prev_e->animstate()->runanim), &(next_e->animstate()->runanim), alpha);
}
<|endoftext|>


<commit_before><commit_msg>Does not sleep after running the last iteration<commit_after><|endoftext|>


<commit_before>#include <iostream>

#include <edlib/EDParams.h>
#include "edlib/Hamiltonian.h"
#include "edlib/SzSymmetry.h"
#include "edlib/SOCRSStorage.h"
#include "edlib/CRSStorage.h"
#include "edlib/HubbardModel.h"
#include "edlib/GreensFunction.h"
#include "edlib/SpinResolvedStorage.h"

int main(int argc, const char ** argv) {
  typedef EDLib::SRSHubbardHamiltonian HamType;
#ifdef USE_MPI
  MPI_Init(&argc, (char ***) &argv);
  alps::mpi::communicator comm;
#endif
  alps::params params(argc, argv);
  if(params.help_requested(std::cout)) {
    exit(0);
  }
  EDLib::define_parameters(params);
//  try {
//  CSRHubbardHamiltonian_float ham(params);
#ifdef USE_MPI
//    EDLib::SRSHubbardHamiltonian ham(params, comm);
    HamType ham(params, comm);
#else
    EDLib::SRSHubbardHamiltonian ham(params);
#endif
    ham.diag();
//  GreensFunction<float, CSRHubbardHamiltonian_float > greensFunction(params, ham);
    EDLib::gf::GreensFunction < double, HamType > greensFunction(params, ham);
    greensFunction.compute();
//    EDLib::CSRSIAMHamiltonian ham2(params);
  /*} catch (std::exception & e) {
#ifdef USE_MPI
    if(comm.rank() == 0) std::cerr<<e.what();
#else
    std::cerr<<e.what();
#endif
  }*/
#ifdef USE_MPI
  MPI_Finalize();
#endif
  return 0;
}
<commit_msg>cleanup<commit_after>#include <iostream>

#include <edlib/EDParams.h>
#include "edlib/Hamiltonian.h"
#include "edlib/SzSymmetry.h"
#include "edlib/SOCRSStorage.h"
#include "edlib/CRSStorage.h"
#include "edlib/HubbardModel.h"
#include "edlib/GreensFunction.h"
#include "edlib/SpinResolvedStorage.h"

int main(int argc, const char ** argv) {
  typedef EDLib::SRSHubbardHamiltonian HamType;
#ifdef USE_MPI
  MPI_Init(&argc, (char ***) &argv);
  alps::mpi::communicator comm;
#endif
  alps::params params(argc, argv);
  if(params.help_requested(std::cout)) {
    exit(0);
  }
  EDLib::define_parameters(params);
  try {
//  CSRHubbardHamiltonian_float ham(params);
#ifdef USE_MPI
//    EDLib::SRSHubbardHamiltonian ham(params, comm);
    HamType ham(params, comm);
#else
    EDLib::SRSHubbardHamiltonian ham(params);
#endif
    ham.diag();
//  GreensFunction<float, CSRHubbardHamiltonian_float > greensFunction(params, ham);
    EDLib::gf::GreensFunction < double, HamType > greensFunction(params, ham);
    greensFunction.compute();
//    EDLib::CSRSIAMHamiltonian ham2(params);
  } catch (std::exception & e) {
#ifdef USE_MPI
    if(comm.rank() == 0) std::cerr<<e.what();
#else
    std::cerr<<e.what();
#endif
  }
#ifdef USE_MPI
  MPI_Finalize();
#endif
  return 0;
}
<|endoftext|>


<commit_before>#include "rbindv.hpp"	//#include "rbind.hpp"
#include <iostream>
#include <string>
#include <type_traits>

struct Func	{
	int operator ()(int a, int& b, int c = 1) const
		{ return a * 10000 + (b *= 100) + c; }
	int memFun(int a, int b, int c = 1) const
		{ return a * 10000 + b * 100 + c; }
};

template <template <typename> class Tr>
struct noref {
    template <typename V>
        struct apply    {
        static constexpr bool value = Tr<typename std::remove_reference<V>::type>::value;
    };
};

int main()
{
	using namespace std::placeholders;
	using namespace mymd::placeholders;
	Func f;
	int a = 2014, b = 2, c = 3, result = 0;
	//----------------------------------------------------------------------------------
	//basic   基本
	auto b1 = mymd::rbind(f, _1, _2, _3);
	result = b1(a, b, c);
	std::cout << "---- basic use" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	auto b1_1 = mymd::rbind(f, until(_3rd));
	result = b1_1(a, b, c);
	std::cout << "---- basic use(placeholders range)" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 10;
	//preset default value     デフォルト値の設定
	auto b2 = mymd::rbind(f, a, _1, _2nd = 11);
	result = b2(b, c);
	std::cout << "---- do not use default value" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	a = 2014, b = 2, c = 10;
	result = b2(b);
	std::cout << "---- use default value for c(=11)" <<std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 4, c = 30;
	//optional argument     引数省略
	auto b3 = mymd::rbind(_1st, 2014, _2nd, _3rd);
	result = b3(Func(), b);
	std::cout << "---- use default value of original functor for c(=1)" << std::endl;
	std::cout << "b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 1;
	std::string str("abcdefg");
	//convert argument by yield method     yieldメソッドによる引数変換
	auto b4 = mymd::rbind(&Func::memFun	,
			    &f			,
			    2014		,
			    _1			,
			    _2nd.yield([](const std::string& s){ return s.length(); })
			    );
	result = b4(b, str);
	std::cout << "---- convert augument by yield for the last argument" << std::endl;
	std::cout << "b = " << b << ", s = " << str << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	//parameter type assert   引数の型の制約
	auto b5 = mymd::rbind(f, _1, _2, _3rd.assert<noref<std::is_integral>>());
	result = b5(a, b=8, c=23);
	std::cout << "---- parameter type assert" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	return 0;
}
<commit_msg>Update main.cpp<commit_after>#include "rbindv.hpp"
#include <iostream>
#include <string>
#include <type_traits>

struct Func	{
	int operator ()(int a, int& b, int c = 1) const
		{ return a * 10000 + (b *= 100) + c; }
	int memFun(int a, int b, int c = 1) const
		{ return a * 10000 + b * 100 + c; }
};

template <template <typename> class Tr>
struct noref {
    template <typename V>
        struct apply    {
        static constexpr bool value = Tr<typename std::remove_reference<V>::type>::value;
    };
};

int main()
{
	using namespace std::placeholders;
	using namespace mymd::placeholders;
	Func f;
	int a = 2014, b = 2, c = 3, result = 0;
	//----------------------------------------------------------------------------------
	//basic   基本
	auto b1 = mymd::rbind(f, _1, _2, _3);
	result = b1(a, b, c);
	std::cout << "---- basic use" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	auto b1_1 = mymd::rbind(f, until(_3rd));
	result = b1_1(a, b, c);
	std::cout << "---- basic use(placeholders range)" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 10;
	//preset default value     デフォルト値の設定
	auto b2 = mymd::rbind(f, a, _1, _2nd = 11);
	result = b2(b, c);
	std::cout << "---- do not use default value" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	a = 2014, b = 2, c = 10;
	result = b2(b);
	std::cout << "---- use default value for c(=11)" <<std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 4, c = 30;
	//optional argument     引数省略
	auto b3 = mymd::rbind(_1st, 2014, _2nd, _3rd);
	result = b3(Func(), b);
	std::cout << "---- use default value of original functor for c(=1)" << std::endl;
	std::cout << "b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 1;
	std::string str("abcdefg");
	//convert argument by yield method     yieldメソッドによる引数変換
	auto b4 = mymd::rbind(&Func::memFun	,
			    &f			,
			    2014		,
			    _1			,
			    _2nd.yield([](const std::string& s){ return s.length(); })
			    );
	result = b4(b, str);
	std::cout << "---- convert augument by yield for the last argument" << std::endl;
	std::cout << "b = " << b << ", s = " << str << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	//parameter type assert   引数の型の制約
	auto b5 = mymd::rbind(f, _1, _2, _3rd.assert<noref<std::is_integral>>());
	result = b5(a, b=8, c=23);
	std::cout << "---- parameter type assert" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	//make nested dependent functor by operator*
    	char s6[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    	auto b6 = mymd::rbind(std::plus<std::string>{},
        	                  *mymd::emplace<std::string>(s6, _1),
                	          *mymd::emplace<std::string>(_2, _3));
	std::cout << "---- nested dependent rbind" << std::endl;
	std::cout << b6(4, s6+20, s6+26) << std::endl;	return 0;
}
<|endoftext|>


<commit_before>e2de6cb5-4b02-11e5-9227-28cfe9171a43<commit_msg>more fixes<commit_after>e2e98a40-4b02-11e5-9359-28cfe9171a43<|endoftext|>


<commit_before>/*
 * compile both driver code and kernel code with nvcc, as in:
 * 			nvcc simple.c simple.cu
 */
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <iostream>

// The function fillArray is in the file simple.cu
extern void gpu_dotProduct(int *distance_array, int *force_array,
                           int *result_array, int num_vectors);

void gen_force_array(int *force, int num_vectors) {
  int i, j, half_vectors;
  half_vectors = num_vectors / 2;
  // go up
  for (i = 0; i < half_vectors; i++) {
    force[i] = i + 1;
  }

  // walk backwards with array, forward counting
  i = 1;
  for (j = num_vectors; j > half_vectors; j--) {
    force[j - 1] = i;
    i++;
  }

  return;
}

void gen_distance_array(int *distance, int num_vectors) {
  int i = 0, j = 1;
  for (i = 0; i < num_vectors; i++) {
    distance[i] = j;
    j++;
    if (j > 10) {
      j = 1;
    }
  }
  return;
}

int main(int argc, char *argv[]) {
  int num_vectors = 0, half_vectors, i, j, s_dotproduct = 0,
      pu_dotproduct_result = 0, temp;
  if (argc < 2) {
    std::cout << "Usage: cuda-musclework num_vectors" << std::endl;
  }
  num_vectors = atoi(argv[1]);
  std::cout << "Using num_vectors: " << num_vectors << std::endl;
  int *distance = (int *)malloc(num_vectors * sizeof(int));
  int *force = (int *)malloc(num_vectors * sizeof(int));
  int *result = (int *)malloc(num_vectors * sizeof(int));

  gen_distance_array(distance, num_vectors);
  gen_force_array(force, num_vectors);

  // Call the function that will call the GPU function
  gpu_dotProduct(distance, force, result, num_vectors);

  for (i = 0; i < num_vectors; i++) {
    pu_dotproduct_result = pu_dotproduct_result + result[i];
  }

  std::cout << "GPU Calc Total: " << pu_dotproduct_result << std::endl;

  return 0;
}
<commit_msg>try c linkage<commit_after>/*
 * compile both driver code and kernel code with nvcc, as in:
 * 			nvcc simple.c simple.cu
 */
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <iostream>

// The function fillArray is in the file simple.cu
extern "C" void gpu_dotProduct(int *distance_array, int *force_array,
                               int *result_array, int num_vectors);

void gen_force_array(int *force, int num_vectors) {
  int i, j, half_vectors;
  half_vectors = num_vectors / 2;
  // go up
  for (i = 0; i < half_vectors; i++) {
    force[i] = i + 1;
  }

  // walk backwards with array, forward counting
  i = 1;
  for (j = num_vectors; j > half_vectors; j--) {
    force[j - 1] = i;
    i++;
  }

  return;
}

void gen_distance_array(int *distance, int num_vectors) {
  int i = 0, j = 1;
  for (i = 0; i < num_vectors; i++) {
    distance[i] = j;
    j++;
    if (j > 10) {
      j = 1;
    }
  }
  return;
}

int main(int argc, char *argv[]) {
  int num_vectors = 0, half_vectors, i, j, s_dotproduct = 0,
      pu_dotproduct_result = 0, temp;
  if (argc < 2) {
    std::cout << "Usage: cuda-musclework num_vectors" << std::endl;
  }
  num_vectors = atoi(argv[1]);
  std::cout << "Using num_vectors: " << num_vectors << std::endl;
  int *distance = (int *)malloc(num_vectors * sizeof(int));
  int *force = (int *)malloc(num_vectors * sizeof(int));
  int *result = (int *)malloc(num_vectors * sizeof(int));

  gen_distance_array(distance, num_vectors);
  gen_force_array(force, num_vectors);

  // Call the function that will call the GPU function
  gpu_dotProduct(distance, force, result, num_vectors);

  for (i = 0; i < num_vectors; i++) {
    pu_dotproduct_result = pu_dotproduct_result + result[i];
  }

  std::cout << "GPU Calc Total: " << pu_dotproduct_result << std::endl;

  return 0;
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    FEMImageRegLMEx.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for detail.

     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.

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

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif
#include <fstream>

#include "FEMImageRegLMEx.h"

// Below, we have typedefs that instantiate all necessary classes.
// Here, we instantiate the image type, load type and
// explicitly template the load implementation type.

#define TWOD
//#define THREED
#ifdef TWOD
typedef itk::Image< unsigned char, 2 >                     fileImageType;
typedef itk::Image< float, 2 >                     ImageType;
// We now declare an element type and load implementation pointer for the visitor class.
typedef itk::fem::Element2DC0LinearTriangularMembrane   ElementType2;
typedef itk::fem::Element2DC0LinearQuadrilateralMembrane   ElementType;
#endif
#ifdef THREED
typedef itk::Image< unsigned char, 3 >                     fileImageType;
typedef itk::Image< float, 3 >                     ImageType;
typedef itk::fem::Element3DC0LinearHexahedronMembrane   ElementType;
typedef itk::fem::Element3DC0LinearTetrahedronMembrane   ElementType2;
#endif
typedef itk::fem::ImageMetricLoad<ImageType,ImageType>     ImageLoadType;
template class itk::fem::ImageMetricLoadImplementation<ImageLoadType>;
typedef ElementType::LoadImplementationFunctionPointer     LoadImpFP;
typedef ElementType::LoadType                              ElementLoadType;
typedef ElementType2::LoadImplementationFunctionPointer     LoadImpFP2;
typedef ElementType2::LoadType                              ElementLoadType2;
typedef itk::fem::VisitorDispatcher<ElementType,ElementLoadType, LoadImpFP>
                                                          DispatcherType;
typedef itk::fem::VisitorDispatcher<ElementType2,ElementLoadType2, LoadImpFP2>
                                                          DispatcherType2;

typedef itk::fem::FEMRegistrationFilter<ImageType,ImageType> RegistrationType;

void ReadRawImageFiles( RegistrationType* X)
{

  typedef  itk::ImageFileReader< fileImageType >      FileSourceType;
  typedef  fileImageType::PixelType PixType;
  const unsigned int ImageDimension=fileImageType::ImageDimension;
  typedef  itk::RawImageIO< PixType,ImageDimension>   RawReaderType;

  FileSourceType::Pointer reffilter = FileSourceType::New();
  reffilter->SetFileName( (X->GetReferenceFile()).c_str() );
  FileSourceType::Pointer tarfilter = FileSourceType::New();
  tarfilter->SetFileName( (X->GetTargetFile()).c_str() );

  RawReaderType::Pointer  rawReader  = RawReaderType::New();
  rawReader->SetFileDimensionality( ImageDimension );

  ImageType::SizeType ImageSize=X->GetImageSize();
  for (unsigned int ii=0; ii<ImageDimension; ii++)
  {
    unsigned int temp=(unsigned int) ImageSize[ii];
    rawReader->SetDimensions( ii, temp );
  }
  reffilter->SetImageIO( rawReader );
  tarfilter->SetImageIO( rawReader );

  try
    {
    reffilter->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << "Exception caught during reference file reading " << std::endl;
    std::cerr << e << std::endl;
    return ;
    }
  try
    {
    tarfilter->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << "Exception caught during target file reading " << std::endl;
    std::cerr << e << std::endl;
    return ;
    }

  typedef itk::RescaleIntensityImageFilter<fileImageType,ImageType> FilterType;
  FilterType::Pointer refrescalefilter = FilterType::New();
  FilterType::Pointer tarrescalefilter = FilterType::New();

  refrescalefilter->SetInput(reffilter->GetOutput());
  tarrescalefilter->SetInput(tarfilter->GetOutput());

  const double desiredMinimum =  0.0;
  const double desiredMaximum =  255.0;

  refrescalefilter->SetOutputMinimum( desiredMinimum );
  refrescalefilter->SetOutputMaximum( desiredMaximum );
  refrescalefilter->UpdateLargestPossibleRegion();
  tarrescalefilter->SetOutputMinimum( desiredMinimum );
  tarrescalefilter->SetOutputMaximum( desiredMaximum );
  tarrescalefilter->UpdateLargestPossibleRegion();

  typedef itk::HistogramMatchingImageFilter<ImageType,ImageType> HEFilterType;
  HEFilterType::Pointer IntensityEqualizeFilter = HEFilterType::New();

  IntensityEqualizeFilter->SetReferenceImage( refrescalefilter->GetOutput() );
  IntensityEqualizeFilter->SetInput( tarrescalefilter->GetOutput() );
  IntensityEqualizeFilter->SetNumberOfHistogramLevels( 100);
  IntensityEqualizeFilter->SetNumberOfMatchPoints( 15);
  IntensityEqualizeFilter->ThresholdAtMeanIntensityOn();
  IntensityEqualizeFilter->Update();

  X->SetReferenceImage(refrescalefilter->GetOutput());
  X->SetTargetImage(IntensityEqualizeFilter->GetOutput()/*tarrescalefilter->GetOutput()*/);
//  X->SetReferenceImage(reffilter->GetOutput());
//  X->SetTargetImage(tarfilter->GetOutput());
}

int main()
{

// Register the correct load implementation with the element typed visitor dispatcher.
  {
    ElementType::LoadImplementationFunctionPointer fp = &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad;
    DispatcherType::RegisterVisitor((ImageLoadType*)0,fp);
  }
  {
    ElementType2::LoadImplementationFunctionPointer fp = &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad;
    DispatcherType2::RegisterVisitor((ImageLoadType*)0,fp);
  }

  RegistrationType::Pointer X= RegistrationType::New(); // Declare the registration class

  X->SetConfigFileName("U:\\noe\\dev\\C\\Insight\\Examples\\FEM\\FEMregLMparams.txt");
  //X->SetConfigFileName("c:\\itk\\Insight\\Examples\\FEM\\FEMregLMparams.txt");
  if (  !X->ReadConfigFile( (X->GetConfigFileName()).c_str() ) ) { return -1; }

  // Read Raw Files
  ReadRawImageFiles(X);

  // Choose the material properties
  itk::fem::MaterialLinearElasticity::Pointer m;
  m=itk::fem::MaterialLinearElasticity::New();
  m->GN=0;       // Global number of the material ///
  m->E=X->GetElasticity();  // Young modulus -- used in the membrane ///
  m->A=1.0;     // Crossection area ///
  m->h=1.0;     // Crossection area ///
  m->I=1.0;    // Moment of inertia ///
  m->nu=0.; //.0;    // poissons -- DONT CHOOSE 1.0!!///
  m->RhoC=1.0;

  // Create the element type
  ElementType::Pointer e1=ElementType::New();
  e1->m_mat=dynamic_cast<itk::fem::MaterialLinearElasticity*>( m );
  X->SetElement(e1);
  X->SetMaterial(m);

  // Register the images
  X->RunRegistration();

  // Get outputs -- in image or vector field form
  X->WriteWarpedImage((X->GetResultsFileName()).c_str());

  X->SetWriteDisplacements(false);
  if (X->GetWriteDisplacements()) {
    X->WriteDisplacementField(0);
    X->WriteDisplacementField(1);
  }
  delete e1;
  delete m;
  return 0;
}

<commit_msg>fix: removing errant fstream include<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    FEMImageRegLMEx.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for detail.

     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.

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

// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif

#include "FEMImageRegLMEx.h"

// Below, we have typedefs that instantiate all necessary classes.
// Here, we instantiate the image type, load type and
// explicitly template the load implementation type.

#define TWOD
//#define THREED
#ifdef TWOD
typedef itk::Image< unsigned char, 2 >                     fileImageType;
typedef itk::Image< float, 2 >                     ImageType;
// We now declare an element type and load implementation pointer for the visitor class.
typedef itk::fem::Element2DC0LinearTriangularMembrane   ElementType2;
typedef itk::fem::Element2DC0LinearQuadrilateralMembrane   ElementType;
#endif
#ifdef THREED
typedef itk::Image< unsigned char, 3 >                     fileImageType;
typedef itk::Image< float, 3 >                     ImageType;
typedef itk::fem::Element3DC0LinearHexahedronMembrane   ElementType;
typedef itk::fem::Element3DC0LinearTetrahedronMembrane   ElementType2;
#endif
typedef itk::fem::ImageMetricLoad<ImageType,ImageType>     ImageLoadType;
template class itk::fem::ImageMetricLoadImplementation<ImageLoadType>;
typedef ElementType::LoadImplementationFunctionPointer     LoadImpFP;
typedef ElementType::LoadType                              ElementLoadType;
typedef ElementType2::LoadImplementationFunctionPointer     LoadImpFP2;
typedef ElementType2::LoadType                              ElementLoadType2;
typedef itk::fem::VisitorDispatcher<ElementType,ElementLoadType, LoadImpFP>
                                                          DispatcherType;
typedef itk::fem::VisitorDispatcher<ElementType2,ElementLoadType2, LoadImpFP2>
                                                          DispatcherType2;

typedef itk::fem::FEMRegistrationFilter<ImageType,ImageType> RegistrationType;

void ReadRawImageFiles( RegistrationType* X)
{

  typedef  itk::ImageFileReader< fileImageType >      FileSourceType;
  typedef  fileImageType::PixelType PixType;
  const unsigned int ImageDimension=fileImageType::ImageDimension;
  typedef  itk::RawImageIO< PixType,ImageDimension>   RawReaderType;

  FileSourceType::Pointer reffilter = FileSourceType::New();
  reffilter->SetFileName( (X->GetReferenceFile()).c_str() );
  FileSourceType::Pointer tarfilter = FileSourceType::New();
  tarfilter->SetFileName( (X->GetTargetFile()).c_str() );

  RawReaderType::Pointer  rawReader  = RawReaderType::New();
  rawReader->SetFileDimensionality( ImageDimension );

  ImageType::SizeType ImageSize=X->GetImageSize();
  for (unsigned int ii=0; ii<ImageDimension; ii++)
  {
    unsigned int temp=(unsigned int) ImageSize[ii];
    rawReader->SetDimensions( ii, temp );
  }
  reffilter->SetImageIO( rawReader );
  tarfilter->SetImageIO( rawReader );

  try
    {
    reffilter->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << "Exception caught during reference file reading " << std::endl;
    std::cerr << e << std::endl;
    return ;
    }
  try
    {
    tarfilter->Update();
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << "Exception caught during target file reading " << std::endl;
    std::cerr << e << std::endl;
    return ;
    }

  typedef itk::RescaleIntensityImageFilter<fileImageType,ImageType> FilterType;
  FilterType::Pointer refrescalefilter = FilterType::New();
  FilterType::Pointer tarrescalefilter = FilterType::New();

  refrescalefilter->SetInput(reffilter->GetOutput());
  tarrescalefilter->SetInput(tarfilter->GetOutput());

  const double desiredMinimum =  0.0;
  const double desiredMaximum =  255.0;

  refrescalefilter->SetOutputMinimum( desiredMinimum );
  refrescalefilter->SetOutputMaximum( desiredMaximum );
  refrescalefilter->UpdateLargestPossibleRegion();
  tarrescalefilter->SetOutputMinimum( desiredMinimum );
  tarrescalefilter->SetOutputMaximum( desiredMaximum );
  tarrescalefilter->UpdateLargestPossibleRegion();

  typedef itk::HistogramMatchingImageFilter<ImageType,ImageType> HEFilterType;
  HEFilterType::Pointer IntensityEqualizeFilter = HEFilterType::New();

  IntensityEqualizeFilter->SetReferenceImage( refrescalefilter->GetOutput() );
  IntensityEqualizeFilter->SetInput( tarrescalefilter->GetOutput() );
  IntensityEqualizeFilter->SetNumberOfHistogramLevels( 100);
  IntensityEqualizeFilter->SetNumberOfMatchPoints( 15);
  IntensityEqualizeFilter->ThresholdAtMeanIntensityOn();
  IntensityEqualizeFilter->Update();

  X->SetReferenceImage(refrescalefilter->GetOutput());
  X->SetTargetImage(IntensityEqualizeFilter->GetOutput()/*tarrescalefilter->GetOutput()*/);
//  X->SetReferenceImage(reffilter->GetOutput());
//  X->SetTargetImage(tarfilter->GetOutput());
}

int main()
{

// Register the correct load implementation with the element typed visitor dispatcher.
  {
    ElementType::LoadImplementationFunctionPointer fp = &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad;
    DispatcherType::RegisterVisitor((ImageLoadType*)0,fp);
  }
  {
    ElementType2::LoadImplementationFunctionPointer fp = &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad;
    DispatcherType2::RegisterVisitor((ImageLoadType*)0,fp);
  }

  RegistrationType::Pointer X= RegistrationType::New(); // Declare the registration class

  X->SetConfigFileName("U:\\noe\\dev\\C\\Insight\\Examples\\FEM\\FEMregLMparams.txt");
  //X->SetConfigFileName("c:\\itk\\Insight\\Examples\\FEM\\FEMregLMparams.txt");
  if (  !X->ReadConfigFile( (X->GetConfigFileName()).c_str() ) ) { return -1; }

  // Read Raw Files
  ReadRawImageFiles(X);

  // Choose the material properties
  itk::fem::MaterialLinearElasticity::Pointer m;
  m=itk::fem::MaterialLinearElasticity::New();
  m->GN=0;       // Global number of the material ///
  m->E=X->GetElasticity();  // Young modulus -- used in the membrane ///
  m->A=1.0;     // Crossection area ///
  m->h=1.0;     // Crossection area ///
  m->I=1.0;    // Moment of inertia ///
  m->nu=0.; //.0;    // poissons -- DONT CHOOSE 1.0!!///
  m->RhoC=1.0;

  // Create the element type
  ElementType::Pointer e1=ElementType::New();
  e1->m_mat=dynamic_cast<itk::fem::MaterialLinearElasticity*>( m );
  X->SetElement(e1);
  X->SetMaterial(m);

  // Register the images
  X->RunRegistration();

  // Get outputs -- in image or vector field form
  X->WriteWarpedImage((X->GetResultsFileName()).c_str());

  X->SetWriteDisplacements(false);
  if (X->GetWriteDisplacements()) {
    X->WriteDisplacementField(0);
    X->WriteDisplacementField(1);
  }
  delete e1;
  delete m;
  return 0;
}

<|endoftext|>


<commit_before>bb5acda1-2747-11e6-96df-e0f84713e7b8<commit_msg>Typical bobby<commit_after>bb6daf11-2747-11e6-b81a-e0f84713e7b8<|endoftext|>


<commit_before>7ab65011-2749-11e6-a43d-e0f84713e7b8<commit_msg>Initial commit.2<commit_after>7ac52075-2749-11e6-8a0e-e0f84713e7b8<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pba_constants.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// @file p9_pba_constants.H
/// @brief Constant enums to support PBA get/putmem procedures (FAPI)
///
// *HWP HWP Owner: Christina Graves clgraves@us.ibm.com
// *HWP FW Owner: Thi Tran thi@us.ibm.com
// *HWP Team: Nest
// *HWP Level: 2
// *HWp Consumed by: SBE

#ifndef _P9_PBA_CONSTANTS_H_
#define _P9_PBA_CONSTANTS_H_

//---------------------------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------------------------

extern "C"
{

//----------------------------------------------------------------------------------------------
// Constant definitions
//----------------------------------------------------------------------------------------------
    enum pba_flags
    {
        // Fastmode flag
        // If this flag is set it means we will not check for errors until
        // the very last granule for the read/write
        FLAG_PBA_FASTMODE = 0x80000000ull,

        // TTYPE flag
        // PBA operation type
        // 0b000: DMA
        // 0b001: LCO_M
        // 0b010: ATOMIC
        // 0b011: CACHE_INJ
        // 0b100: CI_PR_W
        // Same as in the documentation and how they will be passed to the register
        FLAG_PBA_TTYPE    = 0x70000000ull
    };

// TTYPE shift position
    const uint64_t FLAG_PBA_TTYPE_SHIFT = 28;
    const uint64_t FLAG_PBA_TTYPE_MASK = 0b111;

// --------------------------------------------------------------------
// TODO: RTC 147511 - Remove this definition when SBE code is updated
//                    and use PBA class.
// ---------------------------------------------------------------------
//these give the bit mask for each flag
    enum p9_pba_flags
    {
        //fastmode flag, if this flag is set it means we will not check for errors until the very last granule for the read/write
        FLAG_FASTMODE = 0x80000000ull,
        //ttype flag, this is 3 bits, will be set to 0 for dma, 1, to lco_m, 2 for atomic, 3 for cache_inj, and 4 for ci_pr_w --same as in the documentation and how they will be passed to the register
        FLAG_TTYPE    = 0x70000000ull
    };

    enum p9_pba_write_ttype
    {
        DMA = 0,
        LCO = 1,
        ATOMIC = 2,
        INJ = 3,
        CI = 4
    };

    const uint64_t FLAG_TTYPE_SHIFT = 28;
// -----------------------------------------------------

} //extern "C"

#endif //_P9_PBA_CONSTANTS_H_
<commit_msg>Fix TODOs in p9_build_smp HWP<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pba_constants.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/// @file p9_pba_constants.H
/// @brief Constant enums to support PBA get/putmem procedures (FAPI)
///
// *HWP HWP Owner: Christina Graves clgraves@us.ibm.com
// *HWP FW Owner: Thi Tran thi@us.ibm.com
// *HWP Team: Nest
// *HWP Level: 2
// *HWp Consumed by: SBE

#ifndef _P9_PBA_CONSTANTS_H_
#define _P9_PBA_CONSTANTS_H_

//---------------------------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------------------------

extern "C"
{

//----------------------------------------------------------------------------------------------
// Constant definitions
//----------------------------------------------------------------------------------------------
    enum pba_flags
    {
        // Fastmode flag
        // If this flag is set it means we will not check for errors until
        // the very last granule for the read/write
        FLAG_PBA_FASTMODE = 0x80000000ull,

        // TTYPE flag
        // PBA operation type
        // 0b000: DMA
        // 0b001: LCO_M
        // 0b010: ATOMIC
        // 0b011: CACHE_INJ
        // 0b100: CI_PR_W
        // Same as in the documentation and how they will be passed to the register
        FLAG_PBA_TTYPE    = 0x70000000ull
    };

// TTYPE shift position
    const uint64_t FLAG_PBA_TTYPE_SHIFT = 28;
    const uint64_t FLAG_PBA_TTYPE_MASK = 0b111;

} //extern "C"

#endif //_P9_PBA_CONSTANTS_H_
<|endoftext|>


<commit_before>#include "zookeeper_cc_util.h"

#include <utility>
#include <assert.h>
#include <string.h>

namespace zookeeper_cc_util {

std::string EnsureTrailingSlash(std::string data) {
  if (!data.empty() && data[data.size() - 1] == '/') {
    return data;
  } else {
    return data + "/";
  }
}

const char* GetLastPathSegment(const char *path) {
  const char *last_sep = strrchr(path, '/');
  if (!last_sep) {
    return path;
  } else {
    return last_sep + 1;
  }
}

Zookeeper::Zookeeper(std::string hosts, int recv_timeout, std::string base)
  : hosts_(std::move(hosts))
  , recv_timeout_(recv_timeout)
  , base_(EnsureTrailingSlash(std::move(base)))
{
}

std::string Zookeeper::GetAbsolutePath(const char *path) {
  if (path[0] == '/') {
    return base_ + (path + 1);
  } else {
    return base_ + path;
  }
}

bool Zookeeper::Init() {
  assert(!zh_);
  zh_.reset(zookeeper_init(
    hosts_.c_str(),
    NULL, // watcher
    recv_timeout_,
    NULL, // clientid
    NULL, // watcher context
    0 // flags
  ));
  return static_cast<bool>(zh_);
}

int Zookeeper::Create(const char *path, const std::string &value,
                      bool ephemeral, struct ACL_vector *acl) {
  assert(zh_);
  return zoo_create(
    zh_.get(),
    GetAbsolutePath(path).c_str(),
    value.data(),
    value.size(),
    acl,
    (ephemeral ? ZOO_EPHEMERAL : 0), // flags
    NULL, // path_buffer
    0 // path_buffer_len
  );
}

int Zookeeper::Exists(const char *path, const WatcherCallback *watcher,
                      struct Stat *stat) {
  assert(zh_);
  return zoo_wexists(
    zh_.get(),
    GetAbsolutePath(path).c_str(),
    watcher ? &Zookeeper::WatcherHandler : NULL,
    const_cast<void*>(static_cast<const void*>(watcher)),
    stat
  );
}

int Zookeeper::Get(const char *path, std::string *output,
                   const WatcherCallback *watcher, struct Stat *stat) {
  assert(zh_);
  // Zookeeper's limit on data size is 1 MiB, plus 1 for null terminator.
  static const int BUF_SIZE = 1024 * 1024 + 1;
  thread_local char buf[BUF_SIZE];
  int len = sizeof buf;
  int res = zoo_wget(
    zh_.get(),
    GetAbsolutePath(path).c_str(),
    watcher ? &Zookeeper::WatcherHandler : NULL,
    const_cast<void*>(static_cast<const void*>(watcher)),
    buf,
    &len,
    stat
  );
  if (res == ZOK && output) {
    output->assign(buf, buf + len);
  }
  return res;
}

int Zookeeper::Set(const char *path, const std::string &data, int version) {
  assert(zh_);
  return zoo_set(zh_.get(), GetAbsolutePath(path).c_str(),
                 data.data(), data.size(), version);
}

int Zookeeper::Delete(const char *path, int version) {
  assert(zh_);
  return zoo_delete(zh_.get(), GetAbsolutePath(path).c_str(), version);
}

int Zookeeper::GetChildren(const char *path,
                           std::vector<std::string> *children_name,
                           const WatcherCallback *watcher) {
  assert(zh_);
  String_vector children {};
  int res = zoo_wget_children(
    zh_.get(),
    GetAbsolutePath(path).c_str(),
    watcher ? &Zookeeper::WatcherHandler : NULL,
    const_cast<void*>(static_cast<const void*>(watcher)),
    &children
  );
  if (res == ZOK) {
    children_name->assign(children.data, children.data + children.count);
  }
  deallocate_String_vector(&children);
  return res;
}

int Zookeeper::EnforcePath(const char *rel_path, struct ACL_vector *acl) {
  assert(zh_);
  std::string full_path = GetAbsolutePath(rel_path) + "/";
  int res = ZOK;
  // Iterate over all parent znodes of `full_path` by replacing slashes
  // with null characters one-by-one, skipping the very first slash at
  // position 0 (root znode already exists).
  for (size_t i = 1; i < full_path.size(); i++) {
    if (full_path[i] == '/') {
      full_path[i] = 0;
      res = zoo_create(
        zh_.get(),
        full_path.c_str(),
        "", // value
        0, // valuelen
        acl,
        0, // flags
        NULL, // path_buffer
        0 // path_buffer_length
      );
      full_path[i] = '/';
      if (res != ZOK && res != ZNODEEXISTS) {
        return res;
      }
    }
  }
  return res;
}

void Zookeeper::WatcherHandler(zhandle_t *zzh, int type, int state,
                 const char *path, void *watcherCtx) {
  (*static_cast<WatcherCallback*>(watcherCtx))(type, state, path);
}

}  // namespace zookeeper_cc_util
<commit_msg>model-server/zookeeper_cc_util: bug fixes<commit_after>#include "zookeeper_cc_util.h"

#include <utility>
#include <assert.h>
#include <string.h>

namespace zookeeper_cc_util {

std::string EnsureTrailingSlash(std::string data) {
  if (!data.empty() && data[data.size() - 1] == '/') {
    return data;
  } else {
    return data + "/";
  }
}

const char* GetLastPathSegment(const char *path) {
  const char *last_sep = strrchr(path, '/');
  if (!last_sep) {
    return path;
  } else {
    return last_sep + 1;
  }
}

Zookeeper::Zookeeper(std::string hosts, int recv_timeout, std::string base)
  : hosts_(std::move(hosts))
  , recv_timeout_(recv_timeout)
  , base_(EnsureTrailingSlash(std::move(base)))
{
}

std::string Zookeeper::GetAbsolutePath(const char *path) {
  if (path[0] == '/') {
    return base_ + (path + 1);
  } else if (!path[0]) {
    return base_.substr(0, base_.size() - 1);
  } else {
    return base_ + path;
  }
}

bool Zookeeper::Init() {
  assert(!zh_);
  zh_.reset(zookeeper_init(
    hosts_.c_str(),
    NULL, // watcher
    recv_timeout_,
    NULL, // clientid
    NULL, // watcher context
    0 // flags
  ));
  return static_cast<bool>(zh_);
}

int Zookeeper::Create(const char *path, const std::string &value,
                      bool ephemeral, struct ACL_vector *acl) {
  assert(zh_);
  return zoo_create(
    zh_.get(),
    GetAbsolutePath(path).c_str(),
    value.data(),
    value.size(),
    acl,
    (ephemeral ? ZOO_EPHEMERAL : 0), // flags
    NULL, // path_buffer
    0 // path_buffer_len
  );
}

int Zookeeper::Exists(const char *path, const WatcherCallback *watcher,
                      struct Stat *stat) {
  assert(zh_);
  return zoo_wexists(
    zh_.get(),
    GetAbsolutePath(path).c_str(),
    watcher ? &Zookeeper::WatcherHandler : NULL,
    const_cast<void*>(static_cast<const void*>(watcher)),
    stat
  );
}

int Zookeeper::Get(const char *path, std::string *output,
                   const WatcherCallback *watcher, struct Stat *stat) {
  assert(zh_);
  // Zookeeper's limit on data size is 1 MiB, plus 1 for null terminator.
  static const int BUF_SIZE = 1024 * 1024 + 1;
  thread_local char buf[BUF_SIZE];
  int len = sizeof buf;
  int res = zoo_wget(
    zh_.get(),
    GetAbsolutePath(path).c_str(),
    watcher ? &Zookeeper::WatcherHandler : NULL,
    const_cast<void*>(static_cast<const void*>(watcher)),
    buf,
    &len,
    stat
  );
  if (res == ZOK && output) {
    output->assign(buf, buf + len);
  }
  return res;
}

int Zookeeper::Set(const char *path, const std::string &data, int version) {
  assert(zh_);
  return zoo_set(zh_.get(), GetAbsolutePath(path).c_str(),
                 data.data(), data.size(), version);
}

int Zookeeper::Delete(const char *path, int version) {
  assert(zh_);
  return zoo_delete(zh_.get(), GetAbsolutePath(path).c_str(), version);
}

int Zookeeper::GetChildren(const char *path,
                           std::vector<std::string> *children_name,
                           const WatcherCallback *watcher) {
  assert(zh_);
  String_vector children {};
  int res = zoo_wget_children(
    zh_.get(),
    GetAbsolutePath(path).c_str(),
    watcher ? &Zookeeper::WatcherHandler : NULL,
    const_cast<void*>(static_cast<const void*>(watcher)),
    &children
  );
  if (res == ZOK) {
    children_name->assign(children.data, children.data + children.count);
  }
  deallocate_String_vector(&children);
  return res;
}

int Zookeeper::EnforcePath(const char *rel_path, struct ACL_vector *acl) {
  assert(zh_);
  std::string full_path = EnsureTrailingSlash(GetAbsolutePath(rel_path));
  int res = ZOK;
  // Iterate over all parent znodes of `full_path` by replacing slashes
  // with null characters one-by-one, skipping the very first slash at
  // position 0 (root znode already exists).
  for (size_t i = 1; i < full_path.size(); i++) {
    if (full_path[i] == '/') {
      full_path[i] = 0;
      res = zoo_create(
        zh_.get(),
        full_path.c_str(),
        "", // value
        0, // valuelen
        acl,
        0, // flags
        NULL, // path_buffer
        0 // path_buffer_length
      );
      full_path[i] = '/';
      if (res != ZOK && res != ZNODEEXISTS) {
        return res;
      }
    }
  }
  return res;
}

void Zookeeper::WatcherHandler(zhandle_t *zzh, int type, int state,
                 const char *path, void *watcherCtx) {
  (*static_cast<WatcherCallback*>(watcherCtx))(type, state, path);
}

}  // namespace zookeeper_cc_util
<|endoftext|>


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

#include "selxSuperElastixFilter.h"

#include "selxItkSmoothingRecursiveGaussianImageFilterComponent.h"
#include "selxItkImageSink.h"
#include "selxItkImageSource.h"
#include "selxItkMeshSink.h"
#include "selxItkMeshSource.h"
#include "selxRegistrationController.h"

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkDisplacementFieldTransform.h"
#include "itkComposeDisplacementFieldsImageFilter.h"

#include "itkCompositeTransform.h"
#include "itkVector.h"
#include "itkPoint.h"
#include "itkMesh.h"
#include "itkMeshFileReader.h"
#include "itkMeshFileWriter.h"

#include "DefaultComponents.h"
#include "selxDataManager.h"
#include "gtest/gtest.h"

namespace selx {

  class SuperElastixFilterTest : public ::testing::Test {
  public:
    typedef itk::Image<float, 2> Image2DType;
    typedef itk::ImageFileReader<Image2DType> ImageReader2DType;
    typedef itk::ImageFileWriter<Image2DType> ImageWriter2DType;

    typedef itk::Image<double, 3> Image3DType;
    typedef itk::ImageFileReader<Image3DType> ImageReader3DType;
    typedef itk::ImageFileWriter<Image3DType> ImageWriter3DType;

    //TODO make SuperElastixFilter templated over Components
    typedef selx::SuperElastixFilter < TypeList<> > SuperElastixFilterType;

    typedef itk::Mesh<float, 2> MeshType;
    typedef itk::MeshFileReader<MeshType> MeshReaderType;
    typedef itk::MeshFileWriter<MeshType> MeshWriterType;

    typedef DataManager DataManagerType;
    virtual void SetUp() {

    }

    virtual void TearDown() {
      itk::ObjectFactoryBase::UnRegisterAllFactories();
    }

  };

  TEST_F(SuperElastixFilterTest, ImageOnly)
  {
    DataManagerType::Pointer dataManager = DataManagerType::New();

    ImageReader3DType::Pointer imageReader3D = ImageReader3DType::New();
    ImageWriter3DType::Pointer imageWriter3D = ImageWriter3DType::New();

    imageReader3D->SetFileName(dataManager->GetInputFile("sphereA3d.mhd"));
    imageWriter3D->SetFileName(dataManager->GetOutputFile("SuperElastixFilterTest_sphereA3d.mhd"));

    ComponentFactory<ItkImageSinkComponent<3, double>>::RegisterOneFactory();
    ComponentFactory<ItkImageSourceComponent<3, double>>::RegisterOneFactory();
    ComponentFactory<ItkSmoothingRecursiveGaussianImageFilterComponent<3, double>>::RegisterOneFactory();
    ComponentFactory<RegistrationControllerComponent<>>::RegisterOneFactory();

    SuperElastixFilterType::Pointer mySuperElastix;

    Blueprint::Pointer blueprint = Blueprint::New();

    blueprint->AddComponent("InputImage", { { "NameOfClass", { "ItkImageSourceComponent" } } });
    blueprint->AddComponent("ImageFilter", { { "NameOfClass", { "ItkSmoothingRecursiveGaussianImageFilterComponent" } } });
    blueprint->AddComponent("OutputImage", { { "NameOfClass", { "ItkImageSinkComponent" } } });
    blueprint->AddConnection("InputImage", "ImageFilter", { {} }); //
    blueprint->AddConnection("ImageFilter", "OutputImage", { {} });

    EXPECT_NO_THROW(mySuperElastix = SuperElastixFilterType::New());
    mySuperElastix->SetBlueprint(blueprint);

    mySuperElastix->SetInput("InputImage", imageReader3D->GetOutput());
    imageWriter3D->SetInput(mySuperElastix->GetOutput<Image3DType>("OutputImage"));

    EXPECT_NO_THROW(imageWriter3D->Update());
  }
  TEST_F(SuperElastixFilterTest, ImageAndMesh)
  {
    DataManagerType::Pointer dataManager = DataManagerType::New();

    ImageReader3DType::Pointer imageReader3D = ImageReader3DType::New();
    ImageWriter3DType::Pointer imageWriter3D = ImageWriter3DType::New();

    imageReader3D->SetFileName(dataManager->GetInputFile("sphereA3d.mhd"));
    imageWriter3D->SetFileName(dataManager->GetOutputFile("SuperElastixFilterTest_sphereA3d.mhd"));

    MeshReaderType::Pointer meshReader = MeshReaderType::New();
    MeshWriterType::Pointer meshWriter = MeshWriterType::New();

    meshReader->SetFileName(dataManager->GetInputFile("2dSquare.vtk"));
    meshWriter->SetFileName(dataManager->GetOutputFile("SuperElastixFilterTest_2dSquare.vtk"));

    ComponentFactory<ItkImageSinkComponent<3, double>>::RegisterOneFactory();
    ComponentFactory<ItkImageSourceComponent<3, double>>::RegisterOneFactory();
    ComponentFactory<ItkSmoothingRecursiveGaussianImageFilterComponent<3, double>>::RegisterOneFactory();

    ComponentFactory<ItkMeshSinkComponent<2, float>>::RegisterOneFactory();
    ComponentFactory<ItkMeshSourceComponent<2, float>>::RegisterOneFactory();

    SuperElastixFilterType::Pointer mySuperElastix;

    Blueprint::Pointer blueprint = Blueprint::New();

    blueprint->AddComponent("InputImage", { { "NameOfClass", { "ItkImageSourceComponent" } } });
    blueprint->AddComponent("ImageFilter", { { "NameOfClass", { "ItkSmoothingRecursiveGaussianImageFilterComponent" } } });
    blueprint->AddComponent("OutputImage", { { "NameOfClass", { "ItkImageSinkComponent" } } });
    blueprint->AddConnection("InputImage", "ImageFilter", Blueprint::ParameterMapType()); //
    blueprint->AddConnection("ImageFilter", "OutputImage", Blueprint::ParameterMapType());

    blueprint->AddComponent("InputMesh", { { "NameOfClass", { "ItkMeshSourceComponent" } } });
    blueprint->AddComponent("OutputMesh", { { "NameOfClass", { "ItkMeshSinkComponent" } } });
    blueprint->AddConnection("InputMesh", "OutputMesh", Blueprint::ParameterMapType());

    EXPECT_NO_THROW(mySuperElastix = SuperElastixFilterType::New());
    mySuperElastix->SetBlueprint(blueprint);

    mySuperElastix->SetInput("InputMesh", meshReader->GetOutput());
    meshWriter->SetInput(mySuperElastix->GetOutput<MeshType>("OutputMesh"));

    mySuperElastix->SetInput("InputImage", imageReader3D->GetOutput());
    imageWriter3D->SetInput(mySuperElastix->GetOutput<Image3DType>("OutputImage"));

    //mySuperElastix->Update();

    EXPECT_NO_THROW(meshWriter->Update());
    EXPECT_NO_THROW(imageWriter3D->Update());
  }
}<commit_msg>ENH: Added tests for SuperElastix i/o connections<commit_after>/*=========================================================================
*
*  Copyright Leiden University Medical Center, Erasmus University Medical
*  Center and contributors
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*        http://www.apache.org/licenses/LICENSE-2.0.txt
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*=========================================================================*/

#include "selxSuperElastixFilter.h"

#include "selxItkSmoothingRecursiveGaussianImageFilterComponent.h"
#include "selxItkImageSink.h"
#include "selxItkImageSource.h"
#include "selxItkMeshSink.h"
#include "selxItkMeshSource.h"
#include "selxRegistrationController.h"

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkDisplacementFieldTransform.h"
#include "itkComposeDisplacementFieldsImageFilter.h"

#include "itkCompositeTransform.h"
#include "itkVector.h"
#include "itkPoint.h"
#include "itkMesh.h"
#include "itkMeshFileReader.h"
#include "itkMeshFileWriter.h"

#include "DefaultComponents.h"
#include "selxDataManager.h"
#include "gtest/gtest.h"

namespace selx {

  class SuperElastixFilterTest : public ::testing::Test {
  public:
    typedef itk::Image<float, 2> Image2DType;
    typedef itk::ImageFileReader<Image2DType> ImageReader2DType;
    typedef itk::ImageFileWriter<Image2DType> ImageWriter2DType;

    typedef itk::Image<double, 3> Image3DType;
    typedef itk::ImageFileReader<Image3DType> ImageReader3DType;
    typedef itk::ImageFileWriter<Image3DType> ImageWriter3DType;

    /** Fill SUPERelastix' component data base by registering various components */
    typedef TypeList <
      ItkImageSinkComponent<3, double>,
      ItkImageSourceComponent<3, double>,
      ItkSmoothingRecursiveGaussianImageFilterComponent<3, double>,
      ItkMeshSinkComponent<2, float>,
      ItkMeshSourceComponent<2, float> > RegisterComponents;

    typedef SuperElastixFilter<RegisterComponents>          SuperElastixFilterType;

    typedef itk::Mesh<float, 2> MeshType;
    typedef itk::MeshFileReader<MeshType> MeshReaderType;
    typedef itk::MeshFileWriter<MeshType> MeshWriterType;

    typedef DataManager DataManagerType;
    virtual void SetUp() {

    }

    virtual void TearDown() {
      itk::ObjectFactoryBase::UnRegisterAllFactories();
    }

  };

  TEST_F(SuperElastixFilterTest, ImageOnly)
  {
    DataManagerType::Pointer dataManager = DataManagerType::New();

    ImageReader3DType::Pointer imageReader3D = ImageReader3DType::New();
    ImageWriter3DType::Pointer imageWriter3D = ImageWriter3DType::New();

    imageReader3D->SetFileName(dataManager->GetInputFile("sphereA3d.mhd"));
    imageWriter3D->SetFileName(dataManager->GetOutputFile("SuperElastixFilterTest_sphereA3d.mhd"));

    Blueprint::Pointer blueprint = Blueprint::New();

    blueprint->AddComponent("InputImage", { { "NameOfClass", { "ItkImageSourceComponent" } } });
    blueprint->AddComponent("ImageFilter", { { "NameOfClass", { "ItkSmoothingRecursiveGaussianImageFilterComponent" } } });
    blueprint->AddComponent("OutputImage", { { "NameOfClass", { "ItkImageSinkComponent" } } });
    blueprint->AddConnection("InputImage", "ImageFilter", { {} }); //
    blueprint->AddConnection("ImageFilter", "OutputImage", { {} });

    SuperElastixFilterType::Pointer mySuperElastix;
    EXPECT_NO_THROW(mySuperElastix = SuperElastixFilterType::New());
    mySuperElastix->SetBlueprint(blueprint);

    mySuperElastix->SetInput("InputImage", imageReader3D->GetOutput());
    imageWriter3D->SetInput(mySuperElastix->GetOutput<Image3DType>("OutputImage"));

    EXPECT_NO_THROW(imageWriter3D->Update());
  }
  TEST_F(SuperElastixFilterTest, ImageAndMesh)
  {
    DataManagerType::Pointer dataManager = DataManagerType::New();

    ImageReader3DType::Pointer imageReader3D = ImageReader3DType::New();
    ImageWriter3DType::Pointer imageWriter3D = ImageWriter3DType::New();

    imageReader3D->SetFileName(dataManager->GetInputFile("sphereA3d.mhd"));
    imageWriter3D->SetFileName(dataManager->GetOutputFile("SuperElastixFilterTest_sphereA3d.mhd"));

    MeshReaderType::Pointer meshReader = MeshReaderType::New();
    MeshWriterType::Pointer meshWriter = MeshWriterType::New();

    meshReader->SetFileName(dataManager->GetInputFile("2dSquare.vtk"));
    meshWriter->SetFileName(dataManager->GetOutputFile("SuperElastixFilterTest_2dSquare.vtk"));

    Blueprint::Pointer blueprint = Blueprint::New();

    blueprint->AddComponent("InputImage", { { "NameOfClass", { "ItkImageSourceComponent" } } });
    blueprint->AddComponent("ImageFilter", { { "NameOfClass", { "ItkSmoothingRecursiveGaussianImageFilterComponent" } } });
    blueprint->AddComponent("OutputImage", { { "NameOfClass", { "ItkImageSinkComponent" } } });
    blueprint->AddConnection("InputImage", "ImageFilter", Blueprint::ParameterMapType()); //
    blueprint->AddConnection("ImageFilter", "OutputImage", Blueprint::ParameterMapType());

    blueprint->AddComponent("InputMesh", { { "NameOfClass", { "ItkMeshSourceComponent" } } });
    blueprint->AddComponent("OutputMesh", { { "NameOfClass", { "ItkMeshSinkComponent" } } });
    blueprint->AddConnection("InputMesh", "OutputMesh", Blueprint::ParameterMapType());

    SuperElastixFilterType::Pointer mySuperElastix;
    EXPECT_NO_THROW(mySuperElastix = SuperElastixFilterType::New());
    mySuperElastix->SetBlueprint(blueprint);

    mySuperElastix->SetInput("InputMesh", meshReader->GetOutput());
    meshWriter->SetInput(mySuperElastix->GetOutput<MeshType>("OutputMesh"));

    mySuperElastix->SetInput("InputImage", imageReader3D->GetOutput());
    imageWriter3D->SetInput(mySuperElastix->GetOutput<Image3DType>("OutputImage"));

    //mySuperElastix->Update();

    EXPECT_NO_THROW(meshWriter->Update());
    EXPECT_NO_THROW(imageWriter3D->Update());
  }
  TEST_F(SuperElastixFilterTest, TooManyInputs)
  {
    DataManagerType::Pointer dataManager = DataManagerType::New();

    ImageReader3DType::Pointer imageReader3D_A = ImageReader3DType::New();
    ImageReader3DType::Pointer imageReader3D_B = ImageReader3DType::New();

    imageReader3D_A->SetFileName(dataManager->GetInputFile("sphereA3d.mhd"));
    imageReader3D_B->SetFileName(dataManager->GetInputFile("sphereA3d.mhd"));

    Blueprint::Pointer blueprint = Blueprint::New();

    blueprint->AddComponent("Source_A", { { "NameOfClass", { "ItkImageSourceComponent" } } });

    SuperElastixFilterType::Pointer mySuperElastix;
    EXPECT_NO_THROW(mySuperElastix = SuperElastixFilterType::New());
    mySuperElastix->SetBlueprint(blueprint);

    mySuperElastix->SetInput("Source_A", imageReader3D_A->GetOutput());
    mySuperElastix->SetInput("Source_B", imageReader3D_B->GetOutput());

    EXPECT_THROW(mySuperElastix->Update(), itk::ExceptionObject);

  }
  TEST_F(SuperElastixFilterTest, TooManySources)
  {
    DataManagerType::Pointer dataManager = DataManagerType::New();

    ImageReader3DType::Pointer imageReader3D_A = ImageReader3DType::New();

    imageReader3D_A->SetFileName(dataManager->GetInputFile("sphereA3d.mhd"));

    Blueprint::Pointer blueprint = Blueprint::New();

    blueprint->AddComponent("Source_A", { { "NameOfClass", { "ItkImageSourceComponent" } } });
    blueprint->AddComponent("Source_B", { { "NameOfClass", { "ItkImageSourceComponent" } } });
    SuperElastixFilterType::Pointer mySuperElastix;
    EXPECT_NO_THROW(mySuperElastix = SuperElastixFilterType::New());
    mySuperElastix->SetBlueprint(blueprint);

    mySuperElastix->SetInput("Source_A", imageReader3D_A->GetOutput());

    EXPECT_THROW(mySuperElastix->Update(), itk::ExceptionObject);

  }
  TEST_F(SuperElastixFilterTest, TooManyOutputs)
  {
    DataManagerType::Pointer dataManager = DataManagerType::New();

    ImageWriter3DType::Pointer imageWriter3D_A = ImageWriter3DType::New();
    ImageWriter3DType::Pointer imageWriter3D_B = ImageWriter3DType::New();
    imageWriter3D_A->SetFileName(dataManager->GetOutputFile("SuperElastixFilterTest_TooManyOutputs.mhd"));
    imageWriter3D_B->SetFileName(dataManager->GetOutputFile("SuperElastixFilterTest_TooManyOutputs.mhd"));

    Blueprint::Pointer blueprint = Blueprint::New();

    blueprint->AddComponent("Sink_A", { { "NameOfClass", { "ItkImageSinkComponent" } } });

    SuperElastixFilterType::Pointer mySuperElastix;
    EXPECT_NO_THROW(mySuperElastix = SuperElastixFilterType::New());
    mySuperElastix->SetBlueprint(blueprint);

    imageWriter3D_A->SetInput(mySuperElastix->GetOutput<Image3DType>("Sink_A"));
    imageWriter3D_B->SetInput(mySuperElastix->GetOutput<Image3DType>("Sink_B"));

    EXPECT_THROW(imageWriter3D_B->Update(), itk::ExceptionObject);

  }
  TEST_F(SuperElastixFilterTest, TooManySinks)
  {
    DataManagerType::Pointer dataManager = DataManagerType::New();

    ImageWriter3DType::Pointer imageWriter3D_A = ImageWriter3DType::New();
    imageWriter3D_A->SetFileName(dataManager->GetOutputFile("SuperElastixFilterTest_TooManyOutputs.mhd"));

    Blueprint::Pointer blueprint = Blueprint::New();

    blueprint->AddComponent("Sink_A", { { "NameOfClass", { "ItkImageSinkComponent" } } });
    blueprint->AddComponent("Sink_B", { { "NameOfClass", { "ItkImageSinkComponent" } } });

    SuperElastixFilterType::Pointer mySuperElastix;
    EXPECT_NO_THROW(mySuperElastix = SuperElastixFilterType::New());
    mySuperElastix->SetBlueprint(blueprint);

    imageWriter3D_A->SetInput(mySuperElastix->GetOutput<Image3DType>("Sink_A"));

    EXPECT_THROW(imageWriter3D_A->Update(), itk::ExceptionObject);

  }
}<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_pll_initf.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_mem_pll_initf.H
///
/// @brief PLL initfile for MBAs
//------------------------------------------------------------------------------
// *HWP HW Owner        : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Sunil Kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 1
// *HWP Consumed by     : HB
//------------------------------------------------------------------------------

#ifndef _P9_MEM_PLL_INITF_H_
#define _P9_MEM_PLL_INITF_H_

#include <fapi2.H>

typedef fapi2::ReturnCode (*p9_mem_pll_initf_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

/// @brief  > This step is a no-op if memory is running in synchronous mode since MCAs are using thr nest PLL
///  > MBA PLL setup
///       Hostboot does not support twiddling bits, looks up which bucket to use from attributes set during mss_freq
///       Request SBE to scan said ring and data stored as a ring image.
///
///
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PROC_CHIP target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
    fapi2::ReturnCode p9_mem_pll_initf(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chiplet);
}

#endif
<commit_msg>VBU IPL -- update sim PLL configuration<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_pll_initf.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_mem_pll_initf.H
///
/// @brief PLL initfile for MBAs
//------------------------------------------------------------------------------
// *HWP HW Owner        : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Sunil Kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : HB
//------------------------------------------------------------------------------

#ifndef _P9_MEM_PLL_INITF_H_
#define _P9_MEM_PLL_INITF_H_

#include <fapi2.H>

typedef fapi2::ReturnCode (*p9_mem_pll_initf_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

/// @brief  > This step is a no-op if memory is running in synchronous mode since MCAs are using thr nest PLL
///  > MBA PLL setup
///       Hostboot does not support twiddling bits, looks up which bucket to use from attributes set during mss_freq
///       Request SBE to scan said ring and data stored as a ring image.
///
///
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PROC_CHIP target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
    fapi2::ReturnCode p9_mem_pll_initf(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}

#endif
<|endoftext|>