<commit_before>#include "EasyTransfer2.h"

//Captures address and size of struct
void EasyTransfer2::begin(HardwareSerial *theSerial){
	_serial = theSerial;

	//dynamic creation of rx parsing buffer in RAM
	//rx_buffer = (uint8_t*) malloc(size);

	resetData();
}

void EasyTransfer2::writeByte(uint8_t dat){
	if(position<20)
		data[position++]=dat;
		size++;
}
void EasyTransfer2::writeInt(int dat){
	if(position<19){
		data[position++]=dat>>8;
		data[position++]=dat;
		size+=2;
	}
}
uint8_t EasyTransfer2::readByte(){
	if(position>=size)return 0;
	return data[position++];
}
int EasyTransfer2::readInt(){
	if(position+1>=size)return 0;
	int dat_1=data[position++]<<8;
	int dat_2=data[position++];
	int dat= dat_1 | dat_2;
	return dat;
}

void EasyTransfer2::resetData(){
	for(int i=0;i<20;i++){
		data[i]=0;
	}
	size=0;
	position=0;
}

//Sends out struct in binary, with header, length info and checksum
void EasyTransfer2::sendData(){
  uint8_t CS = size;
  _serial->write(0x06);
  _serial->write(0x85);
  _serial->write(size);
  for(int i = 0; i<size; i++){
    CS^=*(data+i);
    _serial->write(*(data+i));
	//Serial.print(*(data+i));
	//Serial.print(",");
  }
  //Serial.println("");
  _serial->write(CS);

  resetData();
}

boolean EasyTransfer2::receiveData(){

  //start off by looking for the header bytes. If they were already found in a previous call, skip it.
  if(rx_len == 0){
  //this size check may be redundant due to the size check below, but for now I'll leave it the way it is.
    if(_serial->available() >= 3){
	//this will block until a 0x06 is found or buffer size becomes less then 3.
      while(_serial->read() != 0x06) {
		//This will trash any preamble junk in the serial buffer
		//but we need to make sure there is enough in the buffer to process while we trash the rest
		//if the buffer becomes too empty, we will escape and try again on the next call
		if(_serial->available() < 3)
			return false;
		}
		//Serial.println("head");
      if (_serial->read() == 0x85){
        rx_len = _serial->read();
		//Serial.print("rx_len:");
		//Serial.println(rx_len);
		resetData();

		//make sure the binary structs on both Arduinos are the same size.
        /*if(rx_len != size){
          rx_len = 0;
          return false;
        }*/
      }
    }
	//Serial.println("nothing");
  }

  //we get here if we already found the header bytes, the struct size matched what we know, and now we are byte aligned.
  if(rx_len != 0){

    while(_serial->available() && rx_array_inx <= rx_len){
      data[rx_array_inx++] = _serial->read();
    }

    if(rx_len == (rx_array_inx-1)){
      //seem to have got whole message
      //last uint8_t is CS
      calc_CS = rx_len;
	  //Serial.print("len:");
	  //Serial.println(rx_len);
      for (int i = 0; i<rx_len; i++){
        calc_CS^=data[i];
		//Serial.print("m");
		//Serial.print(data[i]);
		//Serial.print(",");
      }
	  //Serial.println();
      //Serial.print(data[rx_array_inx-1]);
	  //Serial.print(" ");
	  //Serial.println(calc_CS);

      if(calc_CS == data[rx_array_inx-1]){//CS good
		//resetData();
        //memcpy(data,d,rx_len);
		for(int i=0;i<20;i++){
			//Serial.print(data[i]);
			//Serial.print(",");
		}
		//Serial.println("");
		size=rx_len;
		rx_len = 0;
		rx_array_inx = 0;
		return true;
		}

	  else{
  		//Serial.println("CS");
		resetData();
	  //failed checksum, need to clear this out anyway
		rx_len = 0;
		rx_array_inx = 0;
		return false;
	  }

    }
  }
  //Serial.print(rx_len);
  //Serial.print(" ");
  //Serial.print(rx_array_inx);
  //Serial.print(" ");
  //Serial.println("Short");
  return false;
}<commit_msg>minor changes<commit_after>/******************************************************************
*  EasyTransfer Arduino Library
*		details and example sketch:
*			http://www.billporter.info/easytransfer-arduino-library/
*
*		Brought to you by:
*              Bill Porter
*              www.billporter.info
*
*		See Readme for other info and version history
*
*
*This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or(at your option) any later version.
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.
<http://www.gnu.org/licenses/>
*
*This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
*To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/ or
*send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
******************************************************************/

#include "EasyTransfer2.h"

//Captures address and size of struct
void EasyTransfer2::begin(HardwareSerial *theSerial){
	_serial = theSerial;

	//dynamic creation of rx parsing buffer in RAM
	//rx_buffer = (uint8_t*) malloc(size);

	resetData();
}

void EasyTransfer2::writeByte(uint8_t dat){
	if(position<20)
		data[position++]=dat;
		size++;
}
void EasyTransfer2::writeInt(int dat){
	if(position<19){
		data[position++]=dat>>8;
		data[position++]=dat;
		size+=2;
	}
}
uint8_t EasyTransfer2::readByte(){
	if(position>=size)return 0;
	return data[position++];
}
int EasyTransfer2::readInt(){
	if(position+1>=size)return 0;
	int dat_1=data[position++]<<8;
	int dat_2=data[position++];
	int dat= dat_1 | dat_2;
	return dat;
}

void EasyTransfer2::resetData(){
	for(int i=0;i<20;i++){
		data[i]=0;
	}
	size=0;
	position=0;
}

//Sends out struct in binary, with header, length info and checksum
void EasyTransfer2::sendData(){
  uint8_t CS = size;
  _serial->write(0x06);
  _serial->write(0x85);
  _serial->write(size);
  for(int i = 0; i<size; i++){
    CS^=*(data+i);
    _serial->write(*(data+i));
	//Serial.print(*(data+i));
	//Serial.print(",");
  }
  //Serial.println("");
  _serial->write(CS);

  resetData();
}

boolean EasyTransfer2::receiveData(){

  //start off by looking for the header bytes. If they were already found in a previous call, skip it.
  if(rx_len == 0){
  //this size check may be redundant due to the size check below, but for now I'll leave it the way it is.
    if(_serial->available() >= 3){
	//this will block until a 0x06 is found or buffer size becomes less then 3.
      while(_serial->read() != 0x06) {
		//This will trash any preamble junk in the serial buffer
		//but we need to make sure there is enough in the buffer to process while we trash the rest
		//if the buffer becomes too empty, we will escape and try again on the next call
		if(_serial->available() < 3)
			return false;
		}
		//Serial.println("head");
      if (_serial->read() == 0x85){
        rx_len = _serial->read();
		//Serial.print("rx_len:");
		//Serial.println(rx_len);
		resetData();

		//make sure the binary structs on both Arduinos are the same size.
        /*if(rx_len != size){
          rx_len = 0;
          return false;
        }*/
      }
    }
	//Serial.println("nothing");
  }

  //we get here if we already found the header bytes, the struct size matched what we know, and now we are byte aligned.
  if(rx_len != 0){

    while(_serial->available() && rx_array_inx <= rx_len){
      data[rx_array_inx++] = _serial->read();
    }

    if(rx_len == (rx_array_inx-1)){
      //seem to have got whole message
      //last uint8_t is CS
      calc_CS = rx_len;
	  //Serial.print("len:");
	  //Serial.println(rx_len);
      for (int i = 0; i<rx_len; i++){
        calc_CS^=data[i];
		//Serial.print("m");
		//Serial.print(data[i]);
		//Serial.print(",");
      }
	  //Serial.println();
      //Serial.print(data[rx_array_inx-1]);
	  //Serial.print(" ");
	  //Serial.println(calc_CS);

      if(calc_CS == data[rx_array_inx-1]){//CS good
		//resetData();
        //memcpy(data,d,rx_len);
		for(int i=0;i<20;i++){
			//Serial.print(data[i]);
			//Serial.print(",");
		}
		//Serial.println("");
		size=rx_len;
		rx_len = 0;
		rx_array_inx = 0;
		return true;
		}

	  else{
  		//Serial.println("CS");
		resetData();
	  //failed checksum, need to clear this out anyway
		rx_len = 0;
		rx_array_inx = 0;
		return false;
	  }

    }
  }
  //Serial.print(rx_len);
  //Serial.print(" ");
  //Serial.print(rx_array_inx);
  //Serial.print(" ");
  //Serial.println("Short");
  return false;
}
<|endoftext|>


<commit_before>#include "graph.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>

int main (int ac, char **av)
{
  printf("Running tests...\n");

  graph* g = new graph();

  // Tests 1-2: An unconnected graph
  int elist1[] = {0,1, 0,2, 1,2};
  double x1[] = {0.0, 1.0, 0.0};
  g->init(x1, 3, 3, elist1);
  printf("Test 1: ");
  if (not g->is_connected()) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }
  std::vector<std::vector<int> > components2;
  std::vector<int> v2_1;
  std::vector<int> v2_2;
  v2_1.push_back(0);
  v2_1.push_back(2);
  v2_2.push_back(1);
  components2.push_back(v2_1);
  components2.push_back(v2_2);
  printf("Test 2: ");
  if (components2 == g->get_components()) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }

  // Tests 3-4: A connected graph
  int elist3[] = {0,1, 0,2, 1,2};
  double x3[] = {1.0, 1.0, 0.0};
  g->init(x3, 3, 3, elist3);
  printf("Test 3: ");
  if (g->is_connected()) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }
  std::vector<std::vector<int> > components4;
  std::vector<int> v4_1;
  v4_1.push_back(0);
  v4_1.push_back(1);
  v4_1.push_back(2);
  components4.push_back(v4_1);
  printf("Test 4: ");
  if (components4 == g->get_components()) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }

  // Tests 5-6: Test delta function
  int elist5[] = {0,1, 0,2, 0,3, 1,2, 1,3, 2,3};
  double x5[] = {1.0, 1.0, 0.0};
  g->init(x5, 4, 6, elist5);
  std::vector<int> s5;
  s5.push_back(0);
  s5.push_back(1);
  std::vector<int> delta5;
  delta5.push_back(1);
  delta5.push_back(2);
  delta5.push_back(3);
  delta5.push_back(4);
  printf("Test 5: ");
  if (delta5 == g->delta(s5)) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }
  std::vector<int> s6;
  s6.push_back(0);
  s6.push_back(2);
  s6.push_back(3);
  std::vector<int> delta6;
  delta6.push_back(0);
  delta6.push_back(3);
  delta6.push_back(4);
  printf("Test 6: ");
  if (delta6 == g->delta(s6)) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }

  printf("Done.\n");
  return 0;
}
<commit_msg>Try to fix test_graph<commit_after>#include "graph.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>

int main (int ac, char **av)
{
  printf("Running tests...\n");

  graph* g = new graph();

  // Tests 1-2: An unconnected graph
  int elist1[] = {0,1, 0,2, 1,2};
  int elen1[] = {1,1,1};
  double x1[] = {0.0, 1.0, 0.0};
  g->init(x1, 3, 3, elist1, elen1);
  printf("Test 1: ");
  if (not g->is_connected()) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }
  std::vector<std::vector<int> > components2;
  std::vector<int> v2_1;
  std::vector<int> v2_2;
  v2_1.push_back(0);
  v2_1.push_back(2);
  v2_2.push_back(1);
  components2.push_back(v2_1);
  components2.push_back(v2_2);
  printf("Test 2: ");
  if (components2 == g->get_components()) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }

  // Tests 3-4: A connected graph
  int elist3[] = {0,1, 0,2, 1,2};
  int elen3[] = {1,1,1};
  double x3[] = {1.0, 1.0, 0.0};
  g->init(x3, 3, 3, elist3, elen3);
  printf("Test 3: ");
  if (g->is_connected()) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }
  std::vector<std::vector<int> > components4;
  std::vector<int> v4_1;
  v4_1.push_back(0);
  v4_1.push_back(1);
  v4_1.push_back(2);
  components4.push_back(v4_1);
  printf("Test 4: ");
  if (components4 == g->get_components()) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }

  // Tests 5-6: Test delta function
  int elist5[] = {0,1, 0,2, 0,3, 1,2, 1,3, 2,3};
  int elen5[] = {1,1,1,1,1,1};
  double x5[] = {1.0, 1.0, 0.0};
  g->init(x5, 4, 6, elist5, elen5);
  std::vector<int> s5;
  s5.push_back(0);
  s5.push_back(1);
  std::vector<int> delta5;
  delta5.push_back(1);
  delta5.push_back(2);
  delta5.push_back(3);
  delta5.push_back(4);
  printf("Test 5: ");
  if (delta5 == g->delta(s5)) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }
  std::vector<int> s6;
  s6.push_back(0);
  s6.push_back(2);
  s6.push_back(3);
  std::vector<int> delta6;
  delta6.push_back(0);
  delta6.push_back(3);
  delta6.push_back(4);
  printf("Test 6: ");
  if (delta6 == g->delta(s6)) {
    printf("PASSED\n");
  } else {
    printf("FAILED\n");
  }

  printf("Done.\n");
  return 0;
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: Points.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Header file of Points definition
//
///////////////////////////////////////////////////////////////////////////////

#ifndef POINTS_HPP
#define POINTS_HPP

#include <math.h>
#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
#include <LibUtilities/Foundations/Foundations.hpp>
//#include <LibUtilities/LinearAlgebra/NekMatrix.hpp>

namespace Nektar
{
    namespace LibUtilities
    {
        // Need to add method to compute total number of points given dimension
        // and number of points.

        class PointsKey
        {
        public:
             // Use for looking up the creator.  The creator for number of points
            // can generate for any number, so we want the same creator called
            // for all number.
            struct opLess
            {
                bool operator()(const PointsKey &lhs, const PointsKey &rhs);
            };

           PointsKey(const unsigned int &pointsdim, const int &numpoints,
                const PointsType &pointstype, const PointsIdentifier &pointsid = eWildcard):
                    m_pointsdim(pointsdim),
                    m_numpoints(numpoints),
                    m_pointstype(pointstype),
                    m_pointsid(pointsid)
            {
            }

            virtual ~PointsKey()
            {
            }

            PointsKey(const PointsKey &key)
            {
                *this = key; // defer to assignment operator
            }

            PointsKey& operator=(const PointsKey &key)
            {
                m_pointsdim = key.m_pointsdim;
                m_numpoints = key.m_numpoints;
                m_pointstype  = key.m_pointstype;
                m_pointsid    = key.m_pointsid;

                return *this;
            }

            inline unsigned int GetPointsDim() const
            {
                return m_pointsdim;
            }

            inline unsigned int GetNumPoints() const
            {
                return m_numpoints;
            }

            inline PointsType GetPointsType() const
            {
                return m_pointstype;
            }

            inline PointsIdentifier GetPointsId() const
            {
                return m_pointsid;
            }

            bool operator==(const PointsKey &key)
            {
                return (m_pointsdim == key.m_pointsdim &&
                    m_numpoints == key.m_numpoints &&
                    m_pointstype == key.m_pointstype &&
                    m_pointsid == key.m_pointsid);
            }

            bool operator == (const PointsKey *y)
            {
                return (*this == *y);
            }

            bool operator != (const PointsKey& y)
            {
                return (!(*this == y));
            }

            bool operator != (const PointsKey *y)
            {
                return (!(*this == *y));
            }

            friend bool operator<(const PointsKey &lhs, const PointsKey &rhs);
            friend bool opLess::operator()(const PointsKey &lhs, const PointsKey &rhs);

        protected:
            unsigned int m_pointsdim;     //!< dimension of the points
            unsigned int m_numpoints;     //!< number of the points (as appropriately defined for PointsType)
            PointsType m_pointstype;      //!< Type of Points
            PointsIdentifier m_pointsid;  //!< Unique indentifier (when needed)

        private:
            PointsKey()
            {
                NEKERROR(ErrorUtil::efatal,"Default Constructor for PointsKey should not be called");
            }
        };

        bool operator<(const PointsKey &lhs, const PointsKey &rhs);

        std::ostream& operator<<(std::ostream& os, const PointsKey& rhs);

        template<typename DataT>
        class Points
        {
        public:
            typedef DataT DataType;

            Points(const PointsKey &key): m_pkey(key)
            {
            }

            virtual ~Points()
            {
                if(m_pkey.GetNumPoints())
                {
                    unsigned int dim = m_pkey.GetPointsDim();

                    for(unsigned int i = 0; i < dim; ++i)
                    {
                        delete[] m_points[i];
                    }

                    delete[] m_points;
                    delete[] m_weights;
                }
            }

            void Initialize(void)
            {
                CalculatePoints();
                CalculateWeights();
                CalculateDerivMatrix();
            }

            inline unsigned int GetPointsDim() const
            {
                return m_pkey.GetPointsDim();
            }

            inline unsigned int GetNumPoints() const
            {
                return m_pkey.GetNumPoints();
            }

            inline PointsType GetPointsType() const
            {
                return m_pkey.GetPointsType();
            }

            inline PointsIdentifier GetPointsId() const
            {
                return m_pkey.GetPointsId();
            }

            inline double *GetZ() const
            {
                return m_points[0];
            }

            inline double *GetW() const
            {
                return m_weights;
            }

            inline void GetZW(const double *&z, const double *&w) const
            {
                z = m_points[0];
                w = m_weights;
            }

            inline void GetPoints(const double *&x) const
            {
                x = m_points[0];
            }

            inline void GetPoints(const double *&x, const double *&y) const
            {
                x = m_points[0];
                y = m_points[1];
            }

            inline void GetPoints(const double *&x, const double *&y, const double *&z) const
            {
                x = m_points[0];
                y = m_points[1];
                z = m_points[2];
            }

            //inline const boost::shared_ptr<NekMatrix<DataType> > GetD() const
            //{
            //    return m_derivmatrix;
            //}

        protected:
            PointsKey m_pkey;
            DataType **m_points;
            DataType *m_weights;
//            boost::shared_ptr<NekMatrix<DataType> > m_derivmatrix;

            virtual void CalculatePoints()
            {
                unsigned int pointsDim = GetPointsDim();

                m_points = new Points::DataType*[pointsDim];

                for (unsigned int i=0; i<pointsDim; ++i)
                {
                    m_points[i] = new Points::DataType[GetNumPoints()];
                }
            }

            virtual void CalculateWeights()
            {
                m_weights = new Points::DataType[GetNumPoints()];
            }

            virtual void CalculateDerivMatrix()
            {
            }

        private:
            // This should never be called.
            Points()
            {
                NEKERROR(ErrorUtil::efatal,"Default Constructor for Points should not be called");
            }
        };

    }; // end of namespace
} // end of namespace

#endif //POINTS_HPP
<commit_msg>*** empty log message ***<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: Points.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Header file of Points definition
//
///////////////////////////////////////////////////////////////////////////////

#ifndef POINTS_HPP
#define POINTS_HPP

#include <math.h>
#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
#include <LibUtilities/Foundations/Foundations.hpp>
//#include <LibUtilities/LinearAlgebra/NekMatrix.hpp>

namespace Nektar
{
    namespace LibUtilities
    {
        // Need to add method to compute total number of points given dimension
        // and number of points.

        class PointsKey
        {
        public:
             // Use for looking up the creator.  The creator for number of points
            // can generate for any number, so we want the same creator called
            // for all number.
            struct opLess
            {
                bool operator()(const PointsKey &lhs, const PointsKey &rhs);
            };

           PointsKey(const unsigned int &pointsdim, const int &numpoints,
                const PointsType &pointstype, const PointsIdentifier &pointsid = eWildcard):
                    m_pointsdim(pointsdim),
                    m_numpoints(numpoints),
                    m_pointstype(pointstype),
                    m_pointsid(pointsid)
            {
            }

            virtual ~PointsKey()
            {
            }

            PointsKey(const PointsKey &key)
            {
                *this = key; // defer to assignment operator
            }

            PointsKey& operator=(const PointsKey &key)
            {
                m_numpoints = key.m_numpoints;
                m_pointstype  = key.m_pointstype;

                return *this;
            }

            inline unsigned int GetNumPoints() const
            {
                return m_numpoints;
            }

            inline unsigned int GetTotNumPoints() const
            {
                exit(0);//return m_numpoints;
            }

            inline PointsType GetPointsType() const
            {
                return m_pointstype;
            }

            bool operator==(const PointsKey &key)
            {
                return (m_numpoints == key.m_numpoints &&
                        m_pointstype == key.m_pointstype);
            }

            bool operator == (const PointsKey *y)
            {
                return (*this == *y);
            }

            bool operator != (const PointsKey& y)
            {
                return (!(*this == y));
            }

            bool operator != (const PointsKey *y)
            {
                return (!(*this == *y));
            }

            friend bool operator<(const PointsKey &lhs, const PointsKey &rhs);
            friend bool opLess::operator()(const PointsKey &lhs, const PointsKey &rhs);

        protected:
            unsigned int m_numpoints;     //!< number of the points (as appropriately defined for PointsType)
            PointsType m_pointstype;      //!< Type of Points

        private:
            PointsKey()
            {
                NEKERROR(ErrorUtil::efatal,"Default Constructor for PointsKey should not be called");
            }
        };

        bool operator<(const PointsKey &lhs, const PointsKey &rhs);

        std::ostream& operator<<(std::ostream& os, const PointsKey& rhs);

        template<typename DataT>
        class Points
        {
        public:
            typedef DataT DataType;

            Points(const PointsKey &key): m_pointsKey(key)
            {
            }

            virtual ~Points()
            {
                //if(m_pointsKey.GetNumPoints())
                //{
                //    unsigned int dim = m_pkey.GetPointsDim();

                //    for(unsigned int i = 0; i < dim; ++i)
                //    {
                //        delete[] m_points[i];
                //    }

                //    delete[] m_points;
                //    delete[] m_weights;
                //}
            }

            void Initialize(void)
            {
                CalculatePoints();
                CalculateWeights();
                CalculateDerivMatrix();
            }

            inline unsigned int GetPointsDim() const
            {
                return 1;
            }

            inline unsigned int GetNumPoints() const
            {
                return m_pointsKey.GetNumPoints();
            }

            inline PointsType GetPointsType() const
            {
                return m_pointsKey.GetPointsType();
            }

            inline double *GetZ() const
            {
                return m_points[0];
            }

            inline double *GetW() const
            {
                return m_weights;
            }

            inline void GetZW(const double *&z, const double *&w) const
            {
                z = m_points[0];
                w = m_weights;
            }

            inline void GetPoints(const double *&x) const
            {
                x = m_points[0];
            }

            inline void GetPoints(const double *&x, const double *&y) const
            {
                x = m_points[0];
                y = m_points[1];
            }

            inline void GetPoints(const double *&x, const double *&y, const double *&z) const
            {
                x = m_points[0];
                y = m_points[1];
                z = m_points[2];
            }

            //inline const boost::shared_ptr<NekMatrix<DataType> > GetI(PointsKey)
            //{
            //    return m_derivmatrix;
            //}

//            inline const boost::shared_ptr<NekMatrix<DataType> > GetI(PointsKey)
//            {
//                return m_derivmatrix;
//            }

            //inline const boost::shared_ptr<NekMatrix<DataType> > GetD() const
            //{
            //    return m_derivmatrix;
            //}

        protected:
            PointsKey m_pointsKey;
            DataType **m_points;
            DataType *m_weights;
//            boost::shared_ptr<NekMatrix<DataType> > m_derivmatrix;

            virtual void CalculatePoints()
            {
 /*               unsigned int pointsDim = GetPointsDim();

                m_points = new Points::DataType*[pointsDim];

                for (unsigned int i=0; i<pointsDim; ++i)
                {
                    m_points[i] = new Points::DataType[GetNumPoints()];
                }*/
            }

            virtual void CalculateWeights()
            {
                m_weights = new Points::DataType[GetNumPoints()];
            }

            virtual void CalculateDerivMatrix()
            {
            }

        private:
            // This should never be called.
            Points()
            {
                NEKERROR(ErrorUtil::efatal,"Default Constructor for Points should not be called");
            }
        };

    }; // end of namespace
} // end of namespace

#endif //POINTS_HPP
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "drivers/hpet.hpp"

#include "acpica.hpp"
#include "logging.hpp"
#include "mmap.hpp"
#include "int_lock.hpp"
#include "kernel.hpp" // For suspend_kernel
#include "scheduler.hpp" // For async init
#include "timer.hpp"     // For setting the frequency

#include "drivers/pit.hpp" // For uninstalling it

// TODO Ideally, we should run in periodic mode
// However, I've not been able to make it work (no interrupt are generated)

namespace {

// Offset of the registers inside the hpet memory
constexpr const size_t CAPABILITIES_REGISTER = 0x0;
constexpr const size_t GENERAL_CONFIG_REGISTER = 0x10 / 8;
constexpr const size_t GENERAL_INTERRUPT_REGISTER = 0x20 / 8;
constexpr const size_t MAIN_COUNTER = 0xF0 / 8;

constexpr const size_t GENERAL_CONFIG_ENABLE = 1 << 0;
constexpr const size_t GENERAL_CONFIG_LEGACY = 1 << 1;

constexpr const size_t CAPABILITIES_LEGACY = 1 << 15;
constexpr const size_t CAPABILITIES_64 = 1 << 13;

constexpr const size_t TIMER_CONFIG_ENABLE = 1 << 2;
constexpr const size_t TIMER_CONFIG_PERIODIC = 1 << 3;
constexpr const size_t TIMER_CONFIG_PERIODIC_CAP = 1 << 5;
constexpr const size_t TIMER_CONFIG_64 = 1 << 5;

constexpr const size_t FREQUENCY_GOAL = 10000; // 1 tick every 100 microseconds

ACPI_TABLE_HPET* hpet_table;
uint64_t* hpet_map;
volatile uint64_t comparator_update;

uint64_t timer_configuration_reg(uint64_t n){
    return (0x100 + 0x20 * n) / 8;
}

uint64_t timer_comparator_reg(uint64_t n){
    return (0x108 + 0x20 * n) / 8;
}

uint64_t timer_interrupt_reg(uint64_t n){
    return (0x110 + 0x20 * n) / 8;
}

uint64_t read_register(size_t reg){
    return hpet_map[reg];
}

void write_register(size_t reg, uint64_t value){
    hpet_map[reg] = value;
}

void set_register_bits(size_t reg, uint64_t bits){
    write_register(reg, read_register(reg) | bits);
}

void clear_register_bits(size_t reg, uint64_t bits){
    write_register(reg, read_register(reg) & ~bits);
}

void timer_handler(interrupt::syscall_regs*, void*){
    // Clears Tn_INT_STS
    set_register_bits(GENERAL_INTERRUPT_REGISTER, 1 << 0);

    // Sets the next event to fire an IRQ
    write_register(timer_comparator_reg(0), read_register(MAIN_COUNTER) + comparator_update);

    timer::tick();
}

} //End of anonymous namespace

void hpet::init(){
    // HPET needs ACPI
    scheduler::queue_async_init_task(hpet::late_install);
}

bool hpet::install(){
    // Find the HPET table
    auto status = AcpiGetTable(ACPI_SIG_HPET, 0, reinterpret_cast<ACPI_TABLE_HEADER **>(&hpet_table));
    if (ACPI_FAILURE(status)){
        return false;
    }

    logging::logf(logging::log_level::TRACE, "hpet: Found ACPI HPET table\n");

    return true;
}

void hpet::late_install(){
    if(hpet::install()){
        logging::logf(logging::log_level::TRACE, "hpet: Late install suceeded\n");

        logging::logf(logging::log_level::TRACE, "hpet: HPET Address: %h\n", hpet_table->Address.Address);

        hpet_map = static_cast<uint64_t*>(mmap_phys(hpet_table->Address.Address, 1024)); //TODO Check the size

        // Disable interrupts: We should not be interrupted from this point on
        direct_int_lock lock;

        // Disable before configuration
        clear_register_bits(GENERAL_CONFIG_REGISTER, GENERAL_CONFIG_ENABLE);

        if(!(read_register(CAPABILITIES_REGISTER) & CAPABILITIES_LEGACY)){
            logging::logf(logging::log_level::TRACE, "hpet: HPET is not able to handle legacy replacement mode\n");
            return;
        }

        if(!(read_register(CAPABILITIES_REGISTER) & CAPABILITIES_64)){
             logging::logf(logging::log_level::TRACE, "hpet: HPET is not able to handle 64-bit counter\n");
            return;
        }

        if(!(read_register(timer_configuration_reg(0)) & TIMER_CONFIG_64)){
             logging::logf(logging::log_level::TRACE, "hpet: HPET Timer #0 is not 64-bit\n");
            return;
        }

        // Get the frequency of the main counter

        auto hpet_period = read_register(CAPABILITIES_REGISTER) >> 32;
        auto hpet_frequency = 1000000000000000 / hpet_period;

        uint64_t current_frequency;
        if(hpet_frequency >= FREQUENCY_GOAL){
            current_frequency = FREQUENCY_GOAL;
        } else {
            current_frequency = hpet_frequency;
        }

        comparator_update = hpet_frequency / current_frequency;

        logging::logf(logging::log_level::TRACE, "hpet: period %u\n", hpet_period);
        logging::logf(logging::log_level::TRACE, "hpet: frequency %uHz\n", hpet_frequency);
        logging::logf(logging::log_level::TRACE, "hpet: IRQ frequency %uHz\n", current_frequency);
        logging::logf(logging::log_level::TRACE, "hpet: Comparator update %u\n", comparator_update);

        // Update the current frequency (this will update the sleeping task as well)
        timer::timer_frequency(current_frequency);

        // Give information about the counter
        timer::counter_fun(hpet::counter);
        timer::counter_frequency(hpet_frequency);

        // Uninstall the PIT driver
        pit::remove();

        // Register the IRQ handler
        if(!interrupt::register_irq_handler(0, timer_handler, nullptr)){
            logging::logf(logging::log_level::ERROR, "Unable to register HPET IRQ handler 0\n");
            // TODO At this point, we should reinstall the PIT driver
            suspend_kernel();
            return;
        }

        // Clear the main counter
        write_register(MAIN_COUNTER, 0);

        // Initialize timer #0
        clear_register_bits(timer_configuration_reg(0), TIMER_CONFIG_PERIODIC);
        set_register_bits(timer_configuration_reg(0), TIMER_CONFIG_ENABLE);
        write_register(timer_comparator_reg(0), comparator_update);

        // Enable HPET in legacy mode
        set_register_bits(GENERAL_CONFIG_REGISTER, GENERAL_CONFIG_LEGACY | GENERAL_CONFIG_ENABLE);
    }
}

uint64_t hpet::counter(){
    return read_register(MAIN_COUNTER);
}
<commit_msg>Refactor<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "drivers/hpet.hpp"

#include "acpica.hpp"
#include "logging.hpp"
#include "mmap.hpp"
#include "int_lock.hpp"
#include "kernel.hpp" // For suspend_kernel
#include "scheduler.hpp" // For async init
#include "timer.hpp"     // For setting the frequency

#include "drivers/pit.hpp" // For uninstalling it

// TODO Ideally, we should run in periodic mode
// However, I've not been able to make it work (no interrupt are generated)

namespace {

// Offset of the registers inside the hpet memory
constexpr const size_t CAPABILITIES_REGISTER = 0x0;
constexpr const size_t GENERAL_CONFIG_REGISTER = 0x10 / 8;
constexpr const size_t GENERAL_INTERRUPT_REGISTER = 0x20 / 8;
constexpr const size_t MAIN_COUNTER = 0xF0 / 8;

constexpr const size_t GENERAL_CONFIG_ENABLE = 1 << 0;
constexpr const size_t GENERAL_CONFIG_LEGACY = 1 << 1;

constexpr const size_t CAPABILITIES_LEGACY = 1 << 15;
constexpr const size_t CAPABILITIES_64 = 1 << 13;

constexpr const size_t TIMER_CONFIG_ENABLE = 1 << 2;
constexpr const size_t TIMER_CONFIG_PERIODIC = 1 << 3;
constexpr const size_t TIMER_CONFIG_PERIODIC_CAP = 1 << 5;
constexpr const size_t TIMER_CONFIG_64 = 1 << 5;

constexpr const size_t TIMER_FREQUENCY_GOAL = 10000; // 1 tick every 100 microseconds

ACPI_TABLE_HPET* hpet_table;
uint64_t* hpet_map;
volatile uint64_t comparator_update;

uint64_t timer_configuration_reg(uint64_t n){
    return (0x100 + 0x20 * n) / 8;
}

uint64_t timer_comparator_reg(uint64_t n){
    return (0x108 + 0x20 * n) / 8;
}

uint64_t timer_interrupt_reg(uint64_t n){
    return (0x110 + 0x20 * n) / 8;
}

uint64_t read_register(size_t reg){
    return hpet_map[reg];
}

void write_register(size_t reg, uint64_t value){
    hpet_map[reg] = value;
}

void set_register_bits(size_t reg, uint64_t bits){
    write_register(reg, read_register(reg) | bits);
}

void clear_register_bits(size_t reg, uint64_t bits){
    write_register(reg, read_register(reg) & ~bits);
}

void timer_handler(interrupt::syscall_regs*, void*){
    // Clears Tn_INT_STS
    set_register_bits(GENERAL_INTERRUPT_REGISTER, 1 << 0);

    // Sets the next event to fire an IRQ
    write_register(timer_comparator_reg(0), read_register(MAIN_COUNTER) + comparator_update);

    timer::tick();
}

} //End of anonymous namespace

void hpet::init(){
    // HPET needs ACPI
    scheduler::queue_async_init_task(hpet::late_install);
}

bool hpet::install(){
    // Find the HPET table
    auto status = AcpiGetTable(ACPI_SIG_HPET, 0, reinterpret_cast<ACPI_TABLE_HEADER **>(&hpet_table));
    if (ACPI_FAILURE(status)){
        return false;
    }

    logging::logf(logging::log_level::TRACE, "hpet: Found ACPI HPET table\n");

    return true;
}

void hpet::late_install(){
    if(hpet::install()){
        logging::logf(logging::log_level::TRACE, "hpet: Late install suceeded\n");

        logging::logf(logging::log_level::TRACE, "hpet: HPET Address: %h\n", hpet_table->Address.Address);

        hpet_map = static_cast<uint64_t*>(mmap_phys(hpet_table->Address.Address, 1024)); //TODO Check the size

        // Disable interrupts: We should not be interrupted from this point on
        direct_int_lock lock;

        // Disable before configuration
        clear_register_bits(GENERAL_CONFIG_REGISTER, GENERAL_CONFIG_ENABLE);

        if(!(read_register(CAPABILITIES_REGISTER) & CAPABILITIES_LEGACY)){
            logging::logf(logging::log_level::TRACE, "hpet: HPET is not able to handle legacy replacement mode\n");
            return;
        }

        if(!(read_register(CAPABILITIES_REGISTER) & CAPABILITIES_64)){
             logging::logf(logging::log_level::TRACE, "hpet: HPET is not able to handle 64-bit counter\n");
            return;
        }

        if(!(read_register(timer_configuration_reg(0)) & TIMER_CONFIG_64)){
             logging::logf(logging::log_level::TRACE, "hpet: HPET Timer #0 is not 64-bit\n");
            return;
        }

        // Get the frequency of the main counter

        auto hpet_period = read_register(CAPABILITIES_REGISTER) >> 32;
        auto hpet_frequency = 1000000000000000 / hpet_period;

        uint64_t current_frequency;
        if(hpet_frequency >= TIMER_FREQUENCY_GOAL){
            current_frequency = TIMER_FREQUENCY_GOAL;
        } else {
            current_frequency = hpet_frequency;
        }

        comparator_update = hpet_frequency / current_frequency;

        logging::logf(logging::log_level::TRACE, "hpet: period %u\n", hpet_period);
        logging::logf(logging::log_level::TRACE, "hpet: frequency %uHz\n", hpet_frequency);
        logging::logf(logging::log_level::TRACE, "hpet: IRQ frequency %uHz\n", current_frequency);
        logging::logf(logging::log_level::TRACE, "hpet: Comparator update %u\n", comparator_update);

        // Update the current frequency (this will update the sleeping task as well)
        timer::timer_frequency(current_frequency);

        // Give information about the counter
        timer::counter_fun(hpet::counter);
        timer::counter_frequency(hpet_frequency);

        // Uninstall the PIT driver
        pit::remove();

        // Register the IRQ handler
        if(!interrupt::register_irq_handler(0, timer_handler, nullptr)){
            logging::logf(logging::log_level::ERROR, "Unable to register HPET IRQ handler 0\n");
            // TODO At this point, we should reinstall the PIT driver
            suspend_kernel();
            return;
        }

        // Clear the main counter
        write_register(MAIN_COUNTER, 0);

        // Initialize timer #0
        clear_register_bits(timer_configuration_reg(0), TIMER_CONFIG_PERIODIC);
        set_register_bits(timer_configuration_reg(0), TIMER_CONFIG_ENABLE);
        write_register(timer_comparator_reg(0), comparator_update);

        // Enable HPET in legacy mode
        set_register_bits(GENERAL_CONFIG_REGISTER, GENERAL_CONFIG_LEGACY | GENERAL_CONFIG_ENABLE);
    }
}

uint64_t hpet::counter(){
    return read_register(MAIN_COUNTER);
}
<|endoftext|>


<commit_before>#include "./crab_lang.hpp"
#include "./crab_dom.hpp"

#include <crab/analysis/fwd_analyzer.hpp>
#include <crab/analysis/dataflow/liveness.hpp>

#include <crab/checkers/base_property.hpp>
#include <crab/checkers/assertion.hpp>
#include <crab/checkers/checker.hpp>

// Helper
template<typename CFG, typename Dom, typename IntraFwdAnalyzer>
void intra_run_impl (CFG* cfg,
		     bool run_liveness,
		     unsigned widening,
		     unsigned narrowing,
		     unsigned jump_set_size,
		     bool enable_stats,
		     bool enable_checker){
  typedef crab::cfg::cfg_ref<CFG> cfg_ref_t;
  crab::analyzer::liveness<cfg_ref_t> *live = nullptr;
  if (run_liveness) {
    crab::analyzer::liveness<cfg_ref_t> live_(*cfg);
    live_.exec ();
    live=&live_;
  }
  // Run fixpoint
  Dom inv = Dom::top ();
  crab::outs() << "Invariants using " << inv.getDomainName () << "\n";
  IntraFwdAnalyzer a (*cfg, inv, live, widening, narrowing, jump_set_size);

  a.run ();

  // Print invariants
  for (auto &b : *cfg) {
    auto inv = a[b.label ()];
    crab::outs() << crab::cfg_impl::get_label_str (b.label ()) << "="
		 << inv << "\n";
  }
  // Print abstract trace.
  // We consider as an abtract trace the WTO annotated with how many
  // times a cycle is visited by the fixpoint.
  auto &wto = a.get_wto ();
  crab::outs () << "Abstract trace: " << wto << "\n";

  if (enable_checker) {
    typedef crab::checker::intra_checker<IntraFwdAnalyzer> checker_t;
    typedef crab::checker::assert_property_checker<IntraFwdAnalyzer> assert_checker_t;
    const int verbose = 3;
    typename checker_t::prop_checker_ptr prop (new assert_checker_t (verbose));
    checker_t checker (a, {prop});
    checker.run ();
    checker.show (crab::outs());
  }

  crab::outs() << "\n";
  if (enable_stats) {
    crab::CrabStats::Print(crab::outs());
    crab::CrabStats::reset();
  }

}

// To run abstract domains defined over integers
template<typename Dom>
void run (crab::cfg_impl::z_cfg_t* cfg,
	  bool run_liveness,
	  unsigned widening,
	  unsigned narrowing,
	  unsigned jump_set_size,
	  bool enable_stats) {
  using namespace crab::analyzer;
  typedef intra_fwd_analyzer<crab::cfg_impl::z_cfg_ref_t, Dom> intra_fwd_analyzer_t;
  intra_run_impl<crab::cfg_impl::z_cfg_t, Dom, intra_fwd_analyzer_t>
    (cfg, run_liveness, widening, narrowing, jump_set_size, enable_stats, false);
}

template<typename Dom>
void run_and_check (crab::cfg_impl::z_cfg_t* cfg,
		    bool run_liveness,
		    unsigned widening,
		    unsigned narrowing,
		    unsigned jump_set_size,
		    bool enable_stats) {
  using namespace crab::analyzer;
  typedef intra_fwd_analyzer<crab::cfg_impl::z_cfg_ref_t, Dom> intra_fwd_analyzer_t;
  intra_run_impl<crab::cfg_impl::z_cfg_t, Dom, intra_fwd_analyzer_t>
    (cfg, run_liveness, widening, narrowing, jump_set_size, enable_stats, true);
}

// To run abstract domains defined over rationals
template<typename Dom>
void run (crab::cfg_impl::q_cfg_t* cfg,
	  bool run_liveness,
	  unsigned widening,
	  unsigned narrowing,
	  unsigned jump_set_size,
	  bool enable_stats) {
  using namespace crab::analyzer;
  typedef intra_fwd_analyzer<crab::cfg_impl::q_cfg_ref_t,Dom> intra_fwd_analyzer_t;
  intra_run_impl<crab::cfg_impl::q_cfg_t, Dom, intra_fwd_analyzer_t>
    (cfg, run_liveness, widening, narrowing, jump_set_size, enable_stats, false);
}

////////
//// Explicit instantiations here
////////

#include "./crab_inst.hpp"
<commit_msg>[FIXED] escape address of stack object<commit_after>#include "./crab_lang.hpp"
#include "./crab_dom.hpp"

#include <crab/analysis/fwd_analyzer.hpp>
#include <crab/analysis/dataflow/liveness.hpp>

#include <crab/checkers/base_property.hpp>
#include <crab/checkers/assertion.hpp>
#include <crab/checkers/checker.hpp>

// Helper
template<typename CFG, typename Dom, typename IntraFwdAnalyzer>
void intra_run_impl (CFG* cfg,
		     bool run_liveness,
		     unsigned widening,
		     unsigned narrowing,
		     unsigned jump_set_size,
		     bool enable_stats,
		     bool enable_checker){
  typedef crab::cfg::cfg_ref<CFG> cfg_ref_t;
  crab::analyzer::liveness<cfg_ref_t> live(*cfg);
  if (run_liveness) {
    live.exec ();
  }
  // Run fixpoint
  Dom inv = Dom::top ();
  crab::outs() << "Invariants using " << inv.getDomainName () << "\n";
  IntraFwdAnalyzer a (*cfg, inv,
		      (run_liveness) ? &live : nullptr,
		      widening, narrowing, jump_set_size);

  a.run ();

  // Print invariants
  for (auto &b : *cfg) {
    auto inv = a[b.label ()];
    crab::outs() << crab::cfg_impl::get_label_str (b.label ()) << "="
		 << inv << "\n";
  }
  // Print abstract trace.
  // We consider as an abtract trace the WTO annotated with how many
  // times a cycle is visited by the fixpoint.
  auto &wto = a.get_wto ();
  crab::outs () << "Abstract trace: " << wto << "\n";

  if (enable_checker) {
    typedef crab::checker::intra_checker<IntraFwdAnalyzer> checker_t;
    typedef crab::checker::assert_property_checker<IntraFwdAnalyzer> assert_checker_t;
    const int verbose = 3;
    typename checker_t::prop_checker_ptr prop (new assert_checker_t (verbose));
    checker_t checker (a, {prop});
    checker.run ();
    checker.show (crab::outs());
  }

  crab::outs() << "\n";
  if (enable_stats) {
    crab::CrabStats::Print(crab::outs());
    crab::CrabStats::reset();
  }

}

// To run abstract domains defined over integers
template<typename Dom>
void run (crab::cfg_impl::z_cfg_t* cfg,
	  bool run_liveness,
	  unsigned widening,
	  unsigned narrowing,
	  unsigned jump_set_size,
	  bool enable_stats) {
  using namespace crab::analyzer;
  typedef intra_fwd_analyzer<crab::cfg_impl::z_cfg_ref_t, Dom> intra_fwd_analyzer_t;
  intra_run_impl<crab::cfg_impl::z_cfg_t, Dom, intra_fwd_analyzer_t>
    (cfg, run_liveness, widening, narrowing, jump_set_size, enable_stats, false);
}

template<typename Dom>
void run_and_check (crab::cfg_impl::z_cfg_t* cfg,
		    bool run_liveness,
		    unsigned widening,
		    unsigned narrowing,
		    unsigned jump_set_size,
		    bool enable_stats) {
  using namespace crab::analyzer;
  typedef intra_fwd_analyzer<crab::cfg_impl::z_cfg_ref_t, Dom> intra_fwd_analyzer_t;
  intra_run_impl<crab::cfg_impl::z_cfg_t, Dom, intra_fwd_analyzer_t>
    (cfg, run_liveness, widening, narrowing, jump_set_size, enable_stats, true);
}

// To run abstract domains defined over rationals
template<typename Dom>
void run (crab::cfg_impl::q_cfg_t* cfg,
	  bool run_liveness,
	  unsigned widening,
	  unsigned narrowing,
	  unsigned jump_set_size,
	  bool enable_stats) {
  using namespace crab::analyzer;
  typedef intra_fwd_analyzer<crab::cfg_impl::q_cfg_ref_t,Dom> intra_fwd_analyzer_t;
  intra_run_impl<crab::cfg_impl::q_cfg_t, Dom, intra_fwd_analyzer_t>
    (cfg, run_liveness, widening, narrowing, jump_set_size, enable_stats, false);
}

////////
//// Explicit instantiations here
////////

#include "./crab_inst.hpp"
<|endoftext|>


<commit_before><commit_msg>fix std::max mismatched type compile snafu<commit_after><|endoftext|>


<commit_before>
#include <tree.hpp>
#include <catch.hpp>

SCENARIO("null")
{
	Tree<int> a;
	REQUIRE(a.tree_one()==NULL);
}
SCENARIO("add")
{
	Tree<int> a;
	bool b=a.add(5);
	REQUIRE(b == 1);
}
SCENARIO("find")
{
	Tree<int> a;
	a.add(5);
	bool b = a.find(5);
	REQUIRE(b == 1);
}
<commit_msg>Update init.cpp<commit_after>
#include <tree.hpp>
#include <catch.hpp>

SCENARIO("null")
{
	Tree<int> a;
	REQUIRE(a.tree_one()==NULL);
}
<|endoftext|>


<commit_before>#include "stack.hpp"
#include <catch.hpp>
#include <iostream>
#include <thread>
using namespace std;

SCENARIO("count", "[count]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
}

SCENARIO("push", "[push]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
  REQUIRE(s.top()==1);
}

SCENARIO("pop", "[pop]"){
  stack<int> s;
  s.push(1); s.pop();
  REQUIRE(s.count()==0);
}

SCENARIO("cop", "[cop]"){
  stack<int> s;
  s.push(1);
  stack<int> s2=s;
  REQUIRE(s.count()==1);
  REQUIRE(s.top()==1);
}

SCENARIO("top", "[top]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.top()==1);
}

SCENARIO("empty", "[empty]"){
  stack<int> s1, s2;
  s1.push(1);
  REQUIRE(!s1.empty());
  REQUIRE(s2.empty());
}
SCENARIO("threads", "[threads]"){
  stack<int> s;
  std::thread t1(&stack::push, s, 1);
  std::thread t2(&stack::pop, s);
  t1.join();
  t2.join();
  REQUIRE(s.count()==0);
}

<commit_msg>Update init.cpp<commit_after>#include "stack.hpp"
#include <catch.hpp>
#include <iostream>
#include <thread>
using namespace std;

SCENARIO("count", "[count]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
}

SCENARIO("push", "[push]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.count()==1);
  REQUIRE(s.top()==1);
}

SCENARIO("pop", "[pop]"){
  stack<int> s;
  s.push(1); s.pop();
  REQUIRE(s.count()==0);
}

SCENARIO("cop", "[cop]"){
  stack<int> s;
  s.push(1);
  stack<int> s2=s;
  REQUIRE(s.count()==1);
  REQUIRE(s.top()==1);
}

SCENARIO("top", "[top]"){
  stack<int> s;
  s.push(1);
  REQUIRE(s.top()==1);
}

SCENARIO("empty", "[empty]"){
  stack<int> s1, s2;
  s1.push(1);
  REQUIRE(!s1.empty());
  REQUIRE(s2.empty());
}
SCENARIO("threads", "[threads]"){
 stack<int> s;
	std::thread t1([&s]() {s.push(1); });
	std::thread t2([&s]() {s.pop(); });
	t1.join();
	t2.join();
  REQUIRE(s.count()==0);
}

<|endoftext|>


<commit_before>#include "catch.hpp"

#include "stack.hpp"

TEST_CASE("Stack can be instantiated by various types", "[instantiation]") {
	REQUIRE_NOTHROW(stack<int> st1);
	REQUIRE_NOTHROW(stack<double> st1);
	REQUIRE_NOTHROW(stack<char> st1);
	REQUIRE_NOTHROW(stack<int*> st1);
	REQUIRE_NOTHROW(stack<stack<int>> st1);
}
TEST_CASE("Push, pop, top", "[push_pop_top]") {
	stack<int> st;
	st.push(1);
	st.push(2);
	REQUIRE(st.top() == 2);
	st.pop();
	REQUIRE(st.top() == 1);
	st.pop();
}
TEST_CASE("count", "[count]") {
	stack<int> st;
	REQUIRE(st.count() == 0);
	st.push(1);
	REQUIRE(st.count() == 1);
	st.push(2);
	REQUIRE(st.count() == 2);
	st.pop();
	REQUIRE(st.count() == 1);
	st.pop();
	REQUIRE(st.count() == 0);
}
TEST_CASE("Copy constructor, =", "[copy_ctr, =]") {
	stack<int> st1;
	st1.push(1);
	st1.push(2);
	REQUIRE_NOTHROW(stack<int> st2 = st1);
	REQUIRE_NOTHROW(stack<int> st2;
	st2 = st1);

	stack<int> st3 = st1;
	stack<int> st4 = st1;
	REQUIRE(st1.top() == 2);
	REQUIRE(st3.top() == 2);
	st3.pop();
	REQUIRE(st3.top() == 1);
	REQUIRE(st4.top() == 2);
	st4.pop();
	REQUIRE(st4.top() == 1);
}
TEST_CASE("Empty", "[empty]") {
	stack<int> st1;
	REQUIRE(st1.empty());
	st1.push(38);
	REQUIRE(!st1.empty());
}
TEST_CASE("Allocator doesn't (use or need) default ctors", "[allocator]") {
	class A {
	public:
		A() {
			throw "ctor is called";
		}
		A(int a) {
			;
		}
	};
	REQUIRE_NOTHROW(
		stack<A> st;
		st.push(4);
		st.push(20);
	);
	class B {
	public:
		B(int a) {
			;
		}
	};
	stack<B> st;
	st.push(40);
}
bool dtor_is_called1 = false;
TEST_CASE("Allocator calls dtors", "[allocator]") {
	class A {
	public:
		A(int a) {
			;
		}
		~A() {
			dtor_is_called1 = true;
		}
	};
	stack<A> st;
	st.push(32);
	st.pop();
	REQUIRE(dtor_is_called1);
}
<commit_msg>+ equal test<commit_after>#include "catch.hpp"

#include "stack.hpp"

TEST_CASE("Stack can be instantiated by various types", "[instantiation]") {
	REQUIRE_NOTHROW(stack<int> st1);
	REQUIRE_NOTHROW(stack<double> st1);
	REQUIRE_NOTHROW(stack<char> st1);
	REQUIRE_NOTHROW(stack<int*> st1);
	REQUIRE_NOTHROW(stack<stack<int>> st1);
}
TEST_CASE("Push, pop, top", "[push_pop_top]") {
	stack<int> st;
	st.push(1);
	st.push(2);
	REQUIRE(st.top() == 2);
	st.pop();
	REQUIRE(st.top() == 1);
	st.pop();
}
TEST_CASE("count", "[count]") {
	stack<int> st;
	REQUIRE(st.count() == 0);
	st.push(1);
	REQUIRE(st.count() == 1);
	st.push(2);
	REQUIRE(st.count() == 2);
	st.pop();
	REQUIRE(st.count() == 1);
	st.pop();
	REQUIRE(st.count() == 0);
}
TEST_CASE("Copy constructor", "[copy_ctr]") {
	stack<int> st1;
	st1.push(1);
	st1.push(2);
	REQUIRE_NOTHROW(stack<int> st2 = st1);

	stack<int> st3 = st1;
	stack<int> st4 = st1;
	REQUIRE(st1.top() == 2);
	REQUIRE(st3.top() == 2);
	st3.pop();
	REQUIRE(st3.top() == 1);
	REQUIRE(st4.top() == 2);
	st4.pop();
	REQUIRE(st4.top() == 1);
}
TEST_CASE("Equal", "[equal]") {
	stack<int> st1;
	REQUIRE_NOTHROW(stack<int> st2;
	st2 = st1);
	stack<int> st2;
	st1.push(1);
	st1.push(4);
	st2 = st1;
	REQUIRE(st2.top() == 4);
	st2.pop();
	REQUIRE(st2.top() == 1);
}
TEST_CASE("Empty", "[empty]") {
	stack<int> st1;
	REQUIRE(st1.empty());
	st1.push(38);
	REQUIRE(!st1.empty());
}
TEST_CASE("Allocator doesn't (use or need) default ctors", "[allocator]") {
	class A {
	public:
		A() {
			throw "ctor is called";
		}
		A(int a) {
			;
		}
	};
	REQUIRE_NOTHROW(
		stack<A> st;
		st.push(4);
		st.push(20);
	);
	class B {
	public:
		B(int a) {
			;
		}
	};
	stack<B> st;
	st.push(40);
}
bool dtor_is_called1 = false;
TEST_CASE("Allocator calls dtors", "[allocator]") {
	class A {
	public:
		A(int a) {
			;
		}
		~A() {
			dtor_is_called1 = true;
		}
	};
	stack<A> st;
	st.push(32);
	st.pop();
	REQUIRE(dtor_is_called1);
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
extern "C" {
  #include "config.h"
  #include "debug.h"
  #include "util.h"
  #include "loop.h"
  #include "process.h"
  #include "profile.h"
  #include "socket.h"
  #include "msg.h"
  #include "iface.h"
  #include "id.h"
}
#include "gtest/gtest.h"

extern co_socket_t unix_socket_proto;

bool timer1_success = false;
bool timer2_success = false;
bool timer3_success = false;

int timer1_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params);
int timer2_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params);
int timer3_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params);
int loop_stop_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params);

class LoopTest : public ::testing::Test
{
  protected:
    int ret;

    // context pointers
    co_obj_t *context1;
    co_obj_t *context2;
    co_obj_t *context3;
    co_obj_t *context4;
    co_obj_t *stop;

    // time values
    struct timeval timeval1;
    struct timeval timeval2;
    struct timeval timeval3;
    struct timeval tv_stop;

    // tests
    void Timer();
    void Socket();

    LoopTest()
    {
      ret = co_loop_create();
      // CHECK((poll_fd = epoll_create1(EPOLL_CLOEXEC)) != -1, "Failed to create epoll event.");
    }

  virtual void SetUp()
  {
  }

  ~LoopTest()
  {
    ret = co_loop_destroy();
  }
};

void LoopTest::Timer()
{
  // intialize timer1
  co_obj_t *timer1 = co_timer_create(timeval1, timer1_cb, context1);
  ret = co_loop_set_timer(timer1, 1, context1);
  ASSERT_EQ(1, ret);

  // initialize timer2
  co_obj_t *timer2 = co_timer_create(timeval2, timer2_cb, context2);
  ret = co_loop_set_timer(timer2, 1, context1);
  ASSERT_EQ(1, ret);

  // initialize timer3
  co_obj_t *timer3 = co_timer_create(timeval3, timer3_cb, context3);
  ret = co_loop_set_timer(timer3, 1, context1);
  ASSERT_EQ(1, ret);

  // stops the loop (after 100 ms)
  co_obj_t *loop_stop = co_timer_create(tv_stop, loop_stop_cb, stop);
  ret = co_loop_set_timer(loop_stop, 100, stop);
  ASSERT_EQ(1, ret);

  co_loop_start();

  EXPECT_TRUE(timer1_success);
  EXPECT_TRUE(timer2_success);
  EXPECT_TRUE(timer3_success);
}

void LoopTest::Socket()
{
  // NOTE: co_socket_init is not used right now

  // initialize socket and register it with the event loop
  co_socket_t *socket1 = (co_socket_t*)co_socket_create(sizeof(co_socket_t), unix_socket_proto);
  socket1->register_cb = co_loop_add_socket;
  socket1->bind((co_obj_t*)socket1, "commotiontest.sock");

  // remove socket from loop
  ret = co_loop_remove_socket((co_obj_t *)socket1, NULL);
  ASSERT_EQ(1, ret);

  // destroy socket
  ret = co_socket_destroy((co_obj_t *)socket1);
  ASSERT_EQ(1, ret);

}

TEST_F(LoopTest, Timer)
{
  Timer();
}

TEST_F(LoopTest, Socket)
{
  Socket();
}

// callback functions
  int timer1_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params)
{
  timer1_success = true;
  return 1;
}

int timer2_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params)
{
  timer2_success = true;
  return 1;
}

int timer3_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params)
{
  timer3_success = true;
  return 1;
}

// loop stop function (currently unused)
int loop_stop_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params)
{
  co_loop_stop(); // breaks loop without returning
  return 1;
}<commit_msg>clean up<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
extern "C" {
  #include "config.h"
  #include "debug.h"
  #include "util.h"
  #include "loop.h"
  #include "process.h"
  #include "profile.h"
  #include "socket.h"
  #include "msg.h"
  #include "iface.h"
  #include "id.h"
}
#include "gtest/gtest.h"

extern co_socket_t unix_socket_proto;

bool timer1_success = false;
bool timer2_success = false;
bool timer3_success = false;

int timer1_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params);
int timer2_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params);
int timer3_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params);
int loop_stop_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params);

class LoopTest : public ::testing::Test
{
  protected:
    int ret;

    // context pointers
    co_obj_t *context1;
    co_obj_t *context2;
    co_obj_t *context3;
    co_obj_t *stop;

    // time values
    struct timeval timeval1;
    struct timeval timeval2;
    struct timeval timeval3;
    struct timeval tv_stop;

    // tests
    void Timer();
    void Socket();

    LoopTest()
    {
      ret = co_loop_create();
      // CHECK((poll_fd = epoll_create1(EPOLL_CLOEXEC)) != -1, "Failed to create epoll event.");
    }

  virtual void SetUp()
  {
  }

  ~LoopTest()
  {
    ret = co_loop_destroy();
  }
};

void LoopTest::Timer()
{
  // intialize timer1
  co_obj_t *timer1 = co_timer_create(timeval1, timer1_cb, context1);
  ret = co_loop_set_timer(timer1, 1, context1);
  ASSERT_EQ(1, ret);

  // initialize timer2
  co_obj_t *timer2 = co_timer_create(timeval2, timer2_cb, context2);
  ret = co_loop_set_timer(timer2, 1, context1);
  ASSERT_EQ(1, ret);

  // initialize timer3
  co_obj_t *timer3 = co_timer_create(timeval3, timer3_cb, context3);
  ret = co_loop_set_timer(timer3, 1, context1);
  ASSERT_EQ(1, ret);

  // stops the loop (after 100 ms)
  co_obj_t *loop_stop = co_timer_create(tv_stop, loop_stop_cb, stop);
  ret = co_loop_set_timer(loop_stop, 100, stop);
  ASSERT_EQ(1, ret);

  co_loop_start();

  EXPECT_TRUE(timer1_success);
  EXPECT_TRUE(timer2_success);
  EXPECT_TRUE(timer3_success);
}

void LoopTest::Socket()
{
  // initialize socket and register it with the event loop
  co_socket_t *socket1 = (co_socket_t*)co_socket_create(sizeof(co_socket_t), unix_socket_proto);
  socket1->register_cb = co_loop_add_socket;
  socket1->bind((co_obj_t*)socket1, "commotiontest.sock");

  // remove socket from loop
  ret = co_loop_remove_socket((co_obj_t *)socket1, NULL);
  ASSERT_EQ(1, ret);

  // destroy socket
  ret = co_socket_destroy((co_obj_t *)socket1);
  ASSERT_EQ(1, ret);
}

TEST_F(LoopTest, Timer)
{
  Timer();
}

TEST_F(LoopTest, Socket)
{
  Socket();
}

// callback functions
  int timer1_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params)
{
  timer1_success = true;
  return 1;
}

int timer2_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params)
{
  timer2_success = true;
  return 1;
}

int timer3_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params)
{
  timer3_success = true;
  return 1;
}

// loop stop function (currently unused)
int loop_stop_cb(co_obj_t *self, co_obj_t **output, co_obj_t *params)
{
  co_loop_stop(); // breaks loop without returning
  return 1;
}<|endoftext|>


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

#include "mirtk/Common.h"
#include "mirtk/Options.h"

#include "mirtk/EdgeTable.h"
#include "mirtk/PointSetUtils.h"

#include "vtkSmartPointer.h"
#include "vtkPolyData.h"

#include "gtest/gtest.h"

using namespace mirtk;

// =============================================================================
// Global variables / test arguments
// =============================================================================

const char *input_name = nullptr;

// =============================================================================
// Tests
// =============================================================================

// -----------------------------------------------------------------------------
TEST(EdgeTable, Initialize)
{
  // Read input point set
  ASSERT_TRUE(input_name != nullptr) << "input point set given";
  vtkSmartPointer<vtkPolyData> input = ReadPolyData(input_name, NULL, false);
  const int npoints = static_cast<int>(input->GetNumberOfPoints());
  ASSERT_GT(npoints, 0) << "input point set contains points";

  // Construct edge table
  EdgeTable edgeTable(input);
  ASSERT_EQ(EdgeTable::CCS, edgeTable.Layout()) << "sparse matrix layout is CCS";
  ASSERT_EQ(npoints, edgeTable.Rows()) << "one row for each point";
  ASSERT_EQ(npoints, edgeTable.Cols()) << "one column for each point";
  ASSERT_TRUE(edgeTable.IsSymmetric()) << "edge table is a symmetric matrix";

  // All upper triangular entries are unique and in ascending order
  // and verify that CCS sparse matrix entries are sorted with unique row entries
  int edgeId = 0;
  OrderedSet<int> rows;
  EdgeTable::Entries entries;
  EdgeTable::Entries::const_iterator it;
  OrderedSet<int>::const_iterator rowsIt;
  for (int c = 0, r; c < npoints; ++c) {
    edgeTable.GetCol(c, entries);
    rows.clear();
    for (it = entries.begin(); it != entries.end(); ++it) {
      rows.insert(it->first);
    }
    ASSERT_EQ(rows.size(), entries.size()) << "row entries are unique";
    for (it = entries.begin(), rowsIt = rows.begin(); it != entries.end(); ++it, ++rowsIt) {
      ASSERT_EQ(*rowsIt, it->first) << "row entries are sorted";
    }
    for (it = entries.begin(); it != entries.end(); ++it) {
      r = it->first;
      if (r > c) break;
      ASSERT_EQ(++edgeId, it->second);
    }
  }
  ASSERT_EQ(edgeId, edgeTable.NumberOfEdges()) << "all edges have a unique ID";
}

// -----------------------------------------------------------------------------
TEST(EdgeTable, EdgeIterator)
{
  vtkIdType pid1, pid2;

  // Read input point set
  ASSERT_TRUE(input_name != nullptr) << "input point set given";
  vtkSmartPointer<vtkPolyData> input = ReadPolyData(input_name, NULL, false);
  ASSERT_TRUE(input->GetNumberOfPoints() > 0) << "input point set contains points";

  // Construct edge table and iterator
  EdgeTable edgeTable(input);
  EdgeIterator it(edgeTable);

  // Check that each edge is returned by iterator exactly one time
  // and that the order of edge IDs is the ascening sequence of positive integers
  it.InitTraversal();
  int edgeId, edgeCount = 0;
  while ((edgeId = it.GetNextEdge(pid1, pid2)) != -1) {
    ASSERT_EQ(edgeCount++, edgeId) << "edges are iterated by ascending edge ID";
    ASSERT_EQ(edgeId, edgeTable.EdgeId(pid1, pid2))
        << "EdgeTable::EdgeId consistent with ID returned by EdgeTable::GetNextEdge";
    ASSERT_LE(pid1, pid2) << "order of returned point IDs is such that ptId1 <= ptId2";
  }
  ASSERT_EQ(edgeCount, edgeTable.NumberOfEdges()) << "all edges are being iterated";
}

// =============================================================================
// Main
// =============================================================================

// -----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
  ::testing::InitGoogleTest(&argc, argv);
  input_name = argv[1];
  return RUN_ALL_TESTS();
}
<commit_msg>fix: Build of unit test [PointSet]<commit_after>/*
 * Medical Image Registration ToolKit (MIRTK)
 *
 * Copyright 2016 Imperial College London
 * Copyright 2016 Andreas Schuh
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "mirtk/Common.h"
#include "mirtk/Options.h"

#include "mirtk/EdgeTable.h"
#include "mirtk/PointSetIO.h"

#include "vtkSmartPointer.h"
#include "vtkPolyData.h"

#include "gtest/gtest.h"

using namespace mirtk;

// =============================================================================
// Global variables / test arguments
// =============================================================================

const char *input_name = nullptr;

// =============================================================================
// Tests
// =============================================================================

// -----------------------------------------------------------------------------
TEST(EdgeTable, Initialize)
{
  // Read input point set
  ASSERT_TRUE(input_name != nullptr) << "input point set given";
  vtkSmartPointer<vtkPolyData> input = ReadPolyData(input_name, NULL, false);
  const int npoints = static_cast<int>(input->GetNumberOfPoints());
  ASSERT_GT(npoints, 0) << "input point set contains points";

  // Construct edge table
  EdgeTable edgeTable(input);
  ASSERT_EQ(EdgeTable::CCS, edgeTable.Layout()) << "sparse matrix layout is CCS";
  ASSERT_EQ(npoints, edgeTable.Rows()) << "one row for each point";
  ASSERT_EQ(npoints, edgeTable.Cols()) << "one column for each point";
  ASSERT_TRUE(edgeTable.IsSymmetric()) << "edge table is a symmetric matrix";

  // All upper triangular entries are unique and in ascending order
  // and verify that CCS sparse matrix entries are sorted with unique row entries
  int edgeId = 0;
  OrderedSet<int> rows;
  EdgeTable::Entries entries;
  EdgeTable::Entries::const_iterator it;
  OrderedSet<int>::const_iterator rowsIt;
  for (int c = 0, r; c < npoints; ++c) {
    edgeTable.GetCol(c, entries);
    rows.clear();
    for (it = entries.begin(); it != entries.end(); ++it) {
      rows.insert(it->first);
    }
    ASSERT_EQ(rows.size(), entries.size()) << "row entries are unique";
    for (it = entries.begin(), rowsIt = rows.begin(); it != entries.end(); ++it, ++rowsIt) {
      ASSERT_EQ(*rowsIt, it->first) << "row entries are sorted";
    }
    for (it = entries.begin(); it != entries.end(); ++it) {
      r = it->first;
      if (r > c) break;
      ASSERT_EQ(++edgeId, it->second);
    }
  }
  ASSERT_EQ(edgeId, edgeTable.NumberOfEdges()) << "all edges have a unique ID";
}

// -----------------------------------------------------------------------------
TEST(EdgeTable, EdgeIterator)
{
  vtkIdType pid1, pid2;

  // Read input point set
  ASSERT_TRUE(input_name != nullptr) << "input point set given";
  vtkSmartPointer<vtkPolyData> input = ReadPolyData(input_name, NULL, false);
  ASSERT_TRUE(input->GetNumberOfPoints() > 0) << "input point set contains points";

  // Construct edge table and iterator
  EdgeTable edgeTable(input);
  EdgeIterator it(edgeTable);

  // Check that each edge is returned by iterator exactly one time
  // and that the order of edge IDs is the ascening sequence of positive integers
  it.InitTraversal();
  int edgeId, edgeCount = 0;
  while ((edgeId = it.GetNextEdge(pid1, pid2)) != -1) {
    ASSERT_EQ(edgeCount++, edgeId) << "edges are iterated by ascending edge ID";
    ASSERT_EQ(edgeId, edgeTable.EdgeId(pid1, pid2))
        << "EdgeTable::EdgeId consistent with ID returned by EdgeTable::GetNextEdge";
    ASSERT_LE(pid1, pid2) << "order of returned point IDs is such that ptId1 <= ptId2";
  }
  ASSERT_EQ(edgeCount, edgeTable.NumberOfEdges()) << "all edges are being iterated";
}

// =============================================================================
// Main
// =============================================================================

// -----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
  ::testing::InitGoogleTest(&argc, argv);
  input_name = argv[1];
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "sphere.hpp"
#include "box.hpp"

TEST_CASE("Sphere default construction", "[constructor]") {
        Sphere s{};
        REQUIRE(s.getRadius() == 0.0);
        REQUIRE(s.getCenter() == {0.0, 0.0, 0.0});
}

TEST_CASE("Sphere construction", "[constructor]") {
        Sphere s{{1.0, 1.0, 0.0}, 5.0};
        REQUIRE(s.getRadius() == 5.0);
        REQUIRE(s.getCenter() == {1.0, 1.0, 1.0});
}

TEST_CASE("Sphere radius-only construction", "[constructor]") {
        Sphere s{5.0};
        REQUIRE(s.getRadius() == 5.0);
        REQUIRE(s.getCenter() == {0.0, 0.0, 0.0});
}

TEST_CASE("Sphere copy construction", "[constructor]") {
        Sphere s1{5.0};
        Sphere s2(s1);
        REQUIRE(s2 == s1);
}

TEST_CASE("Sphere move construction", "[constructor]") {
        Sphere s1{5.0};
        Sphere s2(std::move(s1));
        REQUIRE(s2.getRadius() == 5.0);
        REQUIRE(s2.getCenter() == {0.0, 0.0, 0.0});
        REQUIRE(s1.getRadius() == 0.0);
        REQUIRE(s1.getCenter() == {0.0, 0.0, 0.0});
}

TEST_CASE("Sphere area calculation", "[area]") {
        Sphere s{1.0};
        REQUIRE(s.area() == Approx(12.566370614359173));
}

TEST_CASE("Sphere volume calculation", "[volume]") {
        Sphere s{1.0};
        REQUIRE(s.volume() == Approx(4.188790204786391));
}

int main(int argc, char *argv[])
{
  return Catch::Session().run(argc, argv);
}
<commit_msg>Added tests for sphere.<commit_after>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "sphere.hpp"
#include "box.hpp"

TEST_CASE("Sphere default construction", "[constructor]") {
        Sphere s{};
        glm::vec3 c{0.0, 0.0, 0.0};
        REQUIRE(s.getRadius() == 0.0);
        REQUIRE(s.getCenter() == c);
}

TEST_CASE("Sphere construction", "[constructor]") {
        glm::vec3 c{1.0, 1.0, 1.0};
        Sphere s{c, 5.0};
        REQUIRE(s.getRadius() == 5.0);
        REQUIRE(s.getCenter() == c);
}

TEST_CASE("Sphere radius-only construction", "[constructor]") {
        Sphere s{5.0};
        glm::vec3 c{0.0, 0.0, 0.0};
        REQUIRE(s.getRadius() == 5.0);
        REQUIRE(s.getCenter() == c);
}

TEST_CASE("Sphere copy construction", "[constructor]") {
        Sphere s1{5.0};
        Sphere s2(s1);
        REQUIRE(s2.getRadius() == s1.getRadius());
        REQUIRE(s2.getCenter() == s1.getCenter());
}

TEST_CASE("Sphere move construction", "[constructor]") {
        Sphere s1{5.0};
        Sphere s2(std::move(s1));
        glm::vec3 c{0.0, 0.0, 0.0};
        REQUIRE(s2.getRadius() == 5.0);
        REQUIRE(s2.getCenter() == c);
        REQUIRE(s1.getRadius() == 0.0);
        REQUIRE(s1.getCenter() == c);
}

TEST_CASE("Sphere area calculation", "[area]") {
        Sphere s{1.0};
        REQUIRE(s.area() == Approx(12.566370614359173));
}

TEST_CASE("Sphere volume calculation", "[volume]") {
        Sphere s{1.0};
        REQUIRE(s.volume() == Approx(4.188790204786391));
}

int main(int argc, char *argv[])
{
  return Catch::Session().run(argc, argv);
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include "error.h"
#include "sim.h"
#include "particule.h"

int main (int argc, char *argv[])
{
	enum argument {Error, Force, Integration, Graphic, Simulation};
	switch(*argv[1])
	{
		case Error: sim_error(argv[2]);
		case Force: sim_force(argv[2]);
		case Integration: sim_integration(argv[2]);
		case Graphic: sim_graphic(argv[2]);
		case Simulation: sim_simulation(argv[2]);
		default: error_msg("invalid argument in main (main.cpp)");
	}
	return 0;
}

//argv[0] pointe sur une chaîne vide.
//argv[1] mode de test
//argv[2] nom du fichier
<commit_msg>update main.cpp apres discussion fb<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "error.h"
#include "sim.h"

enum Mode {ERROR, FORCE, INTEGRATION, GRAPHIC, SIMULATION};

int main (int argc, char *argv[])
{
    enum Mode mode;

    if(strcmp(argv[1], "Error" ) == 0)
    {
		mode = ERROR;
    }
    else if (strcmp(argv[1], "Force" ) == 0)
    {
		mode = FORCE;
    }
    else if (strcmp(argv[1], "Integration" ) == 0)
    {
		mode = INTEGRATION;
    }
    else if (strcmp(argv[1], "Graphic" ) == 0)
    {
		mode = GRAPHIC;
    }
    else if (strcmp(argv[1], "Simulation" ) == 0)
    {
		mode = SIMULATION;
    }

	if(argc==1)
	{
		//initialise interface graphique //demo.x a revoir
	}
	else
	{
		switch(mode)
		{
			case ERROR: sim_error(argv[2]);
			break;
			case FORCE: sim_force(argv[2]);
			break;
			case INTEGRATION: sim_integration(argv[2]);
			break;
			case GRAPHIC: sim_graphic(argv[2]);
			break;
			case SIMULATION: sim_simulation(argv[2]);
			break;
			//default: error_msg("invalid argument in main (main.cpp)");
		}
	}
	return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>//
//  CRTContants.hpp
//  Clock Signal
//
//  Created by Thomas Harte on 19/03/2016.
//  Copyright © 2016 Thomas Harte. All rights reserved.
//

#ifndef CRTConstants_h
#define CRTConstants_h

#include "OpenGL.hpp"
#include <cstddef>

namespace Outputs {
namespace CRT {

// Output vertices are those used to copy from an input buffer — whether it describes data that maps directly to RGB
// or is one of the intermediate buffers that we've used to convert from composite towards RGB.
const GLsizei OutputVertexOffsetOfHorizontal = 0;
const GLsizei OutputVertexOffsetOfVertical = 4;

const GLsizei OutputVertexSize = 8;

// Input vertices, used only in composite mode, map from the input buffer to temporary buffer locations; such
// remapping occurs to ensure a continous stream of data for each scan, giving correct out-of-bounds behaviour
const GLsizei SourceVertexOffsetOfInputStart = 0;
const GLsizei SourceVertexOffsetOfOutputStart = 4;
const GLsizei SourceVertexOffsetOfEnds = 8;
const GLsizei SourceVertexOffsetOfPhaseTimeAndAmplitude = 12;

const GLsizei SourceVertexSize = 16;

// These constants hold the size of the rolling buffer to which the CPU writes
const GLsizei InputBufferBuilderWidth = 2048;
const GLsizei InputBufferBuilderHeight = 512;

// This is the size of the intermediate buffers used during composite to RGB conversion
const GLsizei IntermediateBufferWidth = 2048;
const GLsizei IntermediateBufferHeight = 1024;

// Some internal buffer sizes
const GLsizeiptr OutputVertexBufferDataSize = OutputVertexSize * IntermediateBufferHeight;		// i.e. the maximum number of scans of output that can be created between draws
const GLsizeiptr SourceVertexBufferDataSize = SourceVertexSize * IntermediateBufferHeight * 10;	// (the maximum number of scans) * conservative, high guess at a maximumum number of events likely to occur within a scan

// TODO: when SourceVertexBufferDataSize is exhausted, the CRT keeps filling OutputVertexBufferDataSize regardless,
// leading to empty scanlines that nevertheless clear old contents.

}
}

#endif /* CRTContants_h */
<commit_msg>Reduced buffer size.<commit_after>//
//  CRTContants.hpp
//  Clock Signal
//
//  Created by Thomas Harte on 19/03/2016.
//  Copyright © 2016 Thomas Harte. All rights reserved.
//

#ifndef CRTConstants_h
#define CRTConstants_h

#include "OpenGL.hpp"
#include <cstddef>

namespace Outputs {
namespace CRT {

// Output vertices are those used to copy from an input buffer — whether it describes data that maps directly to RGB
// or is one of the intermediate buffers that we've used to convert from composite towards RGB.
const GLsizei OutputVertexOffsetOfHorizontal = 0;
const GLsizei OutputVertexOffsetOfVertical = 4;

const GLsizei OutputVertexSize = 8;

// Input vertices, used only in composite mode, map from the input buffer to temporary buffer locations; such
// remapping occurs to ensure a continous stream of data for each scan, giving correct out-of-bounds behaviour
const GLsizei SourceVertexOffsetOfInputStart = 0;
const GLsizei SourceVertexOffsetOfOutputStart = 4;
const GLsizei SourceVertexOffsetOfEnds = 8;
const GLsizei SourceVertexOffsetOfPhaseTimeAndAmplitude = 12;

const GLsizei SourceVertexSize = 16;

// These constants hold the size of the rolling buffer to which the CPU writes
const GLsizei InputBufferBuilderWidth = 2048;
const GLsizei InputBufferBuilderHeight = 512;

// This is the size of the intermediate buffers used during composite to RGB conversion
const GLsizei IntermediateBufferWidth = 2048;
const GLsizei IntermediateBufferHeight = 512;

// Some internal buffer sizes
const GLsizeiptr OutputVertexBufferDataSize = OutputVertexSize * IntermediateBufferHeight;		// i.e. the maximum number of scans of output that can be created between draws
const GLsizeiptr SourceVertexBufferDataSize = SourceVertexSize * IntermediateBufferHeight * 10;	// (the maximum number of scans) * conservative, high guess at a maximumum number of events likely to occur within a scan

// TODO: when SourceVertexBufferDataSize is exhausted, the CRT keeps filling OutputVertexBufferDataSize regardless,
// leading to empty scanlines that nevertheless clear old contents.

}
}

#endif /* CRTContants_h */
<|endoftext|>


<commit_before>//_________________________________________________________________________
//  Utility Class for transverse energy studies
//  Base class for MC analysis
//  - MC output
//  implementation file
//
//*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL)
//_________________________________________________________________________

#include "AliAnalysisEtMonteCarlo.h"
#include "AliAnalysisEtCuts.h"
#include "AliESDtrack.h"
#include "AliStack.h"
#include "AliMCEvent.h"
#include "TH2F.h"
#include "TParticle.h"
#include "AliGenHijingEventHeader.h"
#include "AliGenPythiaEventHeader.h"

using namespace std;

ClassImp(AliAnalysisEtMonteCarlo);

// ctor
AliAnalysisEtMonteCarlo::AliAnalysisEtMonteCarlo() :
  AliAnalysisEt()
  ,fImpactParameter(0)
  ,fNcoll(0)
  ,fNpart(0)
{
}

// dtor
AliAnalysisEtMonteCarlo::~AliAnalysisEtMonteCarlo()
{
}

Int_t AliAnalysisEtMonteCarlo::AnalyseEvent(AliVEvent* ev)
{ // analyse MC event
     ResetEventValues();

    // Get us an mc event
    AliMCEvent *event = dynamic_cast<AliMCEvent*>(ev);

    // Hijing header
    AliGenEventHeader* genHeader = event->GenEventHeader();
    AliGenHijingEventHeader* hijingGenHeader = dynamic_cast<AliGenHijingEventHeader*>(genHeader);
    if (hijingGenHeader) {
      fImpactParameter = hijingGenHeader->ImpactParameter();
      fNcoll = hijingGenHeader->HardScatters(); // or should this be some combination of NN() NNw() NwN() NwNw() ?
      fNpart = hijingGenHeader->ProjectileParticipants() + hijingGenHeader->TargetParticipants();
      /*
      printf("Hijing: ImpactParameter %g ReactionPlaneAngle %g \n",
	     hijingGenHeader->ImpactParameter(), hijingGenHeader->ReactionPlaneAngle());
      printf("HardScatters %d ProjecileParticipants %d TargetParticipants %d\n",
	     hijingGenHeader->HardScatters(), hijingGenHeader->ProjectileParticipants(), hijingGenHeader->TargetParticipants());
      printf("ProjSpectatorsn %d ProjSpectatorsp %d TargSpectatorsn %d TargSpectatorsp %d\n",
	     hijingGenHeader->ProjSpectatorsn(), hijingGenHeader->ProjSpectatorsp(), hijingGenHeader->TargSpectatorsn(), hijingGenHeader->TargSpectatorsp());
      printf("NN %d NNw %d NwN %d, NwNw %d\n",
	     hijingGenHeader->NN(), hijingGenHeader->NNw(), hijingGenHeader->NwN(), hijingGenHeader->NwNw());
      */
    }

    /* // placeholder if we want to get some Pythia info later
    AliGenPythiaEventHeader* pythiaGenHeader = dynamic_cast<AliGenPythiaEventHeader*>(genHeader);
    if (pythiaGenHeader) { // not Hijing; try with Pythia
      printf("Pythia: ProcessType %d  GetPtHard %g \n",
	     pythiaGenHeader->ProcessType(), pythiaGenHeader->GetPtHard());
    }
    */

    // Let's play with the stack!
    AliStack *stack = event->Stack();

    Int_t nPrim = stack->GetNtrack();

    for (Int_t iPart = 0; iPart < nPrim; iPart++)
    {

        TParticle *part = stack->Particle(iPart);

        if (!part)
        {
            Printf("ERROR: Could not get particle %d", iPart);
            continue;
        }

        TParticlePDG *pdg = part->GetPDG(0);

	Double_t particleMassPart = 0; //The mass part in the Et calculation for this particle

        // Check if it is a primary particle
        if (!stack->IsPhysicalPrimary(iPart)) continue;

	// printf("MC: iPart %03d eta %4.3f phi %4.3f code %d charge %g \n", iPart, part->Eta(), part->Phi(), pdg->PdgCode(), pdg->Charge()); // tmp/debug printout

        // Check for reasonable (for now neutral and singly charged) charge on the particle
        //TODO:Maybe not only singly charged?
        if (TMath::Abs(TMath::Abs(pdg->Charge()) - fCuts->GetMonteCarloSingleChargedParticle())<1e-3 && TMath::Abs(TMath::Abs(pdg->Charge()) - fCuts->GetMonteCarloNeutralParticle())<1e-3) continue;

        fMultiplicity++;

        if (TMath::Abs(part->Eta()) < fCuts->GetCommonEtaCut())
        {

            if (
                TMath::Abs(pdg->PdgCode()) == fProtonCode ||
                TMath::Abs(pdg->PdgCode()) == fNeutronCode ||
                TMath::Abs(pdg->PdgCode()) == fLambdaCode ||
                TMath::Abs(pdg->PdgCode()) == fXiCode ||
                TMath::Abs(pdg->PdgCode()) == fXi0Code ||
                TMath::Abs(pdg->PdgCode()) == fOmegaCode
	       )
            {
	      if (pdg->PdgCode() > 0) { particleMassPart = - pdg->Mass();}
	      if (pdg->PdgCode() < 0) { particleMassPart = pdg->Mass();}
	    }
	    Double_t et = part->Energy() * TMath::Sin(part->Theta()) + particleMassPart;

	    if (pdg->PdgCode() == fProtonCode || pdg->PdgCode() == fAntiProtonCode)
	      {
		fProtonEt += et;
	      }
	    if (pdg->PdgCode() == fPiPlusCode || pdg->PdgCode() == fPiMinusCode)
	      {
		fPionEt += et;
	      }
	    if (pdg->PdgCode() == fKPlusCode || pdg->PdgCode() == fKMinusCode)
	      {
		fChargedKaonEt += et;
	      }
	    if (pdg->PdgCode() == fMuPlusCode || pdg->PdgCode() == fMuMinusCode)
	      {
		fMuonEt += et;
	      }
	    if (pdg->PdgCode() == fEPlusCode || pdg->PdgCode() == fEMinusCode)
	      {
		fElectronEt += et;
	      }

	    // some neutrals also
	    if(pdg->PdgCode() == fNeutronCode)
	    {
	      fNeutronEt += et;
	    }
            if(pdg->PdgCode() == fAntiNeutronCode)
	    {
	      fAntiNeutronEt += et;
	    }
	    if(pdg->PdgCode() == fGammaCode)
	    {
	      fGammaEt += et;
	    }

            if (TMath::Abs(pdg->Charge() - fCuts->GetMonteCarloNeutralParticle()) <1e-3 )
            {
	       fNeutralMultiplicity++;
	       fTotNeutralEt += et;

                if (TMath::Abs(part->Eta()) < fEtaCutAcc && part->Phi() < fPhiCutAccMax && part->Phi() > fPhiCutAccMin)
                {
		  fTotNeutralEtAcc += et;
		  fTotEtAcc += et;
                }
            }
            else if (TMath::Abs( pdg->Charge() - fCuts->GetMonteCarloNeutralParticle())<1e-3 )
            {
	       fChargedMultiplicity++;
	       fTotChargedEt += et;
                if (TMath::Abs(part->Eta()) < fEtaCutAcc && part->Phi() < fPhiCutAccMax && part->Phi() > fPhiCutAccMin)
                {
		  fTotChargedEtAcc += et;
		  fTotEtAcc += et;

		    if (pdg->PdgCode() == fProtonCode || pdg->PdgCode() == fAntiProtonCode)
		      {
			fProtonEtAcc += et;
		      }
		    if (pdg->PdgCode() == fPiPlusCode || pdg->PdgCode() == fPiMinusCode)
		      {
			fPionEtAcc += et;
		      }
		    if (pdg->PdgCode() == fKPlusCode || pdg->PdgCode() == fKMinusCode)
		      {
			fChargedKaonEtAcc += et;
		      }
		    if (pdg->PdgCode() == fMuPlusCode || pdg->PdgCode() == fMuMinusCode)
		      {
			fMuonEtAcc += et;
		      }
		    if (pdg->PdgCode() == fEPlusCode || pdg->PdgCode() == fEMinusCode)
		      {
			fElectronEtAcc += et;
		      }

                }

		//	  if (TrackHitsCalorimeter(part, event->GetMagneticField()))
		if (TrackHitsCalorimeter(part)) // magnetic field info not filled?
		  {
		    if (pdg->Charge() > 0) fHistPhivsPtPos->Fill(part->Phi(),part->Pt());
		    else fHistPhivsPtNeg->Fill(part->Phi(), part->Pt());
		  }
	    }
	}
    }

    fTotEt = fTotChargedEt + fTotNeutralEt;
    fTotEtAcc = fTotChargedEtAcc + fTotNeutralEtAcc;

    FillHistograms();

    return 0;
}

void AliAnalysisEtMonteCarlo::Init()
{ // init
    AliAnalysisEt::Init();
}

void AliAnalysisEtMonteCarlo::ResetEventValues()
{ // reset event values
  AliAnalysisEt::ResetEventValues();

  // collision geometry defaults for p+p:
  fImpactParameter = 0;
  fNcoll = 1;
  fNpart = 2;
}

void AliAnalysisEtMonteCarlo::CreateHistograms()
{ // histogram related additions
  AliAnalysisEt::CreateHistograms();
  if (fTree) {
    fTree->Branch("fImpactParameter",&fImpactParameter,"fImpactParameter/D");
    fTree->Branch("fNcoll",&fNcoll,"fNcoll/I");
    fTree->Branch("fNpart",&fNpart,"fNpart/I");
  }
}

bool AliAnalysisEtMonteCarlo::TrackHitsCalorimeter(TParticle* part, Double_t magField)
{
  //  printf(" TrackHitsCalorimeter - magField %f\n", magField);
   AliESDtrack *esdTrack = new AliESDtrack(part);
   // Printf("MC Propagating track: eta: %f, phi: %f, pt: %f", esdTrack->Eta(), esdTrack->Phi(), esdTrack->Pt());

    Bool_t prop = esdTrack->PropagateTo(fDetectorRadius, magField);

    // if(prop) Printf("Track propagated, eta: %f, phi: %f, pt: %f", esdTrack->Eta(), esdTrack->Phi(), esdTrack->Pt());

    bool status = prop &&
      TMath::Abs(esdTrack->Eta()) < fEtaCutAcc &&
      esdTrack->Phi() > fPhiCutAccMin*TMath::Pi()/180. &&
      esdTrack->Phi() < fPhiCutAccMax*TMath::Pi()/180.;
    delete esdTrack;

    return status;
}

<commit_msg>correcting baryon mass subtraction for visible energy in MC<commit_after>//_________________________________________________________________________
//  Utility Class for transverse energy studies
//  Base class for MC analysis
//  - MC output
//  implementation file
//
//*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL)
//_________________________________________________________________________

#include "AliAnalysisEtMonteCarlo.h"
#include "AliAnalysisEtCuts.h"
#include "AliESDtrack.h"
#include "AliStack.h"
#include "AliMCEvent.h"
#include "TH2F.h"
#include "TParticle.h"
#include "TDatabasePDG.h"
#include "AliGenHijingEventHeader.h"
#include "AliGenPythiaEventHeader.h"

using namespace std;

ClassImp(AliAnalysisEtMonteCarlo);

// ctor
AliAnalysisEtMonteCarlo::AliAnalysisEtMonteCarlo() :
  AliAnalysisEt()
  ,fImpactParameter(0)
  ,fNcoll(0)
  ,fNpart(0)
{
}

// dtor
AliAnalysisEtMonteCarlo::~AliAnalysisEtMonteCarlo()
{
}

Int_t AliAnalysisEtMonteCarlo::AnalyseEvent(AliVEvent* ev)
{ // analyse MC event
     ResetEventValues();

    // Get us an mc event
    AliMCEvent *event = dynamic_cast<AliMCEvent*>(ev);

    Double_t protonMass = fPdgDB->GetParticle("proton")->Mass(); // should maybe use average of proton and neutron, but they are pretty close

    // Hijing header
    AliGenEventHeader* genHeader = event->GenEventHeader();
    AliGenHijingEventHeader* hijingGenHeader = dynamic_cast<AliGenHijingEventHeader*>(genHeader);
    if (hijingGenHeader) {
      fImpactParameter = hijingGenHeader->ImpactParameter();
      fNcoll = hijingGenHeader->HardScatters(); // or should this be some combination of NN() NNw() NwN() NwNw() ?
      fNpart = hijingGenHeader->ProjectileParticipants() + hijingGenHeader->TargetParticipants();
      /*
      printf("Hijing: ImpactParameter %g ReactionPlaneAngle %g \n",
	     hijingGenHeader->ImpactParameter(), hijingGenHeader->ReactionPlaneAngle());
      printf("HardScatters %d ProjecileParticipants %d TargetParticipants %d\n",
	     hijingGenHeader->HardScatters(), hijingGenHeader->ProjectileParticipants(), hijingGenHeader->TargetParticipants());
      printf("ProjSpectatorsn %d ProjSpectatorsp %d TargSpectatorsn %d TargSpectatorsp %d\n",
	     hijingGenHeader->ProjSpectatorsn(), hijingGenHeader->ProjSpectatorsp(), hijingGenHeader->TargSpectatorsn(), hijingGenHeader->TargSpectatorsp());
      printf("NN %d NNw %d NwN %d, NwNw %d\n",
	     hijingGenHeader->NN(), hijingGenHeader->NNw(), hijingGenHeader->NwN(), hijingGenHeader->NwNw());
      */
    }

    /* // placeholder if we want to get some Pythia info later
    AliGenPythiaEventHeader* pythiaGenHeader = dynamic_cast<AliGenPythiaEventHeader*>(genHeader);
    if (pythiaGenHeader) { // not Hijing; try with Pythia
      printf("Pythia: ProcessType %d  GetPtHard %g \n",
	     pythiaGenHeader->ProcessType(), pythiaGenHeader->GetPtHard());
    }
    */

    // Let's play with the stack!
    AliStack *stack = event->Stack();

    Int_t nPrim = stack->GetNtrack();

    for (Int_t iPart = 0; iPart < nPrim; iPart++)
    {

        TParticle *part = stack->Particle(iPart);

        if (!part)
        {
            Printf("ERROR: Could not get particle %d", iPart);
            continue;
        }

        TParticlePDG *pdg = part->GetPDG(0);

	Double_t particleMassPart = 0; //The mass part in the Et calculation for this particle

        // Check if it is a primary particle
        if (!stack->IsPhysicalPrimary(iPart)) continue;

	// printf("MC: iPart %03d eta %4.3f phi %4.3f code %d charge %g \n", iPart, part->Eta(), part->Phi(), pdg->PdgCode(), pdg->Charge()); // tmp/debug printout

        // Check for reasonable (for now neutral and singly charged) charge on the particle
        //TODO:Maybe not only singly charged?
        if (TMath::Abs(TMath::Abs(pdg->Charge()) - fCuts->GetMonteCarloSingleChargedParticle())<1e-3 && TMath::Abs(TMath::Abs(pdg->Charge()) - fCuts->GetMonteCarloNeutralParticle())<1e-3) continue;

        fMultiplicity++;

        if (TMath::Abs(part->Eta()) < fCuts->GetCommonEtaCut())
        {

            if (
                TMath::Abs(pdg->PdgCode()) == fProtonCode ||
                TMath::Abs(pdg->PdgCode()) == fNeutronCode ||
                TMath::Abs(pdg->PdgCode()) == fLambdaCode ||
                TMath::Abs(pdg->PdgCode()) == fXiCode ||
                TMath::Abs(pdg->PdgCode()) == fXi0Code ||
                TMath::Abs(pdg->PdgCode()) == fOmegaCode
	       )
            {
	      if (pdg->PdgCode() > 0) { particleMassPart = - protonMass;}
	      if (pdg->PdgCode() < 0) { particleMassPart = protonMass;}
	    }
	    Double_t et = part->Energy() * TMath::Sin(part->Theta()) + particleMassPart;

	    if (pdg->PdgCode() == fProtonCode || pdg->PdgCode() == fAntiProtonCode)
	      {
		fProtonEt += et;
	      }
	    if (pdg->PdgCode() == fPiPlusCode || pdg->PdgCode() == fPiMinusCode)
	      {
		fPionEt += et;
	      }
	    if (pdg->PdgCode() == fKPlusCode || pdg->PdgCode() == fKMinusCode)
	      {
		fChargedKaonEt += et;
	      }
	    if (pdg->PdgCode() == fMuPlusCode || pdg->PdgCode() == fMuMinusCode)
	      {
		fMuonEt += et;
	      }
	    if (pdg->PdgCode() == fEPlusCode || pdg->PdgCode() == fEMinusCode)
	      {
		fElectronEt += et;
	      }

	    // some neutrals also
	    if(pdg->PdgCode() == fNeutronCode)
	    {
	      fNeutronEt += et;
	    }
            if(pdg->PdgCode() == fAntiNeutronCode)
	    {
	      fAntiNeutronEt += et;
	    }
	    if(pdg->PdgCode() == fGammaCode)
	    {
	      fGammaEt += et;
	    }

            if (TMath::Abs(pdg->Charge() - fCuts->GetMonteCarloNeutralParticle()) <1e-3 )
            {
	       fNeutralMultiplicity++;
	       fTotNeutralEt += et;

                if (TMath::Abs(part->Eta()) < fEtaCutAcc && part->Phi() < fPhiCutAccMax && part->Phi() > fPhiCutAccMin)
                {
		  fTotNeutralEtAcc += et;
		  fTotEtAcc += et;
                }
            }
            else if (TMath::Abs( pdg->Charge() - fCuts->GetMonteCarloNeutralParticle())<1e-3 )
            {
	       fChargedMultiplicity++;
	       fTotChargedEt += et;
                if (TMath::Abs(part->Eta()) < fEtaCutAcc && part->Phi() < fPhiCutAccMax && part->Phi() > fPhiCutAccMin)
                {
		  fTotChargedEtAcc += et;
		  fTotEtAcc += et;

		    if (pdg->PdgCode() == fProtonCode || pdg->PdgCode() == fAntiProtonCode)
		      {
			fProtonEtAcc += et;
		      }
		    if (pdg->PdgCode() == fPiPlusCode || pdg->PdgCode() == fPiMinusCode)
		      {
			fPionEtAcc += et;
		      }
		    if (pdg->PdgCode() == fKPlusCode || pdg->PdgCode() == fKMinusCode)
		      {
			fChargedKaonEtAcc += et;
		      }
		    if (pdg->PdgCode() == fMuPlusCode || pdg->PdgCode() == fMuMinusCode)
		      {
			fMuonEtAcc += et;
		      }
		    if (pdg->PdgCode() == fEPlusCode || pdg->PdgCode() == fEMinusCode)
		      {
			fElectronEtAcc += et;
		      }

                }

		//	  if (TrackHitsCalorimeter(part, event->GetMagneticField()))
		if (TrackHitsCalorimeter(part)) // magnetic field info not filled?
		  {
		    if (pdg->Charge() > 0) fHistPhivsPtPos->Fill(part->Phi(),part->Pt());
		    else fHistPhivsPtNeg->Fill(part->Phi(), part->Pt());
		  }
	    }
	}
    }

    fTotEt = fTotChargedEt + fTotNeutralEt;
    fTotEtAcc = fTotChargedEtAcc + fTotNeutralEtAcc;

    FillHistograms();

    return 0;
}

void AliAnalysisEtMonteCarlo::Init()
{ // init
    AliAnalysisEt::Init();
}

void AliAnalysisEtMonteCarlo::ResetEventValues()
{ // reset event values
  AliAnalysisEt::ResetEventValues();

  // collision geometry defaults for p+p:
  fImpactParameter = 0;
  fNcoll = 1;
  fNpart = 2;
}

void AliAnalysisEtMonteCarlo::CreateHistograms()
{ // histogram related additions
  AliAnalysisEt::CreateHistograms();
  if (fTree) {
    fTree->Branch("fImpactParameter",&fImpactParameter,"fImpactParameter/D");
    fTree->Branch("fNcoll",&fNcoll,"fNcoll/I");
    fTree->Branch("fNpart",&fNpart,"fNpart/I");
  }
}

bool AliAnalysisEtMonteCarlo::TrackHitsCalorimeter(TParticle* part, Double_t magField)
{
  //  printf(" TrackHitsCalorimeter - magField %f\n", magField);
   AliESDtrack *esdTrack = new AliESDtrack(part);
   // Printf("MC Propagating track: eta: %f, phi: %f, pt: %f", esdTrack->Eta(), esdTrack->Phi(), esdTrack->Pt());

    Bool_t prop = esdTrack->PropagateTo(fDetectorRadius, magField);

    // if(prop) Printf("Track propagated, eta: %f, phi: %f, pt: %f", esdTrack->Eta(), esdTrack->Phi(), esdTrack->Pt());

    bool status = prop &&
      TMath::Abs(esdTrack->Eta()) < fEtaCutAcc &&
      esdTrack->Phi() > fPhiCutAccMin*TMath::Pi()/180. &&
      esdTrack->Phi() < fPhiCutAccMax*TMath::Pi()/180.;
    delete esdTrack;

    return status;
}

<|endoftext|>