<commit_before>//
//  Exponent.cpp
//  Calculator
//
//  Created by Gavin Scheele on 3/27/14.
//  Copyright (c) 2014 Gavin Scheele. All rights reserved.
//

#include "Exponential.h"

Exponential::Exponential(Expression* base, Rational* exponent){
    this->type = "exponential";
    this->base = base;
    this->exponent = exponent;
    this->exde = new Integer(exponent->getDenominator());
    if (exde->getValue() != 1) {
    	//if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1
    	Integer* baseAsInteger = (Integer *) base;
        base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);
        Integer* one = new Integer(1);
        exponent->setDenominator(one);
    }
    this->exnu = new Integer(exponent->getNumerator());
    if (canExponentiate()) {
    	exponentiate();
    }
}
Exponential::~Exponential(){

}

bool Exponential::canExponentiate() {
    if(base->type == "euler"){
        return false;

    }else if(base->type == "exponential"){
	Exponential* ex = (Exponential *) base;
	this->exponent->multiply(ex->getExponent());
	Integer* numSum = new Integer (1);
	ex->getExponent()->setNumerator(numSum);
        return false;
        // false is returned because the base itself would have already been exponentiated if it were possible

    }else if(base->type == "integer"){
        return true;

    }else if(base->type == "logarithm"){
        return false;

    }else if(base->type == "nthRoot"){
	nthRoot* nr = (nthRoot *) base;
	Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator());
	//makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one
	this->exponent = r;
	nr->setRoot(1);
	return false;

    }else if(base->type == "pi"){
        return false;

    }else if(base->type == "rational"){
        Rational* r = (Rational *) base;
        if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") {
          Exponential* nu = new Exponential(r->geteNumerator(), this->exponent);
          r->setNumerator(nu);
          Exponential* de = new Exponential(r->geteDenominator(), this->exponent);
          r->setDenominator(de);
        }

    }else{
        cout << "type not recognized" << endl;
    }
    return false;
}

void Exponential::exponentiate(){

    Expression* constantBase = base;
    if (this->exponent->getNumerator()==0) {
        Integer* oneInt = new Integer(1);
        Rational* oneRat = new Rational(1, 1);
       this->exponent=oneRat;
       this->base=oneInt;

    }
    bool toFlip = false;
    if (exnu->getValue()<0) {
	    exnu->setValue(exnu->getValue()*-1);
            toFlip = true;
            //handles negative exponents
    }
    while (exponent->getNumerator()>1)
    	{
        base->multiply(constantBase);
        Integer* one = new Integer(1);
        exponent->setNumerator(exponent->geteNumerator()->subtract(one));     //Error: cannot initialize a parameter of type 'Expression *' with an rvalue of type 'int'
    }
    if (toFlip) {
        Integer* one = new Integer(1);
        Rational* mouse = new Rational(one, base);
    	base = mouse;
    }

}

Expression* Exponential::add(Expression* a){
    if(a->type == "euler"){

    }else if(a->type == "exponential"){
	Exponential* ex = (Exponential *) a;
	if (ex->getBase()==this->base) {
		if (ex->getExponent()==this->exponent) {
			Integer* two = new Integer(2);
			this->multiply(two);
		}
	}

    }else if(a->type == "integer"){

    }else if(a->type == "logarithm"){

    }else if(a->type == "nthRoot"){

    }else if(a->type == "pi"){

    }else if(a->type == "rational"){

    }else{
        cout << "type not recognized" << endl;
    }
    return this;
}
Expression* Exponential::subtract(Expression* a){
    if(a->type == "euler"){

    }else if(a->type == "exponential"){
	Exponential* ex = (Exponential *) a;
	if (ex->getBase()==this->base) {
		if (ex->getExponent()==this->exponent) {
			Integer* zero = new Integer(0);
			this->multiply(zero);
		}
	}
    }else if(a->type == "integer"){

    }else if(a->type == "logarithm"){

    }else if(a->type == "nthRoot"){

    }else if(a->type == "pi"){

    }else if(a->type == "rational"){

    }else{
        cout << "type not recognized" << endl;
    }
    return this;
}
Expression* Exponential::multiply(Expression* a){
    if(a->type == "euler"){

    }else if(a->type == "exponential"){
	Exponential* ex = (Exponential *) a;
	if (this->base == ex->getBase()) {
		this->exponent->add(ex->getExponent());
	}

    }else if(a->type == "integer"){

    }else if(a->type == "logarithm"){

    }else if(a->type == "nthRoot"){

    }else if(a->type == "pi"){

    }else if(a->type == "rational"){
	Rational* r = (Rational *) r;
	r->setNumerator(r->geteNumerator()->multiply(this));        //Error: expected expression
	return r;

    }else{
        cout << "type not recognized" << endl;
    }
    return this;
}
Expression* Exponential::divide(Expression* a){
    if(a->type == "euler"){

    }else if(a->type == "exponential"){
	Exponential* ex = (Exponential *) a;
	if (this->base == ex->getBase()) {
		this->exponent->subtract(ex->getExponent());
	}

    }else if(a->type == "integer"){

    }else if(a->type == "logarithm"){

    }else if(a->type == "nthRoot"){

    }else if(a->type == "pi"){

    }else if(a->type == "rational"){
	Rational* r = (Rational *) r;
	r->setDenominator(r->geteDenominator()->multiply(this));      //Error: member reference type 'int' is not a pointer
	return r;

    }else{
        cout << "type not recognized" << endl;
    }
    return this;
}

Rational* Exponential::getExponent() {
    return exponent;
}

Expression* Exponential::getBase() {
    return base;
}

Integer* Exponential::getExnu() {
	return exnu;
}

Integer* Exponential::getExde() {
	return exde;
}

void Exponential::setExnu(Integer* n) {
	exnu = n;
}

void Exponential::setExde(Integer* n) {
	exde = n;
}

void Exponential::setExponent(Rational* e) {
    exponent = e;
}

void Exponential::setBase(Expression* e) {
    base = e;
}

string Exponential::toString() {
    stringstream str;
    str << base << "^" << exponent;
    return str.str();
}

ostream& Exponential::print(std::ostream& output) const{
    output << this->base << this->exponent; //overload cout so that it makes sense
    return output;
}
<commit_msg>changed r to a<commit_after>//
//  Exponent.cpp
//  Calculator
//
//  Created by Gavin Scheele on 3/27/14.
//  Copyright (c) 2014 Gavin Scheele. All rights reserved.
//

#include "Exponential.h"

Exponential::Exponential(Expression* base, Rational* exponent){
    this->type = "exponential";
    this->base = base;
    this->exponent = exponent;
    this->exde = new Integer(exponent->getDenominator());
    if (exde->getValue() != 1) {
    	//if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1
    	Integer* baseAsInteger = (Integer *) base;
        base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);
        Integer* one = new Integer(1);
        exponent->setDenominator(one);
    }
    this->exnu = new Integer(exponent->getNumerator());
    if (canExponentiate()) {
    	exponentiate();
    }
}
Exponential::~Exponential(){

}

bool Exponential::canExponentiate() {
    if(base->type == "euler"){
        return false;

    }else if(base->type == "exponential"){
	Exponential* ex = (Exponential *) base;
	this->exponent->multiply(ex->getExponent());
	Integer* numSum = new Integer (1);
	ex->getExponent()->setNumerator(numSum);
        return false;
        // false is returned because the base itself would have already been exponentiated if it were possible

    }else if(base->type == "integer"){
        return true;

    }else if(base->type == "logarithm"){
        return false;

    }else if(base->type == "nthRoot"){
	nthRoot* nr = (nthRoot *) base;
	Rational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator());
	//makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one
	this->exponent = r;
	nr->setRoot(1);
	return false;

    }else if(base->type == "pi"){
        return false;

    }else if(base->type == "rational"){
        Rational* r = (Rational *) base;
        if (r->geteNumerator()->type == "integer" && r->geteDenominator()->type == "integer") {
          Exponential* nu = new Exponential(r->geteNumerator(), this->exponent);
          r->setNumerator(nu);
          Exponential* de = new Exponential(r->geteDenominator(), this->exponent);
          r->setDenominator(de);
        }

    }else{
        cout << "type not recognized" << endl;
    }
    return false;
}

void Exponential::exponentiate(){

    Expression* constantBase = base;
    if (this->exponent->getNumerator()==0) {
        Integer* oneInt = new Integer(1);
        Rational* oneRat = new Rational(1, 1);
       this->exponent=oneRat;
       this->base=oneInt;

    }
    bool toFlip = false;
    if (exnu->getValue()<0) {
	    exnu->setValue(exnu->getValue()*-1);
            toFlip = true;
            //handles negative exponents
    }
    while (exponent->getNumerator()>1)
    	{
        base->multiply(constantBase);
        Integer* one = new Integer(1);
        exponent->setNumerator(exponent->geteNumerator()->subtract(one));     //Error: cannot initialize a parameter of type 'Expression *' with an rvalue of type 'int'
    }
    if (toFlip) {
        Integer* one = new Integer(1);
        Rational* mouse = new Rational(one, base);
    	base = mouse;
    }

}

Expression* Exponential::add(Expression* a){
    if(a->type == "euler"){

    }else if(a->type == "exponential"){
	Exponential* ex = (Exponential *) a;
	if (ex->getBase()==this->base) {
		if (ex->getExponent()==this->exponent) {
			Integer* two = new Integer(2);
			this->multiply(two);
		}
	}

    }else if(a->type == "integer"){

    }else if(a->type == "logarithm"){

    }else if(a->type == "nthRoot"){

    }else if(a->type == "pi"){

    }else if(a->type == "rational"){

    }else{
        cout << "type not recognized" << endl;
    }
    return this;
}
Expression* Exponential::subtract(Expression* a){
    if(a->type == "euler"){

    }else if(a->type == "exponential"){
	Exponential* ex = (Exponential *) a;
	if (ex->getBase()==this->base) {
		if (ex->getExponent()==this->exponent) {
			Integer* zero = new Integer(0);
			this->multiply(zero);
		}
	}
    }else if(a->type == "integer"){

    }else if(a->type == "logarithm"){

    }else if(a->type == "nthRoot"){

    }else if(a->type == "pi"){

    }else if(a->type == "rational"){

    }else{
        cout << "type not recognized" << endl;
    }
    return this;
}
Expression* Exponential::multiply(Expression* a){
    if(a->type == "euler"){

    }else if(a->type == "exponential"){
	Exponential* ex = (Exponential *) a;
	if (this->base == ex->getBase()) {
		this->exponent->add(ex->getExponent());
	}

    }else if(a->type == "integer"){

    }else if(a->type == "logarithm"){

    }else if(a->type == "nthRoot"){

    }else if(a->type == "pi"){

    }else if(a->type == "rational"){
	Rational* r = (Rational *) a;
	r->setNumerator(r->geteNumerator()->multiply(this));        //Error: expected expression
	return r;

    }else{
        cout << "type not recognized" << endl;
    }
    return this;
}
Expression* Exponential::divide(Expression* a){
    if(a->type == "euler"){

    }else if(a->type == "exponential"){
	Exponential* ex = (Exponential *) a;
	if (this->base == ex->getBase()) {
		this->exponent->subtract(ex->getExponent());
	}

    }else if(a->type == "integer"){

    }else if(a->type == "logarithm"){

    }else if(a->type == "nthRoot"){

    }else if(a->type == "pi"){

    }else if(a->type == "rational"){
	Rational* r = (Rational *) a;
	r->setDenominator(r->geteDenominator()->multiply(this));      //Error: member reference type 'int' is not a pointer
	return r;

    }else{
        cout << "type not recognized" << endl;
    }
    return this;
}

Rational* Exponential::getExponent() {
    return exponent;
}

Expression* Exponential::getBase() {
    return base;
}

Integer* Exponential::getExnu() {
	return exnu;
}

Integer* Exponential::getExde() {
	return exde;
}

void Exponential::setExnu(Integer* n) {
	exnu = n;
}

void Exponential::setExde(Integer* n) {
	exde = n;
}

void Exponential::setExponent(Rational* e) {
    exponent = e;
}

void Exponential::setBase(Expression* e) {
    base = e;
}

string Exponential::toString() {
    stringstream str;
    str << base << "^" << exponent;
    return str.str();
}

ostream& Exponential::print(std::ostream& output) const{
    output << this->base << this->exponent; //overload cout so that it makes sense
    return output;
}
<|endoftext|>


<commit_before>#include "SwarmGLFacade.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "shader.hpp"
#include "Grid.h"
#include "objects.hpp"
#include "Globals.h"
#include <time.h>

#if __cplusplus >=199711L
    #include "GlobalsLoader.h"
#endif

SwarmGLFacade::SwarmGLFacade(void) {
    #if __cplusplus >=199711L
        GlobalsLoader::loadGlobals();
    #endif
	this->init();
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    programID = LoadShaders("TransformVertexShader.vertexshader", "ColorFragmentShader.fragmentshader");
    glUseProgram(programID);
	this->start();
}

void SwarmGLFacade::init() {
    initGLFW();
	initGLEW();
}

void SwarmGLFacade::initGLFW() {
	if (!glfwInit()) {
        fprintf(stderr, "Failed to initialize GLFW\n");
        exit(EXIT_FAILURE);
    }
#ifdef __APPLE__ || __MACH__
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwSetErrorCallback(SwarmGLFacade::error_callback);
#endif
	glfwSetErrorCallback(SwarmGLFacade::error_callback);
	window = glfwCreateWindow(1024, 768, "SwarmGL", NULL, NULL);
    if (!window) {
        glfwTerminate();
		fprintf(stderr, "Failed to initialize GLFW\n");
        assert(false);
    }
    glfwMakeContextCurrent(window);
}

void SwarmGLFacade::initGLEW() {
	glewExperimental = true; // Needed for core profile
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
		assert(false);
    }
}

void SwarmGLFacade::start() {
	Grid* grid = new Grid(DIMENSION_LENGTH);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0,
		      3,
		      GL_FLOAT,
		      GL_FALSE,
		      0,
		      (void*) 0);

    View = glm::lookAt(glm::vec3(0,0,17), // Camera is at (0,0,17), in World Space
                       glm::vec3(0,0,0),  // and looks at the origin
                       glm::vec3(0,1,0)); // Head is up (set to 0,-1,0 to look upside-down)
    Model = glm::mat4(1.0f);
    int iteration_count = 0;
    while(!glfwWindowShouldClose(window))
	{

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        #if __cplusplus >=199711L
            iteration_count++;
            if (iteration_count == 100) {
                iteration_count = 0;
                GlobalsLoader::loadGlobals();
            }
        #endif
		Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
		grid->moveParticles();
		grid->clearQuadrants();
		grid->registerParticles();
		sendMVP();
		grid->applyInfluenceVectors();
		grid->drawParticles();
		glfwSwapBuffers(window);
        glfwPollEvents();
		glEnable(GL_DEPTH_TEST);
		glDepthFunc(GL_LESS);
        grid->clearParticleBuffers();
	}
}

void SwarmGLFacade::sendMVP()
{
	glm::mat4 MVP = Projection * View * Model;
	glUniformMatrix4fv(glGetUniformLocation(programID, "MVP"), 1, GL_FALSE, &MVP[0][0]);
}

SwarmGLFacade::~SwarmGLFacade(void)
{
	delete window;

}
<commit_msg>Checks now if c++11 is available. If not, GlobalsLoader is disabled<commit_after>#include "SwarmGLFacade.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "shader.hpp"
#include "Grid.h"
#include "objects.hpp"
#include "Globals.h"
#include <time.h>

#if __cplusplus >=201103L
    #include "GlobalsLoader.h"
#endif

SwarmGLFacade::SwarmGLFacade(void) {
    #if __cplusplus >=201103L
        GlobalsLoader::loadGlobals();
    #endif
	this->init();
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    programID = LoadShaders("TransformVertexShader.vertexshader", "ColorFragmentShader.fragmentshader");
    glUseProgram(programID);
	this->start();
}

void SwarmGLFacade::init() {
    initGLFW();
	initGLEW();
}

void SwarmGLFacade::initGLFW() {
	if (!glfwInit()) {
        fprintf(stderr, "Failed to initialize GLFW\n");
        exit(EXIT_FAILURE);
    }
#ifdef __APPLE__ || __MACH__
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwSetErrorCallback(SwarmGLFacade::error_callback);
#endif
	glfwSetErrorCallback(SwarmGLFacade::error_callback);
	window = glfwCreateWindow(1024, 768, "SwarmGL", NULL, NULL);
    if (!window) {
        glfwTerminate();
		fprintf(stderr, "Failed to initialize GLFW\n");
        assert(false);
    }
    glfwMakeContextCurrent(window);
}

void SwarmGLFacade::initGLEW() {
	glewExperimental = true; // Needed for core profile
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Failed to initialize GLEW\n");
		assert(false);
    }
}

void SwarmGLFacade::start() {
	Grid* grid = new Grid(DIMENSION_LENGTH);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0,
		      3,
		      GL_FLOAT,
		      GL_FALSE,
		      0,
		      (void*) 0);

    View = glm::lookAt(glm::vec3(0,0,17), // Camera is at (0,0,17), in World Space
                       glm::vec3(0,0,0),  // and looks at the origin
                       glm::vec3(0,1,0)); // Head is up (set to 0,-1,0 to look upside-down)
    Model = glm::mat4(1.0f);
    int iteration_count = 0;
    while(!glfwWindowShouldClose(window))
	{

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        #if __cplusplus >=201103L
            iteration_count++;
            if (iteration_count == 100) {
                iteration_count = 0;
                GlobalsLoader::loadGlobals();
            }
        #endif
		Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
		grid->moveParticles();
		grid->clearQuadrants();
		grid->registerParticles();
		sendMVP();
		grid->applyInfluenceVectors();
		grid->drawParticles();
		glfwSwapBuffers(window);
        glfwPollEvents();
		glEnable(GL_DEPTH_TEST);
		glDepthFunc(GL_LESS);
        grid->clearParticleBuffers();
	}
}

void SwarmGLFacade::sendMVP()
{
	glm::mat4 MVP = Projection * View * Model;
	glUniformMatrix4fv(glGetUniformLocation(programID, "MVP"), 1, GL_FALSE, &MVP[0][0]);
}

SwarmGLFacade::~SwarmGLFacade(void)
{
	delete window;

}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.H $        */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,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_getecid.H
///
/// @brief Get ECID string from target using SCOM
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@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     : SBE
//------------------------------------------------------------------------------

#ifndef _GETECID_H_
#define _GETECID_H_

#include <fapi2.H>

enum P9_GETECID_Public_Constants
{
    p9_getecid_fuseString_len = 192,       // fuse string length
};

typedef fapi2::ReturnCode (*p9_getecid_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
        fapi2::variable_buffer& fuseString);

/// @brief Get ECID string from target using SCOM
///
/// @param[in]     i_target_chip   Reference to TARGET_TYPE_PROC_CHIP target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
    fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
                                 fapi2::variable_buffer& o_fuseString);
}

#endif
<commit_msg>Update hardware procedure metadata<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.H $        */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,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_getecid.H
///
/// @brief Get ECID string from target using SCOM
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@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           : 3
// *HWP Consumed by     : SBE
//------------------------------------------------------------------------------

#ifndef _GETECID_H_
#define _GETECID_H_

#include <fapi2.H>

enum P9_GETECID_Public_Constants
{
    p9_getecid_fuseString_len = 192,       // fuse string length
};

typedef fapi2::ReturnCode (*p9_getecid_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&,
        fapi2::variable_buffer& fuseString);

/// @brief Get ECID string from target using SCOM
///
/// @param[in]     i_target_chip   Reference to TARGET_TYPE_PROC_CHIP target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
    fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip,
                                 fapi2::variable_buffer& o_fuseString);
}

#endif
<|endoftext|>


<commit_before>#include <Riostream.h>
#include "TVirtualMCApplication.h"
#include "TGeoMaterial.h"
#include "TGeoManager.h"
#include <TParticle.h>
#include "TFlukaCerenkov.h"

#include "TFluka.h"
#include "TFlukaCodes.h"

#include "Fdimpar.h"  //(DIMPAR) fluka include
#include "Ftrackr.h"  //(TRACKR) fluka common
#include "Fltclcm.h"  //(LTCLCM) fluka common
#include "Fpaprop.h"  //(PAPROP) fluka common

#ifndef WIN32
# define endraw endraw_
#else
# define endraw ENDRAW
#endif
extern "C" {
void endraw(Int_t& icode, Int_t& mreg, Double_t& rull, Double_t& xsco, Double_t& ysco, Double_t& zsco)
{
  TFluka* fluka = (TFluka*) gMC;
  // nothing to do if particle in dummy region
  if (mreg == fluka->GetDummyRegion()) return;
  Int_t verbosityLevel = fluka->GetVerbosityLevel();
  Bool_t debug = (verbosityLevel >= 3)? kTRUE : kFALSE;
  Int_t mlttc = (icode==kKASKADinelarecoil) ? TRACKR.lt2trk : TRACKR.lt1trk; //LTCLCM.mlatm1;
  fluka->SetCaller(kENDRAW);
  fluka->SetRull(rull);
  fluka->SetXsco(xsco);
  fluka->SetYsco(ysco);
  fluka->SetZsco(zsco);
  fluka->SetMreg(mreg, mlttc);

  Float_t edep = rull;
  Int_t ipt = fluka->PDGFromId(TRACKR.jtrack);
  if (ipt == -1) {
      if (debug) printf("Unknown particle %5d %5d \n", TRACKR.jtrack, icode);
      return;
  }

  if (TRACKR.jtrack == -1) {
  // Handle quantum efficiency the G3 way
      if (debug) printf("endraw: Cerenkov photon depositing energy: %d %e\n", mreg, rull);
      TGeoMaterial* material = (gGeoManager->GetCurrentVolume())->GetMaterial();
      TFlukaCerenkov*  cerenkov = dynamic_cast<TFlukaCerenkov*> (material->GetCerenkovProperties());
      if (cerenkov) {
          Double_t eff = (cerenkov->GetQuantumEfficiency(rull));
          if (gRandom->Rndm() > eff) {
              edep = 0.;
          }
      }
  }

  TVirtualMCStack* cppstack = fluka->GetStack();

  if (debug) {
     cout << "ENDRAW For icode=" << icode
          << " track=" << TRACKR.ispusr[mkbmx2-1] << " pdg=" << fluka->PDGFromId(TRACKR.jtrack)
          << " edep="<< edep << " mreg=" << mreg << endl;
  }

    // check region lattice consistency (debug Ernesto)
    // *****************************************************
    Int_t nodeId;
    Int_t volId = fluka->CurrentVolID(nodeId);
    Int_t crtlttc = gGeoManager->GetCurrentNodeId()+1;
    if(debug && mreg != volId  && !gGeoManager->IsOutside() ) {
       cout << "  endraw:   track=" << TRACKR.ispusr[mkbmx2-1] << " pdg=" << fluka->PDGFromId(TRACKR.jtrack)
            << " icode=" << icode << " gNstep=" << fluka->GetNstep() << endl
            << "               fluka   mreg=" << mreg << " mlttc=" << mlttc << endl
            << "               TGeo   volId=" << volId << " crtlttc=" << crtlttc << endl
            << "     common TRACKR   lt1trk=" << TRACKR.lt1trk << " lt2trk=" << TRACKR.lt2trk << endl
            << "     common LTCLCM   newlat=" << LTCLCM.newlat << " mlatld=" <<  LTCLCM.mlatld << endl
            << "                     mlatm1=" << LTCLCM.mlatm1 << " mltsen=" <<  LTCLCM.mltsen << endl
            << "                     mltsm1=" << LTCLCM.mltsm1 << " mlattc=" << LTCLCM.mlattc << endl;
        if( mlttc == crtlttc ) cout << "   *************************************************************" << endl;
    }
    // *****************************************************
  if (icode != kEMFSCOstopping1 && icode != kEMFSCOstopping2) {
      fluka->SetIcode((FlukaProcessCode_t)icode);
      fluka->SetRull(edep);
      if (icode == kKASKADelarecoil && TRACKR.ispusr[mkbmx2-5]) {
	  //  Elastic recoil and in stuprf npprmr > 0,
	  //  the secondary being loaded is actually still the interacting particle
	  cppstack->SetCurrentTrack( TRACKR.ispusr[mkbmx2-4] );
      } else {
          cppstack->SetCurrentTrack(TRACKR.ispusr[mkbmx2-1] );
      }

      (TVirtualMCApplication::Instance())->Stepping();

  } else {
  //
  // For icode 21,22 the particle has fallen below thresshold.
  // This has to be signalled to the StepManager()
  //
      cppstack->SetCurrentTrack( TRACKR.ispusr[mkbmx2-1] );
      fluka->SetRull(edep);
      fluka->SetIcode((FlukaProcessCode_t) icode);
      (TVirtualMCApplication::Instance())->Stepping();
      fluka->SetTrackIsNew(kFALSE);
      fluka->SetIcode((FlukaProcessCode_t)icode);
      fluka->SetRull(0.);
      (TVirtualMCApplication::Instance())->Stepping();
  }
} // end of endraw
} // end of extern "C"

<commit_msg>No double step.<commit_after>#include <Riostream.h>
#include "TVirtualMCApplication.h"
#include "TGeoMaterial.h"
#include "TGeoManager.h"
#include <TParticle.h>
#include "TFlukaCerenkov.h"

#include "TFluka.h"
#include "TFlukaCodes.h"

#include "Fdimpar.h"  //(DIMPAR) fluka include
#include "Ftrackr.h"  //(TRACKR) fluka common
#include "Fltclcm.h"  //(LTCLCM) fluka common
#include "Fpaprop.h"  //(PAPROP) fluka common

#ifndef WIN32
# define endraw endraw_
#else
# define endraw ENDRAW
#endif
extern "C" {
void endraw(Int_t& icode, Int_t& mreg, Double_t& rull, Double_t& xsco, Double_t& ysco, Double_t& zsco)
{
  TFluka* fluka = (TFluka*) gMC;
  // nothing to do if particle in dummy region
  if (mreg == fluka->GetDummyRegion()) return;
  Int_t verbosityLevel = fluka->GetVerbosityLevel();
  Bool_t debug = (verbosityLevel >= 3)? kTRUE : kFALSE;
  Int_t mlttc = (icode==kKASKADinelarecoil) ? TRACKR.lt2trk : TRACKR.lt1trk; //LTCLCM.mlatm1;
  fluka->SetCaller(kENDRAW);
  fluka->SetRull(rull);
  fluka->SetXsco(xsco);
  fluka->SetYsco(ysco);
  fluka->SetZsco(zsco);
  fluka->SetMreg(mreg, mlttc);

  Float_t edep = rull;
  Int_t ipt = fluka->PDGFromId(TRACKR.jtrack);
  if (ipt == -1) {
      if (debug) printf("Unknown particle %5d %5d \n", TRACKR.jtrack, icode);
      return;
  }

  if (TRACKR.jtrack == -1) {
  // Handle quantum efficiency the G3 way
      if (debug) printf("endraw: Cerenkov photon depositing energy: %d %e\n", mreg, rull);
      TGeoMaterial* material = (gGeoManager->GetCurrentVolume())->GetMaterial();
      TFlukaCerenkov*  cerenkov = dynamic_cast<TFlukaCerenkov*> (material->GetCerenkovProperties());
      if (cerenkov) {
          Double_t eff = (cerenkov->GetQuantumEfficiency(rull));
          if (gRandom->Rndm() > eff) {
              edep = 0.;
          }
      }
  }

  TVirtualMCStack* cppstack = fluka->GetStack();

  if (debug) {
     cout << "ENDRAW For icode=" << icode
          << " track=" << TRACKR.ispusr[mkbmx2-1] << " pdg=" << fluka->PDGFromId(TRACKR.jtrack)
          << " edep="<< edep << " mreg=" << mreg << endl;
  }

    // check region lattice consistency (debug Ernesto)
    // *****************************************************
    Int_t nodeId;
    Int_t volId = fluka->CurrentVolID(nodeId);
    Int_t crtlttc = gGeoManager->GetCurrentNodeId()+1;
    if(debug && mreg != volId  && !gGeoManager->IsOutside() ) {
       cout << "  endraw:   track=" << TRACKR.ispusr[mkbmx2-1] << " pdg=" << fluka->PDGFromId(TRACKR.jtrack)
            << " icode=" << icode << " gNstep=" << fluka->GetNstep() << endl
            << "               fluka   mreg=" << mreg << " mlttc=" << mlttc << endl
            << "               TGeo   volId=" << volId << " crtlttc=" << crtlttc << endl
            << "     common TRACKR   lt1trk=" << TRACKR.lt1trk << " lt2trk=" << TRACKR.lt2trk << endl
            << "     common LTCLCM   newlat=" << LTCLCM.newlat << " mlatld=" <<  LTCLCM.mlatld << endl
            << "                     mlatm1=" << LTCLCM.mlatm1 << " mltsen=" <<  LTCLCM.mltsen << endl
            << "                     mltsm1=" << LTCLCM.mltsm1 << " mlattc=" << LTCLCM.mlattc << endl;
        if( mlttc == crtlttc ) cout << "   *************************************************************" << endl;
    }
    // *****************************************************
  if (icode != kEMFSCOstopping1 && icode != kEMFSCOstopping2) {
      fluka->SetIcode((FlukaProcessCode_t)icode);
      fluka->SetRull(edep);
      if (icode == kKASKADelarecoil && TRACKR.ispusr[mkbmx2-5]) {
	  //  Elastic recoil and in stuprf npprmr > 0,
	  //  the secondary being loaded is actually still the interacting particle
	  cppstack->SetCurrentTrack( TRACKR.ispusr[mkbmx2-4] );
      } else {
          cppstack->SetCurrentTrack(TRACKR.ispusr[mkbmx2-1] );
      }

      (TVirtualMCApplication::Instance())->Stepping();

  } else {
  //
  // For icode 21,22 the particle has fallen below thresshold.
  // This has to be signalled to the StepManager()
  //
      cppstack->SetCurrentTrack( TRACKR.ispusr[mkbmx2-1] );
      fluka->SetRull(edep);
      fluka->SetIcode((FlukaProcessCode_t) icode);
      (TVirtualMCApplication::Instance())->Stepping();
      fluka->SetTrackIsNew(kFALSE);
//      fluka->SetIcode((FlukaProcessCode_t)icode);
//      fluka->SetRull(0.);
//      (TVirtualMCApplication::Instance())->Stepping();
  }
} // end of endraw
} // end of extern "C"

<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#include "QmitkXnatEditor.h"

// Qmitk
#include "QmitkXnatObjectEditorInput.h"
#include "org_mitk_gui_qt_xnatinterface_Activator.h"

// CTK XNAT Core
#include "ctkXnatObject.h"
#include "ctkXnatDataModel.h"
#include "ctkXnatScanResource.h"
#include "ctkXnatFile.h"

// CTK XNAT Widgets
#include "ctkXnatListModel.h"

// Blueberry
#include <berryQModelIndexObject.h>
#include <berryIWorkbenchPage.h>

// Qt
#include <QListView>
#include <QRegExp>
#include <QModelIndex>
#include <QDir>

// MITK
#include <mitkDataStorage.h>
#include <mitkIOUtil.h>

const std::string QmitkXnatEditor::EDITOR_ID = "org.mitk.editors.xnat.browser";

QmitkXnatEditor::QmitkXnatEditor() :
  m_DataStorageServiceTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()),
  m_Session(0),
  m_ListModel(new ctkXnatListModel()),
  m_SelectionListener(new berry::SelectionChangedAdapter<QmitkXnatEditor>(this, &QmitkXnatEditor::SelectionChanged)),
  m_DownloadPath(berry::Platform::GetServiceRegistry().
    GetServiceById<berry::IPreferencesService>(berry::IPreferencesService::ID)->
    GetSystemPreferences()->Node("/XnatConnection")->Get("Download Path", "").c_str())
{
  m_DataStorageServiceTracker.open();
  if(m_DownloadPath.isEmpty())
  {
    QString xnatFolder = "XNAT_DOWNLOADS";
    QDir dir(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()->getDataFile("").absoluteFilePath());
    dir.mkdir(xnatFolder);
    dir.setPath(dir.path() + "/" + xnatFolder);
    m_DownloadPath = dir.path() + "/";
  }
}

QmitkXnatEditor::~QmitkXnatEditor()
{
  delete m_ListModel;
  berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService();
  s->RemoveSelectionListener(m_SelectionListener);
  m_DataStorageServiceTracker.close();
}

bool QmitkXnatEditor::IsDirty() const
{
  return false;
}

bool QmitkXnatEditor::IsSaveAsAllowed() const
{
  return false;
}

void QmitkXnatEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input)
{
  this->SetInput(input);
  this->SetSite(site);
}

void QmitkXnatEditor::DoSave()
{
}

void QmitkXnatEditor::DoSaveAs()
{
}

void QmitkXnatEditor::SetInput(berry::IEditorInput::Pointer input)
{
  // If the input is not a QmitkXnatObjectEditorInput the semi global xnat session will be loaded.
  QmitkXnatObjectEditorInput::Pointer oPtr = input.Cast<QmitkXnatObjectEditorInput>();
  if(oPtr.IsNotNull())
  {
    SetInputWithNotify(oPtr);
    this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch();
  }
  else
  {
    m_Session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatConnectionManager()->GetXnatConnection();

    if(m_Session == 0)
    {
      MITK_INFO << "Please check your XNAT Connection Preferences!";
      return;
    }

    QmitkXnatObjectEditorInput::Pointer xoPtr = QmitkXnatObjectEditorInput::New( m_Session->dataModel() );
    berry::IEditorInput::Pointer editorInput( xoPtr );
    SetInputWithNotify(editorInput);
    this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch();
  }
}

void QmitkXnatEditor::SetFocus()
{
}

void QmitkXnatEditor::CreateQtPartControl( QWidget *parent )
{
  // create GUI widgets from the Qt Designer's .ui file
  m_Controls.setupUi( parent );
  m_Controls.treeView->setModel(m_ListModel);

  GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener);

  connect( m_Controls.treeView, SIGNAL(activated(const QModelIndex&)), this, SLOT(OnObjectActivated(const QModelIndex&)) );

  connect( m_Controls.buttonDownloadResource, SIGNAL(clicked()), this, SLOT(DownloadResource()) );
  connect( m_Controls.buttonDownloadFile, SIGNAL(clicked()), this, SLOT(DownloadFile()) );
  connect( m_Controls.buttonDataModel, SIGNAL(clicked()), this, SLOT(OnDataModelButtonClicked()) );
  connect( m_Controls.buttonProject, SIGNAL(clicked()), this, SLOT(OnProjectButtonClicked()) );
  connect( m_Controls.buttonSubject, SIGNAL(clicked()), this, SLOT(OnSubjectButtonClicked()) );
  connect( m_Controls.buttonExperiment, SIGNAL(clicked()), this, SLOT(OnExperimentButtonClicked()) );
  connect( m_Controls.buttonKindOfData, SIGNAL(clicked()), this, SLOT(OnKindOfDataButtonClicked()) );
  connect( m_Controls.buttonSession, SIGNAL(clicked()), this, SLOT(OnSessionButtonClicked()) );
  connect( m_Controls.buttonResource, SIGNAL(clicked()), this, SLOT(OnResourceButtonClicked()) );

  // Makes the breadcrumb feature invisible
  for(int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count()-1; i++)
  {
    QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i);
    child->widget()->setVisible(false);
  }
  for(int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count()-1; i++)
  {
    QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i);
    child->widget()->setVisible(false);
  }
  UpdateList();
}

void QmitkXnatEditor::UpdateList()
{
  QmitkXnatObjectEditorInput::Pointer xoPtr(GetEditorInput().Cast<QmitkXnatObjectEditorInput>());
  if( xoPtr.IsNull() )
    return;
  ctkXnatObject* inputObject = xoPtr->GetXnatObject();
  if( inputObject == NULL )
    return;
  m_ListModel->setRootObject( inputObject );
  m_Controls.treeView->reset();

  // recursive method to check parents of the inputObject
  m_ParentCount = ParentChecker(inputObject);

  // breadcrumb labels
  for(int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count()-1; i++)
  {
    QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i);
    child->widget()->setVisible(false);
  }
  for(int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count()-1; i++)
  {
    QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i);
    child->widget()->setVisible(false);
  }

  ctkXnatObject* parent = NULL;
  for(int i = m_ParentCount*2; i >= 0; i--)
  {
    if(i > 12)
      break;
    m_Controls.breadcrumbDescriptionLayout->itemAt(i)->widget()->setVisible(true);
    QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i);
    child->widget()->setVisible(true);
    if(i>0)
    {
      m_Controls.breadcrumbHorizontalLayout->itemAt(i-1)->widget()->setVisible(true);
      m_Controls.breadcrumbDescriptionLayout->itemAt(i-1)->widget()->setVisible(true);
    }
    if(parent == NULL)
    {
      parent = inputObject;
    }
    // make breadcrumb button
    QPushButton* breadcrumbButton = dynamic_cast<QPushButton*>(child->widget());
    breadcrumbButton->setText(parent->id());
    parent = parent->parent();
    i--;
  }
}

void QmitkXnatEditor::SelectionChanged(berry::IWorkbenchPart::Pointer sourcepart,
                               berry::ISelection::ConstPointer selection)
{
  // check for null selection
  if (selection.IsNull())
  {
    return;
  }
  // exclude own selection events and check whether this kind of selection can be handled
  if (sourcepart != this &&
      selection.Cast<const berry::IStructuredSelection>())
  {
    berry::IStructuredSelection::ConstPointer currentSelection = selection.Cast<const berry::IStructuredSelection>();
    // iterates over the selection
    for (berry::IStructuredSelection::iterator itr = currentSelection->Begin();
         itr != currentSelection->End(); ++itr)
    {
      if (berry::SmartPointer<berry::QModelIndexObject> objectPointer = itr->Cast<berry::QModelIndexObject>())
      {
        // get object of selected ListWidgetElement
        ctkXnatObject* object = objectPointer->GetQModelIndex().data(Qt::UserRole).value<ctkXnatObject*>();

        // if a file is selected, don't change the input and list view
        if ( dynamic_cast<ctkXnatFile*>(object) == NULL ){
          QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( object );
          berry::IEditorInput::Pointer editorInput( oPtr );
          if ( !(editorInput == this->GetEditorInput()) )
            this->SetInput(editorInput);

          UpdateList();
        }
      }
    }
  }
}

void QmitkXnatEditor::DownloadResource()
{
  if (!m_Controls.treeView->selectionModel()->hasSelection())
    return;

  const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex();
  QVariant variant = m_ListModel->data(index, Qt::UserRole);
  if ( variant.isValid() )
  {
    ctkXnatScanResource* resource = dynamic_cast<ctkXnatScanResource*>(variant.value<ctkXnatObject*>());
    if (resource != NULL)
    {
      MITK_INFO << "Download started ...";
      MITK_INFO << "...";
      QString resourcePath = m_DownloadPath + resource->id() + ".zip";
      resource->download(resourcePath);

      // Testing if the path exists
      QDir downDir(m_DownloadPath);
      if( downDir.exists(resource->id() + ".zip") )
      {
        MITK_INFO << "Download of " << resource->id().toStdString() << ".zip was completed!";
      }
      else
      {
        MITK_INFO << "Download of " << resource->id().toStdString() << ".zip failed!";
      }
    }
    else
    {
      MITK_INFO << "Selection was not a resource folder!";
    }
  }
}

void QmitkXnatEditor::DownloadFile()
{
  if (!m_Controls.treeView->selectionModel()->hasSelection())
    return;
  const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex();
  InternalFileDownload(index);
}

void QmitkXnatEditor::ToHigherLevel()
{
  ctkXnatObject* parent = GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->parent();
  if( parent ==  NULL)
  {
    return;
  }
  QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( parent );
  berry::IEditorInput::Pointer editorInput( oPtr );
  SetInput(editorInput);
  UpdateList();
}

void QmitkXnatEditor::OnObjectActivated(const QModelIndex &index)
{
  if (!index.isValid()) return;

  ctkXnatObject* child = GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->children().at(index.row());
  if( child != NULL )
  {
    ctkXnatFile* file = dynamic_cast<ctkXnatFile*>(child);
    if( file != NULL )
    {
      // Download file and put into datamanager
      InternalFileDownload(index);
      mitk::IDataStorageService* dsService = m_DataStorageServiceTracker.getService();
      if(dsService != NULL)
      {
        mitk::DataNode::Pointer node = mitk::IOUtil::LoadDataNode((m_DownloadPath + file->id()).toStdString());
        if ( ( node.IsNotNull() ) && ( node->GetData() != NULL ) )
        {
          dsService->GetDataStorage()->GetDataStorage()->Add(node);
          mitk::BaseData::Pointer basedata = node->GetData();
          mitk::RenderingManager::GetInstance()->InitializeViews(
            basedata->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true );
        }
      }
    }
    else
    {
      // Updates the root item
      QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( child );
      berry::IEditorInput::Pointer editorInput( oPtr );
      SetInput(editorInput);

      this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch();

      UpdateList();
    }
  }

}

void QmitkXnatEditor::InternalFileDownload(const QModelIndex& index)
{
  QVariant variant = m_ListModel->data(index, Qt::UserRole);
  if ( variant.isValid() )
  {
    ctkXnatFile* file = dynamic_cast<ctkXnatFile*>(variant.value<ctkXnatObject*>());
    if (file != NULL)
    {
      MITK_INFO << "Download started ...";
      MITK_INFO << "...";
      QString filePath = m_DownloadPath + file->id();
      file->download(filePath);

      // Testing if the file exists
      QDir downDir(m_DownloadPath);
      if( downDir.exists(file->id()) )
      {
        MITK_INFO << "Download of " << file->id().toStdString() << " was completed!";
      }
      else
      {
        MITK_INFO << "Download of " << file->id().toStdString() << " failed!";
      }
    }
    else
    {
      MITK_INFO << "Selection was not a file!";
    }
  }
}

int QmitkXnatEditor::ParentChecker(ctkXnatObject* child)
{
  int sum;
  if( child->parent() == NULL )
  {
    return 0;
  }
  else
  {
    sum = 1 + ParentChecker(child->parent());
  }
  return sum;
}

void QmitkXnatEditor::OnDataModelButtonClicked()
{
  for(int i = m_ParentCount; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnProjectButtonClicked()
{
  for(int i = m_ParentCount-1; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnSubjectButtonClicked()
{
  for(int i = m_ParentCount-2; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnExperimentButtonClicked()
{
  for(int i = m_ParentCount-3; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnKindOfDataButtonClicked()
{
  for(int i = m_ParentCount-4; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnSessionButtonClicked()
{
  for(int i = m_ParentCount-5; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnResourceButtonClicked()
{
  for(int i = m_ParentCount-6; i > 0; i--)
  {
    ToHigherLevel();
  }
}
<commit_msg>COMP: Use ctkXnatResource instead of the removed ctkXnatScanResource.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

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

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

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

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

#include "QmitkXnatEditor.h"

// Qmitk
#include "QmitkXnatObjectEditorInput.h"
#include "org_mitk_gui_qt_xnatinterface_Activator.h"

// CTK XNAT Core
#include "ctkXnatObject.h"
#include "ctkXnatDataModel.h"
#include "ctkXnatResource.h"
#include "ctkXnatFile.h"

// CTK XNAT Widgets
#include "ctkXnatListModel.h"

// Blueberry
#include <berryQModelIndexObject.h>
#include <berryIWorkbenchPage.h>

// Qt
#include <QListView>
#include <QRegExp>
#include <QModelIndex>
#include <QDir>

// MITK
#include <mitkDataStorage.h>
#include <mitkIOUtil.h>

const std::string QmitkXnatEditor::EDITOR_ID = "org.mitk.editors.xnat.browser";

QmitkXnatEditor::QmitkXnatEditor() :
  m_DataStorageServiceTracker(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()),
  m_Session(0),
  m_ListModel(new ctkXnatListModel()),
  m_SelectionListener(new berry::SelectionChangedAdapter<QmitkXnatEditor>(this, &QmitkXnatEditor::SelectionChanged)),
  m_DownloadPath(berry::Platform::GetServiceRegistry().
    GetServiceById<berry::IPreferencesService>(berry::IPreferencesService::ID)->
    GetSystemPreferences()->Node("/XnatConnection")->Get("Download Path", "").c_str())
{
  m_DataStorageServiceTracker.open();
  if(m_DownloadPath.isEmpty())
  {
    QString xnatFolder = "XNAT_DOWNLOADS";
    QDir dir(mitk::org_mitk_gui_qt_xnatinterface_Activator::GetContext()->getDataFile("").absoluteFilePath());
    dir.mkdir(xnatFolder);
    dir.setPath(dir.path() + "/" + xnatFolder);
    m_DownloadPath = dir.path() + "/";
  }
}

QmitkXnatEditor::~QmitkXnatEditor()
{
  delete m_ListModel;
  berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService();
  s->RemoveSelectionListener(m_SelectionListener);
  m_DataStorageServiceTracker.close();
}

bool QmitkXnatEditor::IsDirty() const
{
  return false;
}

bool QmitkXnatEditor::IsSaveAsAllowed() const
{
  return false;
}

void QmitkXnatEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input)
{
  this->SetInput(input);
  this->SetSite(site);
}

void QmitkXnatEditor::DoSave()
{
}

void QmitkXnatEditor::DoSaveAs()
{
}

void QmitkXnatEditor::SetInput(berry::IEditorInput::Pointer input)
{
  // If the input is not a QmitkXnatObjectEditorInput the semi global xnat session will be loaded.
  QmitkXnatObjectEditorInput::Pointer oPtr = input.Cast<QmitkXnatObjectEditorInput>();
  if(oPtr.IsNotNull())
  {
    SetInputWithNotify(oPtr);
    this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch();
  }
  else
  {
    m_Session = mitk::org_mitk_gui_qt_xnatinterface_Activator::GetXnatConnectionManager()->GetXnatConnection();

    if(m_Session == 0)
    {
      MITK_INFO << "Please check your XNAT Connection Preferences!";
      return;
    }

    QmitkXnatObjectEditorInput::Pointer xoPtr = QmitkXnatObjectEditorInput::New( m_Session->dataModel() );
    berry::IEditorInput::Pointer editorInput( xoPtr );
    SetInputWithNotify(editorInput);
    this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch();
  }
}

void QmitkXnatEditor::SetFocus()
{
}

void QmitkXnatEditor::CreateQtPartControl( QWidget *parent )
{
  // create GUI widgets from the Qt Designer's .ui file
  m_Controls.setupUi( parent );
  m_Controls.treeView->setModel(m_ListModel);

  GetSite()->GetWorkbenchWindow()->GetSelectionService()->AddSelectionListener(m_SelectionListener);

  connect( m_Controls.treeView, SIGNAL(activated(const QModelIndex&)), this, SLOT(OnObjectActivated(const QModelIndex&)) );

  connect( m_Controls.buttonDownloadResource, SIGNAL(clicked()), this, SLOT(DownloadResource()) );
  connect( m_Controls.buttonDownloadFile, SIGNAL(clicked()), this, SLOT(DownloadFile()) );
  connect( m_Controls.buttonDataModel, SIGNAL(clicked()), this, SLOT(OnDataModelButtonClicked()) );
  connect( m_Controls.buttonProject, SIGNAL(clicked()), this, SLOT(OnProjectButtonClicked()) );
  connect( m_Controls.buttonSubject, SIGNAL(clicked()), this, SLOT(OnSubjectButtonClicked()) );
  connect( m_Controls.buttonExperiment, SIGNAL(clicked()), this, SLOT(OnExperimentButtonClicked()) );
  connect( m_Controls.buttonKindOfData, SIGNAL(clicked()), this, SLOT(OnKindOfDataButtonClicked()) );
  connect( m_Controls.buttonSession, SIGNAL(clicked()), this, SLOT(OnSessionButtonClicked()) );
  connect( m_Controls.buttonResource, SIGNAL(clicked()), this, SLOT(OnResourceButtonClicked()) );

  // Makes the breadcrumb feature invisible
  for(int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count()-1; i++)
  {
    QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i);
    child->widget()->setVisible(false);
  }
  for(int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count()-1; i++)
  {
    QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i);
    child->widget()->setVisible(false);
  }
  UpdateList();
}

void QmitkXnatEditor::UpdateList()
{
  QmitkXnatObjectEditorInput::Pointer xoPtr(GetEditorInput().Cast<QmitkXnatObjectEditorInput>());
  if( xoPtr.IsNull() )
    return;
  ctkXnatObject* inputObject = xoPtr->GetXnatObject();
  if( inputObject == NULL )
    return;
  m_ListModel->setRootObject( inputObject );
  m_Controls.treeView->reset();

  // recursive method to check parents of the inputObject
  m_ParentCount = ParentChecker(inputObject);

  // breadcrumb labels
  for(int i = 0; i < m_Controls.breadcrumbHorizontalLayout->count()-1; i++)
  {
    QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i);
    child->widget()->setVisible(false);
  }
  for(int i = 0; i < m_Controls.breadcrumbDescriptionLayout->count()-1; i++)
  {
    QLayoutItem* child = m_Controls.breadcrumbDescriptionLayout->itemAt(i);
    child->widget()->setVisible(false);
  }

  ctkXnatObject* parent = NULL;
  for(int i = m_ParentCount*2; i >= 0; i--)
  {
    if(i > 12)
      break;
    m_Controls.breadcrumbDescriptionLayout->itemAt(i)->widget()->setVisible(true);
    QLayoutItem* child = m_Controls.breadcrumbHorizontalLayout->itemAt(i);
    child->widget()->setVisible(true);
    if(i>0)
    {
      m_Controls.breadcrumbHorizontalLayout->itemAt(i-1)->widget()->setVisible(true);
      m_Controls.breadcrumbDescriptionLayout->itemAt(i-1)->widget()->setVisible(true);
    }
    if(parent == NULL)
    {
      parent = inputObject;
    }
    // make breadcrumb button
    QPushButton* breadcrumbButton = dynamic_cast<QPushButton*>(child->widget());
    breadcrumbButton->setText(parent->id());
    parent = parent->parent();
    i--;
  }
}

void QmitkXnatEditor::SelectionChanged(berry::IWorkbenchPart::Pointer sourcepart,
                               berry::ISelection::ConstPointer selection)
{
  // check for null selection
  if (selection.IsNull())
  {
    return;
  }
  // exclude own selection events and check whether this kind of selection can be handled
  if (sourcepart != this &&
      selection.Cast<const berry::IStructuredSelection>())
  {
    berry::IStructuredSelection::ConstPointer currentSelection = selection.Cast<const berry::IStructuredSelection>();
    // iterates over the selection
    for (berry::IStructuredSelection::iterator itr = currentSelection->Begin();
         itr != currentSelection->End(); ++itr)
    {
      if (berry::SmartPointer<berry::QModelIndexObject> objectPointer = itr->Cast<berry::QModelIndexObject>())
      {
        // get object of selected ListWidgetElement
        ctkXnatObject* object = objectPointer->GetQModelIndex().data(Qt::UserRole).value<ctkXnatObject*>();

        // if a file is selected, don't change the input and list view
        if ( dynamic_cast<ctkXnatFile*>(object) == NULL ){
          QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( object );
          berry::IEditorInput::Pointer editorInput( oPtr );
          if ( !(editorInput == this->GetEditorInput()) )
            this->SetInput(editorInput);

          UpdateList();
        }
      }
    }
  }
}

void QmitkXnatEditor::DownloadResource()
{
  if (!m_Controls.treeView->selectionModel()->hasSelection())
    return;

  const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex();
  QVariant variant = m_ListModel->data(index, Qt::UserRole);
  if ( variant.isValid() )
  {
    ctkXnatResource* resource = dynamic_cast<ctkXnatResource*>(variant.value<ctkXnatObject*>());
    if (resource != NULL)
    {
      MITK_INFO << "Download started ...";
      MITK_INFO << "...";
      QString resourcePath = m_DownloadPath + resource->id() + ".zip";
      resource->download(resourcePath);

      // Testing if the path exists
      QDir downDir(m_DownloadPath);
      if( downDir.exists(resource->id() + ".zip") )
      {
        MITK_INFO << "Download of " << resource->id().toStdString() << ".zip was completed!";
      }
      else
      {
        MITK_INFO << "Download of " << resource->id().toStdString() << ".zip failed!";
      }
    }
    else
    {
      MITK_INFO << "Selection was not a resource folder!";
    }
  }
}

void QmitkXnatEditor::DownloadFile()
{
  if (!m_Controls.treeView->selectionModel()->hasSelection())
    return;
  const QModelIndex index = m_Controls.treeView->selectionModel()->currentIndex();
  InternalFileDownload(index);
}

void QmitkXnatEditor::ToHigherLevel()
{
  ctkXnatObject* parent = GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->parent();
  if( parent ==  NULL)
  {
    return;
  }
  QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( parent );
  berry::IEditorInput::Pointer editorInput( oPtr );
  SetInput(editorInput);
  UpdateList();
}

void QmitkXnatEditor::OnObjectActivated(const QModelIndex &index)
{
  if (!index.isValid()) return;

  ctkXnatObject* child = GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->children().at(index.row());
  if( child != NULL )
  {
    ctkXnatFile* file = dynamic_cast<ctkXnatFile*>(child);
    if( file != NULL )
    {
      // Download file and put into datamanager
      InternalFileDownload(index);
      mitk::IDataStorageService* dsService = m_DataStorageServiceTracker.getService();
      if(dsService != NULL)
      {
        mitk::DataNode::Pointer node = mitk::IOUtil::LoadDataNode((m_DownloadPath + file->id()).toStdString());
        if ( ( node.IsNotNull() ) && ( node->GetData() != NULL ) )
        {
          dsService->GetDataStorage()->GetDataStorage()->Add(node);
          mitk::BaseData::Pointer basedata = node->GetData();
          mitk::RenderingManager::GetInstance()->InitializeViews(
            basedata->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true );
        }
      }
    }
    else
    {
      // Updates the root item
      QmitkXnatObjectEditorInput::Pointer oPtr = QmitkXnatObjectEditorInput::New( child );
      berry::IEditorInput::Pointer editorInput( oPtr );
      SetInput(editorInput);

      this->GetEditorInput().Cast<QmitkXnatObjectEditorInput>()->GetXnatObject()->fetch();

      UpdateList();
    }
  }

}

void QmitkXnatEditor::InternalFileDownload(const QModelIndex& index)
{
  QVariant variant = m_ListModel->data(index, Qt::UserRole);
  if ( variant.isValid() )
  {
    ctkXnatFile* file = dynamic_cast<ctkXnatFile*>(variant.value<ctkXnatObject*>());
    if (file != NULL)
    {
      MITK_INFO << "Download started ...";
      MITK_INFO << "...";
      QString filePath = m_DownloadPath + file->id();
      file->download(filePath);

      // Testing if the file exists
      QDir downDir(m_DownloadPath);
      if( downDir.exists(file->id()) )
      {
        MITK_INFO << "Download of " << file->id().toStdString() << " was completed!";
      }
      else
      {
        MITK_INFO << "Download of " << file->id().toStdString() << " failed!";
      }
    }
    else
    {
      MITK_INFO << "Selection was not a file!";
    }
  }
}

int QmitkXnatEditor::ParentChecker(ctkXnatObject* child)
{
  int sum;
  if( child->parent() == NULL )
  {
    return 0;
  }
  else
  {
    sum = 1 + ParentChecker(child->parent());
  }
  return sum;
}

void QmitkXnatEditor::OnDataModelButtonClicked()
{
  for(int i = m_ParentCount; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnProjectButtonClicked()
{
  for(int i = m_ParentCount-1; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnSubjectButtonClicked()
{
  for(int i = m_ParentCount-2; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnExperimentButtonClicked()
{
  for(int i = m_ParentCount-3; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnKindOfDataButtonClicked()
{
  for(int i = m_ParentCount-4; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnSessionButtonClicked()
{
  for(int i = m_ParentCount-5; i > 0; i--)
  {
    ToHigherLevel();
  }
}

void QmitkXnatEditor::OnResourceButtonClicked()
{
  for(int i = m_ParentCount-6; i > 0; i--)
  {
    ToHigherLevel();
  }
}
<|endoftext|>


<commit_before>/*
 * opencog/atoms/base/Node.cc
 *
 * Copyright (C) 2008-2010 OpenCog Foundation
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <stdio.h>

#include <opencog/util/Logger.h>
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/base/Link.h>
#include <opencog/atomspace/AtomTable.h>

#include "Node.h"

using namespace opencog;

void Node::init(const std::string& cname)
{
    if (not classserver().isA(_type, NODE))
    {
        throw InvalidParamException(TRACE_INFO,
            "Node - Invalid node type '%d' %s.",
            _type, classserver().getTypeName(_type).c_str());
    }
    _name = cname;
}

std::string Node::toShortString(const std::string& indent) const
{
    std::string tmpname = _name;
    if (_name == "")
        tmpname = "#" + std::to_string(_uuid);

    std::string atname;
    if (_atomTable)
        atname = std::to_string(_atomTable->get_uuid());
    else
        atname = "NULL";

    std::string nam = indent +
        "(" + classserver().getTypeName(_type) +
        " \"" + tmpname + "\") ; [" +
        std::to_string(_uuid) + "][" + atname +"]\n";
    return nam;
}

std::string Node::toString(const std::string& indent) const
{
    std::string tmpname = _name;
    if (_name == "")
        tmpname = "#" + std::to_string(_uuid);

    std::string answer = indent;

    answer += "(" + classserver().getTypeName(_type);

    answer += " \"" + tmpname + "\"";

    // Print the TV and AV only if its not the default.
    if (not getAttentionValue()->isDefaultAV())
        answer += " (av " +
             std::to_string(getAttentionValue()->getSTI()) + " " +
             std::to_string(getAttentionValue()->getLTI()) + " " +
             std::to_string(getAttentionValue()->getVLTI()) + ")";

    if (not getTruthValue()->isDefaultTV())
        answer += " " + getTruthValue()->toString();

    answer += ") ; [" +
            std::to_string(_uuid) + "][" +
            std::to_string(_atomTable? _atomTable->get_uuid() : -1) +
            "]\n";

    return answer;
}

bool Node::operator==(const Atom& other) const
{
    // Rule out obvious mis-matches, based on the hash.
    if (get_hash() != other.get_hash()) return false;

    if (getType() != other.getType()) return false;
    return getName() == other.getName();
}

bool Node::operator<(const Atom& other) const
{
    if (get_hash() < other.get_hash()) return true;
    if (other.get_hash() < get_hash()) return false;

    // We get to here only if the hashes are equal.
    // Compare the contents directly, for this
    // (hopefully rare) case.
    if (getType() == other.getType())
        return getName() < other.getName();
    else
        return getType() < other.getType();
}

ContentHash Node::compute_hash() const
{
	ContentHash hsh = std::hash<std::string>()(getName());
	hsh = hsh ^ (getType() << 23);

	// Nodes will never have the MSB set.
	ContentHash mask = ~(((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1));
	hsh &= mask;

	if (Handle::INVALID_HASH == hsh) hsh -= 1;
	_content_hash = hsh;
	return _content_hash;
}
<commit_msg>Optimize Node content compare, too.<commit_after>/*
 * opencog/atoms/base/Node.cc
 *
 * Copyright (C) 2008-2010 OpenCog Foundation
 * Copyright (C) 2002-2007 Novamente LLC
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <stdio.h>

#include <opencog/util/Logger.h>
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/base/Link.h>
#include <opencog/atomspace/AtomTable.h>

#include "Node.h"

using namespace opencog;

void Node::init(const std::string& cname)
{
    if (not classserver().isA(_type, NODE))
    {
        throw InvalidParamException(TRACE_INFO,
            "Node - Invalid node type '%d' %s.",
            _type, classserver().getTypeName(_type).c_str());
    }
    _name = cname;
}

std::string Node::toShortString(const std::string& indent) const
{
    std::string tmpname = _name;
    if (_name == "")
        tmpname = "#" + std::to_string(_uuid);

    std::string atname;
    if (_atomTable)
        atname = std::to_string(_atomTable->get_uuid());
    else
        atname = "NULL";

    std::string nam = indent +
        "(" + classserver().getTypeName(_type) +
        " \"" + tmpname + "\") ; [" +
        std::to_string(_uuid) + "][" + atname +"]\n";
    return nam;
}

std::string Node::toString(const std::string& indent) const
{
    std::string tmpname = _name;
    if (_name == "")
        tmpname = "#" + std::to_string(_uuid);

    std::string answer = indent;

    answer += "(" + classserver().getTypeName(_type);

    answer += " \"" + tmpname + "\"";

    // Print the TV and AV only if its not the default.
    if (not getAttentionValue()->isDefaultAV())
        answer += " (av " +
             std::to_string(getAttentionValue()->getSTI()) + " " +
             std::to_string(getAttentionValue()->getLTI()) + " " +
             std::to_string(getAttentionValue()->getVLTI()) + ")";

    if (not getTruthValue()->isDefaultTV())
        answer += " " + getTruthValue()->toString();

    answer += ") ; [" +
            std::to_string(_uuid) + "][" +
            std::to_string(_atomTable? _atomTable->get_uuid() : -1) +
            "]\n";

    return answer;
}

bool Node::operator==(const Atom& other) const
{
    // If other points to this, then have equality.
    if (this == &other) return true;

    // Rule out obvious mis-matches, based on the hash.
    if (get_hash() != other.get_hash()) return false;

    if (getType() != other.getType()) return false;
    return getName() == other.getName();
}

bool Node::operator<(const Atom& other) const
{
    if (get_hash() < other.get_hash()) return true;
    if (other.get_hash() < get_hash()) return false;

    // We get to here only if the hashes are equal.
    // Compare the contents directly, for this
    // (hopefully rare) case.
    if (getType() == other.getType())
        return getName() < other.getName();
    else
        return getType() < other.getType();
}

ContentHash Node::compute_hash() const
{
	ContentHash hsh = std::hash<std::string>()(getName());
	hsh = hsh ^ (getType() << 23);

	// Nodes will never have the MSB set.
	ContentHash mask = ~(((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1));
	hsh &= mask;

	if (Handle::INVALID_HASH == hsh) hsh -= 1;
	_content_hash = hsh;
	return _content_hash;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

// Generator for particles according generic functions
// For high pt performance studies realistic distribution of the particles - local density in jets to be approximated
//
//
//  TF1 *   fF1Momentum;          // 1/momentum distribution function inGeV
//  TF1 *   fFPhi;                // phi distribution function in rad     - if not set flat 0-2pi used
//  TF1 *   fFTheta;              // theta distribution function in rad   - if not set flat pi/4-3pi/4 used
//  TF3 *   fFPosition;           // position distribution function in cm - TO FIX if not set 0 used ()
//  TF1 *   fFPdg;                // pdg distribution function            - if not set flat jet pdg used
//  We assume that the moment, postion and PDG code of particles are independent
//  Only tracks/particle crossing the reference radius at given z range
//
// Origin: marian.ivanov@cern.ch

/*
  To test generator for particular setting run
  AliGenPerformance::TestAliGenPerformance(Int_t nEvents, TF1 *f1pt, TF1 *fpdg){
  For distribution of
    fF1Momentum=new TF1("f1pt","1-10*x",0,0.1);
    AliGenPerformance::TestAliGenPerformance(1000, fF1Momentum,0)
    pt distribution of charged primary particles described by powerlaw with slope -1.7

  gSystem->Load("libpythia6");
  gSystem->Load("libEGPythia6");
  gSystem->Load("liblhapdf");
  gSystem->Load("libAliPythia6");
  //
  AliGenPerformance::TestAliGenPerformance(5000,0,0);
  TFile * f = TFile::Open("testAliGenPerformance.root");
  testGener.Draw("pt>>his(100,10,100)","charge!=0&&abs(fKF)<2000","");
  f1pt = new TF1("f1pt","1/(0.01+x)",0,0.1);
  his->Fit(f1);

*/

#include <TParticle.h>
#include <TF1.h>
#include <TF3.h>
#include <TDatabasePDG.h>
#include <TParticlePDG.h>

#include "AliRun.h"
#include "AliLog.h"
#include "AliESDtrack.h"
#include "AliESDVertex.h"
#include "AliGenPerformance.h"
#include "AliGenEventHeader.h"
#include "TMCParticle.h"
#include <AliPythia.h>
#include <TTreeStream.h>
#include <TChain.h>

ClassImp(AliGenPerformance)

//-----------------------------------------------------------------------------
AliGenPerformance::AliGenPerformance():
  AliGenerator(),
  fNJets(1),                // mean number of jets per event
  fF1Momentum(0),           // momentum distribution function
  fFPhi(0),                 // phi distribution function
  fFTheta(0),               // theta distribution function
  fFPosition(0),            // position distribution function
  fFPdg(0),                 // pdg distribution function
  fTestStream(0)            // test stream - used for tuning of parameters of generator
{
  //
  // Default constructor
  //
  SetNumberParticles(1);
}

AliGenPerformance::AliGenPerformance(const AliGenPerformance& func):
  AliGenerator(),
  fNJets(func.fNJets),                   //
  fF1Momentum(func.fF1Momentum),           // momentum distribution function
  fFPhi(func.fFPhi),                     // phi distribution function
  fFTheta(func.fFTheta),                 // theta distribution function
  fFPosition(func.fFPosition),           // position distribution function
  fFPdg(func.fFPdg)                     // pdg distribution function
{
    // Copy constructor
    SetNumberParticles(1);
}

AliGenPerformance & AliGenPerformance::operator=(const AliGenPerformance& func)
{
    // Assigment operator
      if(&func == this) return *this;
      fNJets      = func.fNJets;
      fF1Momentum = func.fF1Momentum;
      fFPhi       = func.fFPhi;
      fFTheta     = func.fFTheta;
      fFPosition  = func.fFPosition;
      fFPdg       = func.fFPdg;
      return *this;
}

//-----------------------------------------------------------------------------
void AliGenPerformance::Generate()
{
  //
  // Generate one muon
  //
  Int_t naccepted =0;
  Int_t njets=gRandom->Poisson(fNJets);
  TDatabasePDG *databasePDG = TDatabasePDG::Instance();

  for (Int_t iparton=0; iparton<njets; iparton++){
    //
    //
    //
    Float_t mom[3];
    Float_t posf[3];
    Double_t pos[3];
    Int_t pdg;
    Double_t ptot, pt,  phi, theta;
    //
    if (fF1Momentum){
      ptot     = 1./fF1Momentum->GetRandom();
    }else{
      ptot     = 0.001+gRandom->Rndm()*0.2;
      ptot/=ptot;
    }
    if (fFPhi){
      phi      = fFPhi->GetRandom();
    }else{
      phi      = gRandom->Rndm()*TMath::TwoPi();
    }
    if (fFTheta){
      theta    = fFTheta->GetRandom();
    }else{
      theta    =  (gRandom->Rndm()-0.5)*TMath::Pi()*0.5 +TMath::Pi()/2;
    }
    pt     = ptot*TMath::Sin(theta);
    mom[0] = pt*TMath::Cos(phi);
    mom[1] = pt*TMath::Sin(phi);
    mom[2] = ptot*TMath::Cos(theta);
    pos[0]=fOrigin[0]; pos[1]=fOrigin[1]; pos[2]=fOrigin[2];
    //
    if (fFPosition) fFPosition->GetRandom3(pos[0],pos[1],pos[2]); // ???? should be taken from "primary" coctail
    //
    posf[0]=pos[0];
    posf[1]=pos[1];
    posf[2]=pos[2];
    if (fFPdg){
      pdg = TMath::Nint(fFPdg->GetRandom());
    }else{
      pdg = 1+TMath::Nint(gRandom->Rndm()*5.);
    }
    Float_t polarization[3]= {0,0,0};
    Int_t nPart;
    //
    AliPythia *py=AliPythia::Instance();
    TParticlePDG *mParticle=databasePDG->GetParticle(pdg);
    if (mParticle==NULL) continue;
    Double_t mass=mParticle->Mass();
    Double_t energy=TMath::Sqrt(ptot*ptot+mass*mass);
    py->Py1ent(-1, -pdg, energy, theta, phi);
    py->Py1ent( 2,  pdg, energy, theta, phi+TMath::Pi());
    py->Pyexec();
    TObjArray * array = py->GetPrimaries();
    Int_t nParticles=array->GetEntries();
    //array->Print();
    Int_t pLabel  [nParticles];
    for (Int_t iparticle=0; iparticle<nParticles;  iparticle++){
      TMCParticle * mcParticle= (TMCParticle*)array->At(iparticle);
      Int_t flavour = mcParticle->GetKF();
      mom[0]=mcParticle->GetPx();
      mom[1]=mcParticle->GetPy();
      mom[2]=mcParticle->GetPz();
      posf[0]+=mcParticle->GetVx();
      posf[1]+=mcParticle->GetVy();
      posf[2]+=mcParticle->GetVz();
      TParticlePDG * pdgParticle=databasePDG->GetParticle(flavour);
      Int_t decayFlag=(iparticle<2)?1:11;
      pLabel[iparticle]=-1;
      Int_t pythiaParent=mcParticle->GetParent();
      Int_t stackParent=(pythiaParent>0&&pythiaParent<nParticles)?pLabel[pythiaParent]:-1;
      //
      if (!fTestStream &&pdgParticle!=NULL) {
	if (mcParticle->GetEnergy()<=mcParticle->GetMass()){
	  //::Error("AliGenPerformance::Generate","Unphysical particle %d",flavour); // MI to check Energy definition
	  continue;
	}
	// Missing info in roder to apply reweighting
	// 1.) mother track missing - all particles considered primary
	//        how to obtain mother ID ?
	// 2.)
	//
	PushTrack(fTrackIt,stackParent,flavour,mom, posf, polarization,0,kPPrimary,nPart,1.,decayFlag);
	pLabel[iparticle]=nPart;
	if (stackParent>0) KeepTrack(stackParent);
      }
      if (fTestStream){
	if (pdgParticle){
	  Double_t charge=pdgParticle->Charge();
	  Double_t mass=pdgParticle->Mass();
	  Double_t  pt=TMath::Sqrt(mcParticle->GetPx()*mcParticle->GetPx()+mcParticle->GetPy()*mcParticle->GetPy());
	  (*fTestStream)<<"testGener"<<
	    "njets="<<njets<<
	    "ptot="<<ptot<<
	    "theta="<<theta<<
	    "phi="<<phi<<
	    "pdg="<<pdg<<
	    "charge="<<charge<<
	    "mass="<<mass<<
	    "pt="<<pt<<
	    "nParticles="<<nParticles<<
	    "ipart="<<iparticle<<
	    "mcParticle.="<<mcParticle<<
	    "\n";
	}
      }
      naccepted++;
    }
  }
  //  AliGenEventHeader* header = new AliGenEventHeader("THn");
  //gAlice->SetGenEventHeader(header);

  return;
}

//-----------------------------------------------------------------------------
void AliGenPerformance::Init()
{
  //
  // Initialisation, check consistency of selected ranges
  //

  printf("************ AliGenPerformance ****************\n");
  printf("************************************************\n");
  if (!fF1Momentum){
    AliInfo("Momentum distribution function not specified");
  }
  if (!fFPhi){
    AliInfo("phi distribution function not specified");
  }
  if (!fFTheta){
    AliInfo("Theta distribution function not specified");
  }
  if (!fFPosition){
    AliInfo("Position distribution function not specified");
  }
  if (!fFPdg){
    AliInfo("PDG distribution function not specified");
  }

  return;
}

void AliGenPerformance::SetFunctions(TF1 * momentum, TF1 *fphi, TF1 *ftheta,TF3 * position, TF1* pdg){
  //
  // Set the function
  //
  fF1Momentum = momentum;
  fFPhi = fphi;
  fFTheta = ftheta;
  fFPosition = position;
  fFPdg = pdg;
}

void AliGenPerformance::TestAliGenPerformance(Int_t nEvents, TF1 *f1pt, TF1 *fpdg){
  //
  // test the genrator class - write particle  to the tree
  //
  AliGenPerformance *genPerformance= new AliGenPerformance;
  genPerformance->SetNJets(1);
  if (!f1pt) f1pt = new TF1("f1pt","1-10*x",0,0.1);
  if (!fpdg) fpdg = new TF1("f1pt","x",1,6);
  genPerformance->SetFunctions(f1pt,0,0,0,fpdg);
  TTreeSRedirector*pcstream = new TTreeSRedirector("testAliGenPerformance.root","recreate");
  genPerformance->SetStreamer(pcstream);
  for (Int_t i=0; i<nEvents;i++){
    genPerformance->Generate();
  }
  delete pcstream;
}

TChain *  AliGenPerformance::MakeKineChain(){
  //
  // Make chain of Kinematic trees
  // input list should be provided as a text files kinematics.list
  //
  TChain *chain = new TChain("xxx","xxx");
  TObjArray *kineArray = gSystem->GetFromPipe("cat kinematics.list").Tokenize("\n");
  Int_t nFiles=kineArray->GetEntries();
  for (Int_t iFile=0; iFile<nFiles; iFile++){
    TFile * fkine = TFile::Open(kineArray->At(iFile)->GetName());
    TList * kineList = fkine->GetListOfKeys();
    for (Int_t iKey=0; iKey<kineList->GetEntries();iKey++){
      chain->AddFile(kineArray->At(iFile)->GetName(), TChain::kBigNumber, TString::Format("%s/TreeK",kineList->At(iKey)->GetName()).Data());
    }
  }
  return chain;
  /*
    TChain * chainMother = AliGenPerformance::MakeKineChain();
    TChain * chainDaughter = AliGenPerformance::MakeKineChain();
    TChain * chainDaughter2 = AliGenPerformance::MakeKineChain();
    chainMother->SetAlias("tNumber","This->GetTreeNumber()");
    chainMother->SetAlias("eNumber","This.GetTree().GetReadEntry()");
    chainMother->SetAlias("mP","Particles.P()");

    chainMother->BuildIndex("This->GetTreeNumber()","This.GetTree().GetReadEntry()");
    chainDaughter->BuildIndex("This->GetTreeNumber()","Particles.GetMother(0)");
    chainDaughter2->BuildIndex("This->GetTreeNumber()","Particles.GetMother(0)");
    chainDaughter->AddFriend(chainMother,"M");
    chainDaughter->AddFriend(chainDaughter2,"D");

    TChain * chainMother = AliGenPerformance::MakeKineChain();
    TChain * chainDaughter = AliGenPerformance::MakeKineChain();
    chainMother->SetAlias("index0","(Particles.GetDaughter(0)+1000000*This->GetTreeNumber()+0)");
    chainDaughter->SetAlias("index0","(This.GetTree().GetReadEntry()+1000000*This->GetTreeNumber()+0)");
    //
    chainMother->BuildIndex("Particles.GetDaughter(0)+1000000*This->GetTreeNumber()");
    chainDaughter->BuildIndex("This.GetTree().GetReadEntry()+1000000*This->GetTreeNumber()");
    chainMother->AddFriend(chainDaughter,"D");

  */
}
<commit_msg>ATO-245 - 1.) Store parrent indeces 2.) Add small static function to crea a Kine chain 3.) To be possible to correlate Mother/Daughter - some fix in TChain needed (commit for ROOT5 prepared - to be discussed with root team)<commit_after>/**************************************************************************
 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

// Generator for particles according generic functions
// For high pt performance studies realistic distribution of the particles - local density in jets to be approximated
//
//
//  TF1 *   fF1Momentum;          // 1/momentum distribution function inGeV
//  TF1 *   fFPhi;                // phi distribution function in rad     - if not set flat 0-2pi used
//  TF1 *   fFTheta;              // theta distribution function in rad   - if not set flat pi/4-3pi/4 used
//  TF3 *   fFPosition;           // position distribution function in cm - TO FIX if not set 0 used ()
//  TF1 *   fFPdg;                // pdg distribution function            - if not set flat jet pdg used
//  We assume that the moment, postion and PDG code of particles are independent
//  Only tracks/particle crossing the reference radius at given z range
//
// Origin: marian.ivanov@cern.ch

/*
  To test generator for particular setting run
  AliGenPerformance::TestAliGenPerformance(Int_t nEvents, TF1 *f1pt, TF1 *fpdg){
  For distribution of
    fF1Momentum=new TF1("f1pt","1-10*x",0,0.1);
    AliGenPerformance::TestAliGenPerformance(1000, fF1Momentum,0)
    pt distribution of charged primary particles described by powerlaw with slope -1.7

  gSystem->Load("libpythia6");
  gSystem->Load("libEGPythia6");
  gSystem->Load("liblhapdf");
  gSystem->Load("libAliPythia6");
  //
  AliGenPerformance::TestAliGenPerformance(5000,0,0);
  TFile * f = TFile::Open("testAliGenPerformance.root");
  testGener.Draw("pt>>his(100,10,100)","charge!=0&&abs(fKF)<2000","");
  f1pt = new TF1("f1pt","1/(0.01+x)",0,0.1);
  his->Fit(f1);

*/

#include <TParticle.h>
#include <TF1.h>
#include <TF3.h>
#include <TDatabasePDG.h>
#include <TParticlePDG.h>

#include "AliRun.h"
#include "AliLog.h"
#include "AliESDtrack.h"
#include "AliESDVertex.h"
#include "AliGenPerformance.h"
#include "AliGenEventHeader.h"
#include "TMCParticle.h"
#include <AliPythia.h>
#include <TTreeStream.h>
#include <TChain.h>

ClassImp(AliGenPerformance)

//-----------------------------------------------------------------------------
AliGenPerformance::AliGenPerformance():
  AliGenerator(),
  fNJets(1),                // mean number of jets per event
  fF1Momentum(0),           // momentum distribution function
  fFPhi(0),                 // phi distribution function
  fFTheta(0),               // theta distribution function
  fFPosition(0),            // position distribution function
  fFPdg(0),                 // pdg distribution function
  fTestStream(0)            // test stream - used for tuning of parameters of generator
{
  //
  // Default constructor
  //
  SetNumberParticles(1);
}

AliGenPerformance::AliGenPerformance(const AliGenPerformance& func):
  AliGenerator(),
  fNJets(func.fNJets),                   //
  fF1Momentum(func.fF1Momentum),           // momentum distribution function
  fFPhi(func.fFPhi),                     // phi distribution function
  fFTheta(func.fFTheta),                 // theta distribution function
  fFPosition(func.fFPosition),           // position distribution function
  fFPdg(func.fFPdg)                     // pdg distribution function
{
    // Copy constructor
    SetNumberParticles(1);
}

AliGenPerformance & AliGenPerformance::operator=(const AliGenPerformance& func)
{
    // Assigment operator
      if(&func == this) return *this;
      fNJets      = func.fNJets;
      fF1Momentum = func.fF1Momentum;
      fFPhi       = func.fFPhi;
      fFTheta     = func.fFTheta;
      fFPosition  = func.fFPosition;
      fFPdg       = func.fFPdg;
      return *this;
}

//-----------------------------------------------------------------------------
void AliGenPerformance::Generate()
{
  //
  // Generate one muon
  //
  Int_t naccepted =0;
  Int_t njets=gRandom->Poisson(fNJets);
  TDatabasePDG *databasePDG = TDatabasePDG::Instance();

  for (Int_t iparton=0; iparton<njets; iparton++){
    //
    //
    //
    Float_t mom[3];
    Float_t posf[3];
    Double_t pos[3];
    Int_t pdg;
    Double_t ptot, pt,  phi, theta;
    //
    if (fF1Momentum){
      ptot     = 1./fF1Momentum->GetRandom();
    }else{
      ptot     = 0.001+gRandom->Rndm()*0.2;
      ptot/=ptot;
    }
    if (fFPhi){
      phi      = fFPhi->GetRandom();
    }else{
      phi      = gRandom->Rndm()*TMath::TwoPi();
    }
    if (fFTheta){
      theta    = fFTheta->GetRandom();
    }else{
      theta    =  (gRandom->Rndm()-0.5)*TMath::Pi()*0.5 +TMath::Pi()/2;
    }
    pt     = ptot*TMath::Sin(theta);
    mom[0] = pt*TMath::Cos(phi);
    mom[1] = pt*TMath::Sin(phi);
    mom[2] = ptot*TMath::Cos(theta);
    pos[0]=fOrigin[0]; pos[1]=fOrigin[1]; pos[2]=fOrigin[2];
    //
    if (fFPosition) fFPosition->GetRandom3(pos[0],pos[1],pos[2]); // ???? should be taken from "primary" coctail
    //
    posf[0]=pos[0];
    posf[1]=pos[1];
    posf[2]=pos[2];
    if (fFPdg){
      pdg = TMath::Nint(fFPdg->GetRandom());
    }else{
      pdg = 1+TMath::Nint(gRandom->Rndm()*5.);
    }
    Float_t polarization[3]= {0,0,0};
    Int_t nPart;
    //
    AliPythia *py=AliPythia::Instance();
    TParticlePDG *mParticle=databasePDG->GetParticle(pdg);
    if (mParticle==NULL) continue;
    Double_t mass=mParticle->Mass();
    Double_t energy=TMath::Sqrt(ptot*ptot+mass*mass);
    py->Py1ent(-1, -pdg, energy, theta, phi);
    py->Py1ent( 2,  pdg, energy, theta, phi+TMath::Pi());
    py->Pyexec();
    TObjArray * array = py->GetPrimaries();
    Int_t nParticles=array->GetEntries();
    //array->Print();
    Int_t pLabel  [nParticles];
    for (Int_t iparticle=0; iparticle<nParticles;  iparticle++){
      TMCParticle * mcParticle= (TMCParticle*)array->At(iparticle);
      Int_t flavour = mcParticle->GetKF();
      mom[0]=mcParticle->GetPx();
      mom[1]=mcParticle->GetPy();
      mom[2]=mcParticle->GetPz();
      posf[0]+=mcParticle->GetVx();
      posf[1]+=mcParticle->GetVy();
      posf[2]+=mcParticle->GetVz();
      TParticlePDG * pdgParticle=databasePDG->GetParticle(flavour);
      Int_t decayFlag=(iparticle<2)?1:11;
      pLabel[iparticle]=-1;
      Int_t pythiaParent=mcParticle->GetParent();
      Int_t stackParent=(pythiaParent>0&&pythiaParent<nParticles)?pLabel[pythiaParent]:-1;
      //
      if (!fTestStream &&pdgParticle!=NULL) {
	if (mcParticle->GetEnergy()<=mcParticle->GetMass()){
	  //::Error("AliGenPerformance::Generate","Unphysical particle %d",flavour); // MI to check Energy definition
	  continue;
	}
	// Missing info in order to apply reweighting
	// 1.) validate mother/daughter relationship
	// 2.) validate position distribution
	// 3.) add decay mode
	PushTrack(fTrackIt,stackParent,flavour,mom, posf, polarization,0,kPPrimary,nPart,1.,decayFlag);
	pLabel[iparticle]=nPart;
	if (stackParent>0) KeepTrack(stackParent);
      }
      if (fTestStream){
	if (pdgParticle){
	  Double_t charge=pdgParticle->Charge();
	  Double_t mass=pdgParticle->Mass();
	  Double_t  pt=TMath::Sqrt(mcParticle->GetPx()*mcParticle->GetPx()+mcParticle->GetPy()*mcParticle->GetPy());
	  (*fTestStream)<<"testGener"<<
	    "njets="<<njets<<
	    "ptot="<<ptot<<
	    "theta="<<theta<<
	    "phi="<<phi<<
	    "pdg="<<pdg<<
	    "charge="<<charge<<
	    "mass="<<mass<<
	    "pt="<<pt<<
	    "nParticles="<<nParticles<<
	    "ipart="<<iparticle<<
	    "mcParticle.="<<mcParticle<<
	    "\n";
	}
      }
      naccepted++;
    }
  }
  //  AliGenEventHeader* header = new AliGenEventHeader("THn");
  //gAlice->SetGenEventHeader(header);

  return;
}

//-----------------------------------------------------------------------------
void AliGenPerformance::Init()
{
  //
  // Initialisation, check consistency of selected ranges
  //

  printf("************ AliGenPerformance ****************\n");
  printf("************************************************\n");
  if (!fF1Momentum){
    AliInfo("Momentum distribution function not specified");
  }
  if (!fFPhi){
    AliInfo("phi distribution function not specified");
  }
  if (!fFTheta){
    AliInfo("Theta distribution function not specified");
  }
  if (!fFPosition){
    AliInfo("Position distribution function not specified");
  }
  if (!fFPdg){
    AliInfo("PDG distribution function not specified");
  }

  return;
}

void AliGenPerformance::SetFunctions(TF1 * momentum, TF1 *fphi, TF1 *ftheta,TF3 * position, TF1* pdg){
  //
  // Set the function
  //
  fF1Momentum = momentum;
  fFPhi = fphi;
  fFTheta = ftheta;
  fFPosition = position;
  fFPdg = pdg;
}

void AliGenPerformance::TestAliGenPerformance(Int_t nEvents, TF1 *f1pt, TF1 *fpdg){
  //
  // test the genrator class - write particle  to the tree
  //
  AliGenPerformance *genPerformance= new AliGenPerformance;
  genPerformance->SetNJets(1);
  if (!f1pt) f1pt = new TF1("f1pt","1-10*x",0,0.1);
  if (!fpdg) fpdg = new TF1("f1pt","x",1,6);
  genPerformance->SetFunctions(f1pt,0,0,0,fpdg);
  TTreeSRedirector*pcstream = new TTreeSRedirector("testAliGenPerformance.root","recreate");
  genPerformance->SetStreamer(pcstream);
  for (Int_t i=0; i<nEvents;i++){
    genPerformance->Generate();
  }
  delete pcstream;
}

TChain *  AliGenPerformance::MakeKineChain(){
  //
  // Make chain of Kinematic trees
  // input list should be provided as a text files kinematics.list
  //
  TChain *chain = new TChain("xxx","xxx");
  TObjArray *kineArray = gSystem->GetFromPipe("cat kinematics.list").Tokenize("\n");
  Int_t nFiles=kineArray->GetEntries();
  for (Int_t iFile=0; iFile<nFiles; iFile++){
    TFile * fkine = TFile::Open(kineArray->At(iFile)->GetName());
    TList * kineList = fkine->GetListOfKeys();
    for (Int_t iKey=0; iKey<kineList->GetEntries();iKey++){
      chain->AddFile(kineArray->At(iFile)->GetName(), TChain::kBigNumber, TString::Format("%s/TreeK",kineList->At(iKey)->GetName()).Data());
    }
  }
  return chain;
  /*
    // using following lines properties of mother particles and daughter particles can be correlated
    // Unfortuantelly to do it fix in the TChain needed.
    //    1.) problem with aliases (fix prepared)
    //    2.)
    TChain * chainMother = AliGenPerformance::MakeKineChain();
    TChain * chainDaughter = AliGenPerformance::MakeKineChain();
    chainMother->SetAlias("index0","(Particles.GetDaughter(0)+1000000*This->GetTreeNumber()+0)");
    chainDaughter->SetAlias("index0","(This.GetTree().GetReadEntry()+1000000*This->GetTreeNumber()+0)");
    //
    chainMother->BuildIndex("index0");
    chainDaughter->BuildIndex("index0");
    chainMother->AddFriend(chainDaughter,"D");
  */
}
<|endoftext|>


<commit_before>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2020 Ryo Suzuki
//	Copyright (c) 2016-2020 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <array>
# include <Siv3D/String.hpp>
# include <Siv3D/FormatLiteral.hpp>
# include <Siv3D/Time.hpp>
# include "CLogger.hpp"

namespace s3d
{
	namespace detail
	{
		constexpr std::array<StringView, 7> LogTypeNames =
		{
			U"[error]   "_sv,
			U"[fail]    "_sv,
			U"[warning] "_sv,
			U""_sv,
			U"[info]    "_sv,
			U"[trace]   "_sv,
			U"[verbose] "_sv,
		};
	}

	CLogger::CLogger()
	{

	}

	CLogger::~CLogger()
	{

	}

	void CLogger::write(const LogType type, const StringView s)
	{
		if (not m_enabled)
		{
			return;
		}

		const int64 timeStamp = Time::GetMillisec();
		const StringView logTypeName = detail::LogTypeNames[FromEnum(type)];
		const String text = U"{}: {}"_fmt(timeStamp, logTypeName) + s + U'\n';
		const std::string output = text.narrow();

		std::lock_guard lock(m_mutex);
		{
			std::cout << output;
		}
	}

	void CLogger::setEnabled(const bool enabled)
	{
		m_enabled = enabled;
	}
}
<commit_msg>[Linux] fix<commit_after>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2020 Ryo Suzuki
//	Copyright (c) 2016-2020 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <array>
# include <Siv3D/String.hpp>
# include <Siv3D/FormatLiteral.hpp>
# include <Siv3D/Time.hpp>
# include "CLogger.hpp"

namespace s3d
{
	namespace detail
	{
		constexpr std::array<StringView, 7> LogTypeNames =
		{
			U"[error]   "_sv,
			U"[fail]    "_sv,
			U"[warning] "_sv,
			U""_sv,
			U"[info]    "_sv,
			U"[trace]   "_sv,
			U"[verbose] "_sv,
		};
	}

	CLogger::CLogger()
	{

	}

	CLogger::~CLogger()
	{

	}

	void CLogger::write(const LogType type, const StringView s)
	{
		if (not m_enabled)
		{
			return;
		}

		const int64 timeStamp = Time::GetMillisec();
		const StringView logTypeName = detail::LogTypeNames[FromEnum(type)];
		const String text = U"{}: {}"_fmt(timeStamp, logTypeName) + s;
		const std::string output = text.narrow();

		std::lock_guard lock(m_mutex);
		{
			std::cout << output << std::endl;
		}
	}

	void CLogger::setEnabled(const bool enabled)
	{
		m_enabled = enabled;
	}
}
<|endoftext|>