<commit_before>//
// Created by volundr on 7/6/16.
//

#include "UartInterface.h"

namespace bno055 {

    /**
     * Opens communications with the UART device found at location 'deviceFile'
     * This code was taken from the 'Using the UART' tutorial page found at
     * http://www.raspberry-projects.com/pi/programming-in-c/uart-serial-port/using-the-uart
     */
    bool UartInterface::openPort(const char* deviceFile, tcflag_t baudRate) {
        /*
         * Close any existing serial communications
         */
        closePort();
        /*
         * OPEN THE UART
         * The flags (defined in fcntl.h):
         * 	Access modes (use 1 of these):
         * 		O_RDONLY - Open for reading only.
         * 		O_RDWR - Open for reading and writing.
         * 		O_WRONLY - Open for writing only.
         *
         * 	O_NDELAY / O_NONBLOCK (same function) -
         * 	Enables nonblocking mode. When set read requests on the file can return immediately with a failure status
         * 	if there is no input immediately available (instead of blocking). Likewise, sendData requests can also return
         * 	immediately with a failure status if the output can't be written immediately.
         *
         * 	O_NOCTTY -
         * 	When set and path identifies a terminal device, open() shall not cause the terminal device to become the
         * 	controlling terminal for the process.
         */
//        uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_SYNC);		//Open in synchronous mode
        uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_NONBLOCK);		//Open in asynchronous mode
        if (uartFile == -1) {
            return false;
        }

        /*
         * CONFIGURE THE UART
         * The flags (defined in /usr/include/termios.h -
         * see http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html):
         *
         * 	Baud rate:  B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000,
         * 	                B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000
         * 	CSIZE   :   CS5, CS6, CS7, CS8
         * 	CLOCAL  :   Ignore modem status lines
         * 	CREAD   :   Enable receiver
         * 	IGNPAR  :   Ignore characters with parity errors
         * 	ICRNL   :   Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters
         * 	                - don't use for bianry comms!)
         * 	PARENB  :   Parity enable
         * 	PARODD  :   Odd parity (else even)
         */
        struct termios options;
        tcgetattr(uartFile, &options);
        options.c_cflag = baudRate | CS8 | CLOCAL | CREAD | CSTOPB;		//<Set baud rate
        options.c_iflag = IGNPAR;
        options.c_oflag = 0;
        options.c_lflag = 0;
        tcflush(uartFile, TCIOFLUSH);
        tcsetattr(uartFile, TCSANOW, &options);

        return true;
    }

    bool UartInterface::closePort() {
        if (uartFile != -1) {
            close(uartFile);
            uartFile = -1;
            return true;
        }
        return false;
    }

    UartInterface::~UartInterface() {
        if (uartFile != -1) {
            close(uartFile);
        }
    }

    int64_t UartInterface::sendData(uint8_t* data, uint32_t length) {
        if (uartFile == -1) {
            return -1;
        } else {
            return (int64_t)write(uartFile, data, length);
        }
    }

    int64_t UartInterface::recvData(uint8_t* empty, uint32_t maxLength) {
        if (uartFile == -1) {
            return -1;
        } else {
            return (int64_t)read(uartFile, (void*)empty, maxLength);
        }
    }

}
<commit_msg>removed second stop bit<commit_after>//
// Created by volundr on 7/6/16.
//

#include "UartInterface.h"

namespace bno055 {

    /**
     * Opens communications with the UART device found at location 'deviceFile'
     * This code was taken from the 'Using the UART' tutorial page found at
     * http://www.raspberry-projects.com/pi/programming-in-c/uart-serial-port/using-the-uart
     */
    bool UartInterface::openPort(const char* deviceFile, tcflag_t baudRate) {
        /*
         * Close any existing serial communications
         */
        closePort();
        /*
         * OPEN THE UART
         * The flags (defined in fcntl.h):
         * 	Access modes (use 1 of these):
         * 		O_RDONLY - Open for reading only.
         * 		O_RDWR - Open for reading and writing.
         * 		O_WRONLY - Open for writing only.
         *
         * 	O_NDELAY / O_NONBLOCK (same function) -
         * 	Enables nonblocking mode. When set read requests on the file can return immediately with a failure status
         * 	if there is no input immediately available (instead of blocking). Likewise, sendData requests can also return
         * 	immediately with a failure status if the output can't be written immediately.
         *
         * 	O_NOCTTY -
         * 	When set and path identifies a terminal device, open() shall not cause the terminal device to become the
         * 	controlling terminal for the process.
         */
//        uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_SYNC);		//Open in synchronous mode
        uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_NONBLOCK);		//Open in asynchronous mode
        if (uartFile == -1) {
            return false;
        }

        /*
         * CONFIGURE THE UART
         * The flags (defined in /usr/include/termios.h -
         * see http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html):
         *
         * 	Baud rate:  B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000,
         * 	                B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000
         * 	CSIZE   :   CS5, CS6, CS7, CS8
         * 	CLOCAL  :   Ignore modem status lines
         * 	CREAD   :   Enable receiver
         * 	IGNPAR  :   Ignore characters with parity errors
         * 	ICRNL   :   Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters
         * 	                - don't use for bianry comms!)
         * 	PARENB  :   Parity enable
         * 	PARODD  :   Odd parity (else even)
         */
        struct termios options;
        tcgetattr(uartFile, &options);
        options.c_cflag = baudRate | CS8 | CLOCAL | CREAD;		//<Set baud rate
        options.c_iflag = IGNPAR;
        options.c_oflag = 0;
        options.c_lflag = 0;
        tcflush(uartFile, TCIOFLUSH);
        tcsetattr(uartFile, TCSANOW, &options);

        return true;
    }

    bool UartInterface::closePort() {
        if (uartFile != -1) {
            close(uartFile);
            uartFile = -1;
            return true;
        }
        return false;
    }

    UartInterface::~UartInterface() {
        if (uartFile != -1) {
            close(uartFile);
        }
    }

    int64_t UartInterface::sendData(uint8_t* data, uint32_t length) {
        if (uartFile == -1) {
            return -1;
        } else {
            return (int64_t)write(uartFile, data, length);
        }
    }

    int64_t UartInterface::recvData(uint8_t* empty, uint32_t maxLength) {
        if (uartFile == -1) {
            return -1;
        } else {
            return (int64_t)read(uartFile, (void*)empty, maxLength);
        }
    }

}
<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>
#include "grid.h"
#include "cell.h"
#include <iostream>

using namespace sf;

int main()
{
	//Calling grid here
	//this will be 1027 / 32 which is defend in grid.cpp
	int gridWidth = grid::windowWidth / grid::x;
	//this will be 720 / 32 which also defend in grid.cpp
	int gridHeight = grid::windowHeight / grid::y;
	//Calling cell setup
	cell::Setup(gridWidth, gridHeight);
	int drawingCells[32][32];
	//starting with the window
	sf::RenderWindow window(sf::VideoMode(grid::windowWidth, grid::windowHeight), "Welcome to Mohanad's Game Of Life");
	bool Gamestart = false;
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
			if (event.type == Event::KeyPressed) {
				switch (event.key.code) {
				case Keyboard::Escape:
					printf("Bye Bye and see you next time \n");
					exit(0);

				}
			}
			if (event.type == sf::Event::MouseButtonPressed) {

				int clickX = (event.mouseButton.x / gridWidth);
				int clickY = (event.mouseButton.y / gridHeight);
				drawingCells[clickX][clickY] = drawingCells[clickX][clickY] == 1 ? 0.5 : 1;

				//checking is the mouse clicked or not
				printf("mouse clicked \n");
			}
			//this will run the game
			if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::R)
			{

				if (Gamestart = true) {
					for (size_t row = 0; row < gridHeight; row++)
					{

						int count = 0;
						if (drawingCells[32 - 1][32 - 1]) {
							++count;
						}
						if (drawingCells[32 - 1][32 - 1]) {
							++count;
						}
						if (drawingCells[32 + 1][32 - 1]) {
							++count;
						}
						if (drawingCells[32 + 1][32]) {
							++count;
						}
						if (drawingCells[32 + 1][32 + 1]) {
							++count;
						}
						if (drawingCells[32][32 + 1]) {
							++count;
						}
						if (drawingCells[32 - 1][32 + 1]) {
							++count;
						}
						if (drawingCells[32 - 1][32]) {
							++count;
						}
						else {

							for (int x = 0; x < gridWidth; x++) {
								for (int y = 0; y < gridHeight; y++) {
									drawingCells[x][y] = drawingCells[x][y];
								}

							}
						}

						printf("Start \n");
					}

					window.clear();

					for (size_t row = 0; row < grid::x; row++)
					{
						for (size_t column = 0; column < grid::y; column++)
						{
							int state = drawingCells[row][column];
							if (state == 1) {
								cell::Setcolor(Color::White);
							}
							else if (state == 0) {
								cell::Setcolor(Color::Blue);

							}
							cell::Setposition((column * gridWidth), (row * gridHeight));
							window.draw(cell::target);

						}

					}
					window.display();

				}

			}

		}
	}
}
<commit_msg>Adding the mouse<commit_after>#include <SFML/Graphics.hpp>
#include "grid.h"
#include "cell.h"
#include <iostream>

using namespace sf;

int main()
{
	//Calling grid here
	//this will be 1027 / 32 which is defend in grid.cpp
	int gridWidth = grid::windowWidth / grid::x;
	//this will be 720 / 32 which also defend in grid.cpp
	int gridHeight = grid::windowHeight / grid::y;
	//Calling cell setup
	cell::Setup(gridWidth, gridHeight);
	int drawingCells[32][32];
	//starting with the window
	sf::RenderWindow window(sf::VideoMode(grid::windowWidth, grid::windowHeight), "Welcome to Mohanad's Game Of Life");
	bool Gamestart = false;
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
			if (event.type == Event::KeyPressed) {
				switch (event.key.code) {
				case Keyboard::Escape:
					printf("Bye Bye and see you next time \n");
					exit(0);

				}
			}
			if (event.type == sf::Event::MouseButtonPressed) {
				int cell = 0;
				int clickX = (event.mouseButton.x / gridWidth);
				int clickY = (event.mouseButton.y / gridHeight);
					if (Mouse::isButtonPressed(Mouse::Left)) {
						drawingCells[clickX][clickY] = drawingCells[clickX][clickY] == 1 ? 0.5 : 1;
						cell += (clickX + clickY ? 1 : 0);
						drawingCells[event.mouseButton.x][event.mouseButton.y];
						//checking is the mouse clicked or not
						printf("mouse clicked \n");

					}
			}
			//this will run the game
			if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::R)
			{

				if (Gamestart = true) {
					for (size_t row = 0; row < gridHeight; row++)
					{

						int count = 0;
						if (drawingCells[32 - 1][32 - 1]) {
							++count;
						}
						if (drawingCells[32 - 1][32 - 1]) {
							++count;
						}
						if (drawingCells[32 + 1][32 - 1]) {
							++count;
						}
						if (drawingCells[32 + 1][32]) {
							++count;
						}
						if (drawingCells[32 + 1][32 + 1]) {
							++count;
						}
						if (drawingCells[32][32 + 1]) {
							++count;
						}
						if (drawingCells[32 - 1][32 + 1]) {
							++count;
						}
						if (drawingCells[32 - 1][32]) {
							++count;
						}
						else {

							for (int x = 0; x < gridWidth; x++) {
								for (int y = 0; y < gridHeight; y++) {
									drawingCells[x][y] = drawingCells[x][y];
								}

							}
						}

						printf("Start \n");
					}

					window.clear();

					for (size_t row = 0; row < grid::x; row++)
					{
						for (size_t column = 0; column < grid::y; column++)
						{
							int state = drawingCells[row][column];
							if (state == 1) {
								cell::Setcolor(Color::White);
							}
							else if (state == 0) {
								cell::Setcolor(Color::Blue);

							}
							cell::Setposition((column * gridWidth), (row * gridHeight));
							window.draw(cell::target);

						}

					}
					window.display();

				}

			}

		}
	}
}
<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>
#include "grid.h"
#include "cell.h"

using namespace sf;

int main()
{
	//Calling grid here
	int gridWidth = grid::windowWidth / grid::x;
	int gridHeight = grid::windowHeight / grid::y;
	//Calling cell setup
	cell::Setup(gridWidth, gridHeight);
	int drawingCells[32][32];
	//starting with the window
	sf::RenderWindow window(sf::VideoMode(grid::windowWidth, grid::windowHeight), "Welcome to Mohanad Game Of Life");
	sf::Event windowEvent;
	cell::Setup(gridWidth, gridHeight);
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
		}
		for (rsize_t row = 0; row < grid::x; row++)
		{
			for (rsize_t column = 0; column < grid::y; column++)
			{
				int total = drawingCells[32][32];

				if (total == 1) {
					cell::Setcolor(Color::White);
				}
				else if (total == 0) {
					cell::Setcolor(Color::Blue);
				}
				cell::Setposition((column * gridWidth), (row * gridHeight));
				window.draw(cell::target);
				window.setActive();
				window.display();
			}
		}
	}
}<commit_msg>Adding the key pressed<commit_after>#include <SFML/Graphics.hpp>
#include "grid.h"
#include "cell.h"

using namespace sf;

int main()
{
	//Calling grid here
	int gridWidth = grid::windowWidth / grid::x;
	int gridHeight = grid::windowHeight / grid::y;
	//Calling cell setup
	cell::Setup(gridWidth, gridHeight);
	int drawingCells[32][32];
	//starting with the window
	sf::RenderWindow window(sf::VideoMode(grid::windowWidth, grid::windowHeight), "Welcome to Mohanad Game Of Life");
	cell::Setup(gridWidth, gridHeight);

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
			if (event.type == Event::KeyPressed) {
				switch (event.key.code) {
				case Keyboard::Escape:
					exit(0);
				}
			}
		}
					for (rsize_t row = 0; row < grid::x; row++)
					{
						for (rsize_t column = 0; column < grid::y; column++)
						{
							int total = drawingCells[32][32];

							if (total == 1) {
								cell::Setcolor(Color::White);
							}
							else if (total == 0) {
								cell::Setcolor(Color::Blue);
							}
							cell::Setposition((column * gridWidth), (row * gridHeight));
							window.draw(cell::target);
							window.setActive();
							window.display();
						}
					}
				}
			}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <array>
#include <cmath>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <ApplicationServices/ApplicationServices.h>
#include <unistd.h>
using namespace cv;
CGEventRef move;
int main()
{
	while(true)
	{
		moveCursor(getEyePos());
	}
	return 0;
}
void moveCursor(int x, y)
{
	move = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, CGPointMake(200, 200), kCGMouseButtonLeft);
}
std::array<int, 2> getEyePos(std::string LR)
{
	std::array eyePosition;
	return eyePosition;
}<commit_msg>TempStash<commit_after>#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <array>
#include <cmath>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <ApplicationServices/ApplicationServices.h>
#include <unistd.h>
using namespace cv;
CGEventRef move;
int main()
{
	std::cout << "Program initiated by user" << std::endl;
	VideoCapture cap(0);
	if (!cap.isOpened())
	{
		std::cout << "ERROR: Webcam failed to initialize"
		return -1;
	}
	else
		std::cout << "Webcam initiated" << std::endl;
	namedWindow("Hack NJIT 2016", CV_WINDOW_AUTOSIZE);
	while(true)
	{
		moveCursor(getEyePos());
	}
	return 0;
}
void moveCursor(int x, y)
{
	move = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, CGPointMake(200, 200), kCGMouseButtonLeft);
}
std::array<int, 2> getEyePos(std::string LR)
{
	std::array eyePosition;
	return eyePosition;
}<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/CopasiSE/CopasiSE.cpp,v $
   $Revision: 1.9 $
   $Name:  $
   $Author: shoops $
   $Date: 2005/02/18 16:20:37 $
   End CVS Header */

// Main
//
// (C) Stefan Hoops 2002
//

#include <stdlib.h>
#include <sstream>
#include <string>
#include <iostream>

#define COPASI_MAIN
#define COPASI_TRACE_CONSTRUCTION

#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "utilities/CCopasiMessage.h"
#include "utilities/CCopasiException.h"
#include "utilities/CCopasiTask.h"
#include "commandline/COptionParser.h"
#include "commandline/COptions.h"
#include "function/CFunctionDB.h"

int main(int argc, char *argv[])
{
  try
    {
      // Parse the commandline options
      COptions::init(argc, argv);
    }

  catch (copasi::autoexcept &e)
    {
      switch (e.get_autothrow_id())
        {
        case copasi::autothrow_help:
          std::cout << "Usage: " << argv[0] << " [options]\n";
          std::cout << e.what();
        }

      return 1;
    }

  catch (copasi::option_error &e)
    {
      std::cerr << argv[0] << ": " << e.what() << "\n";
      std::cerr << e.get_help_comment() << std::endl;

      return 1;
    }

  // Create the root container.
  CCopasiContainer::init();

  // Create the global data model.
  CCopasiDataModel::Global = new CCopasiDataModel;

  const COptions::nonOptionType & Files = COptions::getNonOptions();

  if (!COptions::compareValue("ImportSBML", std::string("")))
    {
      // Import the SBML File
      std::string ImportSBML;
      COptions::getValue("ImportSBML", ImportSBML);
      CCopasiDataModel::Global->importSBML(ImportSBML);

      // Save the COPASI File, which is the only thing to do.
      std::string Save;
      COptions::getValue("Save", Save);
      CCopasiDataModel::Global->saveModel(Save);
    }

  COptions::nonOptionType::const_iterator it = Files.begin();
  COptions::nonOptionType::const_iterator end = Files.end();

  for (; it != end; ++it)
    {
      CCopasiDataModel::Global->loadModel(*it);

      // Check whether exporting to SBML is requested.
      if (!COptions::compareValue("ExportSBML", std::string("")))
        {
          // Export the SBML File
          std::string ExportSBML;
          COptions::getValue("ExportSBML", ExportSBML);
          CCopasiDataModel::Global->exportSBML(ExportSBML);

          // Since only one export file name can be specified we
          // stop execution.
          return 0;
        }

      CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList();
      unsigned C_INT32 i, imax = TaskList.size();

      for (i = 0; i < imax; i++)
        if (TaskList[i]->isScheduled())
          {
            TaskList[i]->initialize();
            TaskList[i]->process();
            TaskList[i]->restore();
          }

      // Check whether a file for saving the resulting model is given
      if (!COptions::compareValue("Save", std::string("")))
        {
          std::string Save;
          COptions::getValue("Save", Save);
          CCopasiDataModel::Global->saveModel(Save);

          // Since only one save file name can be specified we
          // stop execution.
          return 0;
        }

      CCopasiDataModel::Global->saveModel("");
    }

  //  catch (CCopasiException Exception)
  //    {
  //      std::cout << Exception.getMessage().getText() << std::endl;
  //}

  pdelete(CCopasiDataModel::Global);
  pdelete(CCopasiContainer::Root);

  std::cout << "Leaving main program." << std::endl;
  return 0;
}
<commit_msg>Set the model of the problem of task before task initialization.<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/CopasiSE/CopasiSE.cpp,v $
   $Revision: 1.10 $
   $Name:  $
   $Author: shoops $
   $Date: 2005/02/25 01:51:46 $
   End CVS Header */

// Main
//
// (C) Stefan Hoops 2002
//

#include <stdlib.h>
#include <sstream>
#include <string>
#include <iostream>

#define COPASI_MAIN
#define COPASI_TRACE_CONSTRUCTION

#include "copasi.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "utilities/CCopasiMessage.h"
#include "utilities/CCopasiException.h"
#include "utilities/CCopasiTask.h"
#include "utilities/CCopasiProblem.h"
#include "commandline/COptionParser.h"
#include "commandline/COptions.h"
#include "function/CFunctionDB.h"

int main(int argc, char *argv[])
{
  try
    {
      // Parse the commandline options
      COptions::init(argc, argv);
    }

  catch (copasi::autoexcept &e)
    {
      switch (e.get_autothrow_id())
        {
        case copasi::autothrow_help:
          std::cout << "Usage: " << argv[0] << " [options]\n";
          std::cout << e.what();
        }

      return 1;
    }

  catch (copasi::option_error &e)
    {
      std::cerr << argv[0] << ": " << e.what() << "\n";
      std::cerr << e.get_help_comment() << std::endl;

      return 1;
    }

  // Create the root container.
  CCopasiContainer::init();

  // Create the global data model.
  CCopasiDataModel::Global = new CCopasiDataModel;

  const COptions::nonOptionType & Files = COptions::getNonOptions();

  if (!COptions::compareValue("ImportSBML", std::string("")))
    {
      // Import the SBML File
      std::string ImportSBML;
      COptions::getValue("ImportSBML", ImportSBML);
      CCopasiDataModel::Global->importSBML(ImportSBML);

      // Save the COPASI File, which is the only thing to do.
      std::string Save;
      COptions::getValue("Save", Save);
      CCopasiDataModel::Global->saveModel(Save);
    }

  COptions::nonOptionType::const_iterator it = Files.begin();
  COptions::nonOptionType::const_iterator end = Files.end();

  for (; it != end; ++it)
    {
      CCopasiDataModel::Global->loadModel(*it);

      // Check whether exporting to SBML is requested.
      if (!COptions::compareValue("ExportSBML", std::string("")))
        {
          // Export the SBML File
          std::string ExportSBML;
          COptions::getValue("ExportSBML", ExportSBML);
          CCopasiDataModel::Global->exportSBML(ExportSBML);

          // Since only one export file name can be specified we
          // stop execution.
          return 0;
        }

      CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList();
      unsigned C_INT32 i, imax = TaskList.size();

      for (i = 0; i < imax; i++)
        if (TaskList[i]->isScheduled())
          {
            TaskList[i]->getProblem()->setModel(CCopasiDataModel::Global->getModel());

            TaskList[i]->initialize();
            TaskList[i]->process();
            TaskList[i]->restore();
          }

      // Check whether a file for saving the resulting model is given
      if (!COptions::compareValue("Save", std::string("")))
        {
          std::string Save;
          COptions::getValue("Save", Save);
          CCopasiDataModel::Global->saveModel(Save);

          // Since only one save file name can be specified we
          // stop execution.
          return 0;
        }

      CCopasiDataModel::Global->saveModel("");
    }

  //  catch (CCopasiException Exception)
  //    {
  //      std::cout << Exception.getMessage().getText() << std::endl;
  //}

  pdelete(CCopasiDataModel::Global);
  pdelete(CCopasiContainer::Root);

  std::cout << "Leaving main program." << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CModelValue.cpp,v $
//   $Revision: 1.45 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2007/10/02 18:18:05 $
// End CVS Header

// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <iostream>
#include <string>
#include <vector>
#include <limits>

#include "copasi.h"

#include "CModel.h"
#include "CModelValue.h"

#include "CopasiDataModel/CCopasiDataModel.h"
#include "function/CExpression.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "utilities/utility.h"

//static
const std::string CModelEntity::StatusName[] =
  {
    "fixed",
    "assignment",
    "reactions",
    "ode",
    "time",
    ""
  };

//static
const char * CModelEntity::XMLStatus[] =
  {
    "fixed",
    "assignment",
    "reactions",
    "ode",
    "time",
    NULL
  };

// the "variable" keyword is used for compatibility reasons. It actually means "this metab is part
// of the reaction network, copasi needs to figure out if it is independent, dependent (moieties) or unused."

CModelEntity::CModelEntity(const std::string & name,
                           const CCopasiContainer * pParent,
                           const std::string & type,
                           const unsigned C_INT32 & flag):
    CCopasiContainer(name, pParent, type, (flag | CCopasiObject::Container | CCopasiObject::ValueDbl | CCopasiObject::ModelEntity)),
    mKey(""),
    mpValueData(NULL),
    mpValueAccess(NULL),
    mpIValue(NULL),
    mRate(0.0),
    mpExpression(NULL),
    mpInitialExpression(NULL),
    mStatus(FIXED),
    mUsed(false),
    mUsedOnce(false),
    mpModel(NULL)
{
  initObjects();

  *mpIValue = 1.0;
  *mpValueData = std::numeric_limits<C_FLOAT64>::quiet_NaN();

  CONSTRUCTOR_TRACE;
}

CModelEntity::CModelEntity(const CModelEntity & src,
                           const CCopasiContainer * pParent):
    CCopasiContainer(src, pParent),
    mKey(""),
    mpValueData(NULL),
    mpValueAccess(NULL),
    mpIValue(NULL),
    mRate(src.mRate),
    mpExpression(new CExpression(*src.mpExpression)),
    mpInitialExpression(new CExpression(*src.mpInitialExpression)),
    mStatus(FIXED),
    mUsed(false),
    mUsedOnce(false),
    mpModel(NULL)
{
  initObjects();

  setStatus(src.mStatus);

  *mpValueData = *src.mpValueData;
  *mpIValue = *src.mpIValue;

  CONSTRUCTOR_TRACE;
}

CModelEntity::~CModelEntity()
{
  if (mpModel)
    mpModel->getStateTemplate().remove(this);

  // After the above call we definitely own the data and
  // therfore must destroy them.

  pdelete(mpValueData);
  pdelete(mpIValue);
  pdelete(mpExpression);
  pdelete(mpInitialExpression);

  DESTRUCTOR_TRACE;
}

const std::string & CModelEntity::getKey() const {return mKey;}

const C_FLOAT64 & CModelEntity::getValue() const {return *mpValueAccess;}

const C_FLOAT64 & CModelEntity::getInitialValue() const
  {
    if (mpInitialExpression != NULL)
      const_cast< CModelEntity * >(this)->refreshInitialValue();

    return *mpIValue;
  }

const CModelEntity::Status & CModelEntity::getStatus() const {return mStatus;}

bool CModelEntity::compile()
{
  bool success = true;

  std::set< const CCopasiObject * > NoDependencies;
  std::vector< CCopasiContainer * > listOfContainer;

  switch (mStatus)
    {
    case ASSIGNMENT:
      listOfContainer.push_back(getObjectAncestor("Model"));

      success &= mpExpression->compile(listOfContainer);
      mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());

      pdelete(mpInitialExpression);
      mpInitialExpression = CExpression::createInitialExpression(*mpExpression);

      if (mpInitialExpression != NULL)
        {
          success &= mpInitialExpression->compile(listOfContainer);
          mpIValueReference->setDirectDependencies(mpInitialExpression->getDirectDependencies());
          mpIValueReference->setRefresh(this, &CModelEntity::refreshInitialValue);
        }
      else
        {
          mpIValueReference->setDirectDependencies(NoDependencies);
          mpIValueReference->clearRefresh();
        }

      break;

    case ODE:
      mpValueReference->addDirectDependency(this);

      listOfContainer.push_back(getObjectAncestor("Model"));
      success &= mpExpression->compile(listOfContainer);
      mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());

      break;

    default:
      break;
    }

  return success;
}

void CModelEntity::calculate()
{
  switch (mStatus)
    {
    case ASSIGNMENT:
      *mpValueData = mpExpression->calcValue();
      break;

    case ODE:
      mRate = mpExpression->calcValue();
      break;

    default:
      break;
    }
}

void CModelEntity::refreshInitialValue()
{
  switch (mStatus)
    {
    case ASSIGNMENT:
      *mpIValue = mpInitialExpression->calcValue();
      break;

    default:
      break;
    }
}

bool CModelEntity::setExpression(const std::string & expression)
{
  if (isFixed()) return false;

  if (mpExpression == NULL)
    mpExpression = new CExpression;

  if (mpModel)
    mpModel->setCompileFlag(true);

  if (!mpExpression->setInfix(expression)) return false;

  return compile();
}

std::string CModelEntity::getExpression() const
  {
    if (isFixed() || mpExpression == NULL)
      return "";

    mpExpression->updateInfix();
    return mpExpression->getInfix();
  }

CExpression* CModelEntity::getExpressionPtr()
{
  return mpExpression;
}

const CExpression* CModelEntity::getExpressionPtr() const
  {
    return mpExpression;
  }

bool CModelEntity::setExpressionPtr(CExpression* pExpression)
{
  if (isFixed()) return false;

  if (mpExpression)
    pdelete(mpExpression);

  mpExpression = pExpression;

  if (mpModel)
    mpModel->setCompileFlag(true);

  return compile();
}

CExpression* CModelEntity::getInitialExpressionPtr()
{
  return mpInitialExpression;
}

const CExpression* CModelEntity::getInitialExpressionPtr() const
  {
    return mpInitialExpression;
  }

bool CModelEntity::setInitialExpressionPtr(CExpression* pExpression)
{
  if (mStatus == ASSIGNMENT) return false;

  if (mpInitialExpression)
    pdelete(mpInitialExpression);

  mpInitialExpression = pExpression;

  return compile();
}

bool CModelEntity::setInitialExpression(const std::string & expression)
{
  if (mStatus == ASSIGNMENT) return false;

  if (mpInitialExpression == NULL)
    mpInitialExpression = new CExpression;

  return mpInitialExpression->setInfix(expression);
}

std::string CModelEntity::getInitialExpression() const
  {
    if (mStatus == ASSIGNMENT || mpInitialExpression == NULL)
      return "";

    return mpInitialExpression->getInfix();
  }

/**
 * Return rate of production of this entity
 */
const C_FLOAT64 & CModelEntity::getRate() const
  {
    return mRate;
  }

CCopasiObject * CModelEntity::getInitialValueReference() const
  {return mpIValueReference;}

CCopasiObject * CModelEntity::getValueReference() const
  {return mpValueReference;}

CCopasiObject * CModelEntity::getRateReference() const
  {return mpRateReference;}

//***********

void CModelEntity::setValue(const C_FLOAT64 & value)
{
  if (mStatus == FIXED) return;

  *mpValueData = value;

#ifdef COPASI_DEBUG
  //if (mStatus == FIXED)
  //std::cout << "warning: set the transient concentration on a fixed entity" << std::endl;
#endif
}

void CModelEntity::setInitialValue(const C_FLOAT64 & initialValue)
{
  *mpIValue = initialValue;
}

void CModelEntity::setRate(const C_FLOAT64 & rate)
{
  mRate = rate;
}

//  ******************

void CModelEntity::setStatus(const CModelEntity::Status & status)
{
  if (mStatus != status)
    {
      if (mpModel != NULL)
        mpModel->setCompileFlag(true);

      mStatus = status;
      this->setValuePtr(mpValueData);

      if (mpModel != NULL)
        mpModel->setCompileFlag(true);

      std::set< const CCopasiObject * > NoDependencies;

      setDirectDependencies(NoDependencies);
      clearRefresh();

      pdelete(mpInitialExpression);

      mpIValueReference->setDirectDependencies(NoDependencies);
      mpIValueReference->clearRefresh();

      mpValueReference->setDirectDependencies(NoDependencies);
      mpValueReference->clearRefresh();

      mpRateReference->setDirectDependencies(NoDependencies);
      mpRateReference->clearRefresh();

      switch (mStatus)
        {
        case ASSIGNMENT:
          if (mpExpression == NULL)
            mpExpression = new CExpression;

          mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());
          mpValueReference->setRefresh(this, &CModelEntity::calculate);

          mRate = std::numeric_limits<C_FLOAT64>::quiet_NaN();

          mUsed = true;
          mUsedOnce = false;
          break;

        case ODE:
          if (mpExpression == NULL)
            mpExpression = new CExpression;

          mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());
          mpRateReference->setRefresh(this, &CModelEntity::calculate);

          mUsed = true;
          mUsedOnce = false;
          break;

        case REACTIONS:
          pdelete(mpExpression);

          mUsed = true;
          mUsedOnce = false;
          break;

        case TIME:
          pdelete(mpExpression);

          mUsed = true;
          mUsedOnce = false;
          break;

        case FIXED:
          pdelete(mpExpression);

          mRate = 0.0;

          mUsed = false;
          mUsedOnce = false;
          break;
        }
    }
}

void * CModelEntity::getValuePointer() const
{return const_cast<C_FLOAT64 *>(mpValueAccess);}

void CModelEntity::initObjects()
{
  C_FLOAT64 Dummy;

  mpValueReference =
    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("Value",
        Dummy,
        CCopasiObject::ValueDbl));
  mpIValueReference =
    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("InitialValue",
        Dummy,
        CCopasiObject::ValueDbl));

  mpRateReference =
    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("Rate", mRate, CCopasiObject::ValueDbl));

  addObjectReference("SBMLId", mSBMLId, CCopasiObject::ValueString);

  mpModel = static_cast<CModel *>(getObjectAncestor("Model"));

  if (mpModel)
    {
      mpModel->getStateTemplate().add(this);
    }
  else
    {
      // This creates the needed values.
      setInitialValuePtr(NULL);
      setValuePtr(NULL);
    }
}

void CModelEntity::setInitialValuePtr(C_FLOAT64 * pInitialValue)
{
  mpIValue = pInitialValue;
  if (!mpIValue) mpIValue = new C_FLOAT64;
  mpIValueReference->setReference(*mpIValue);
}

void CModelEntity::setValuePtr(C_FLOAT64 * pValue)
{
  mpValueData = pValue;
  if (!mpValueData) mpValueData = new C_FLOAT64;

  if (mStatus == FIXED)
    mpValueAccess = mpIValue;
  else
    mpValueAccess = mpValueData;

  mpValueReference->setReference(*mpValueAccess);
}

bool CModelEntity::setObjectParent(const CCopasiContainer * pParent)
{
  CCopasiContainer::setObjectParent(pParent);
  CModel * pNewModel = static_cast<CModel *>(getObjectAncestor("Model"));

  if (mpModel == pNewModel) return true;

  C_FLOAT64 InitialValue = *mpIValue;
  C_FLOAT64 Value = *mpValueData;

  if (mpModel)
    {
      mpModel->getStateTemplate().remove(this);
    }
  else
    {
      pdelete(mpIValue);
      pdelete(mpValueData);
    }

  if (pNewModel)
    {
      pNewModel->getStateTemplate().add(this);
    }
  else
    {
      mpValueData = new C_FLOAT64;
      mpIValue = new C_FLOAT64;
    }

  mpModel = pNewModel;
  *mpIValue = InitialValue;
  *mpValueData = Value;

  return true;
}

std::set< const CCopasiObject * > CModelEntity::getDeletedObjects() const
  {
    std::set< const CCopasiObject * > Deleted;

    Deleted.insert(this);
    Deleted.insert(mpIValueReference);
    Deleted.insert(mpValueReference);
    Deleted.insert(mpRateReference);

    return Deleted;
  }

void CModelEntity::setSBMLId(const std::string& id)
{
  this->mSBMLId = id;
}

const std::string& CModelEntity::getSBMLId() const
  {
    return this->mSBMLId;
  }

void CModelEntity::setUsed(const bool & used)
{mUsed = used;}

const bool & CModelEntity::isUsed() const
  {return mUsed;}

void CModelEntity::setUsedOnce(const bool & usedOnce)
{mUsedOnce = usedOnce;}

const bool & CModelEntity::isUsedOnce() const
  {return mUsedOnce;}

//********************************************************************+

CModelValue::CModelValue(const std::string & name,
                         const CCopasiContainer * pParent):
    CModelEntity(name, pParent, "ModelValue")
{
  mKey = GlobalKeys.add("ModelValue", this);
  initObjects();

  CONSTRUCTOR_TRACE;
}

CModelValue::CModelValue(const CModelValue & src,
                         const CCopasiContainer * pParent):
    CModelEntity(src, pParent)
{
  mKey = GlobalKeys.add("ModelValue", this);
  initObjects();
  CONSTRUCTOR_TRACE;
}

CModelValue::~CModelValue()
{
  GlobalKeys.remove(mKey);

  DESTRUCTOR_TRACE;
}

void CModelValue::initObjects()
{}

std::ostream & operator<<(std::ostream &os, const CModelValue & d)
{
  os << "    ++++CModelValue: " << d.getObjectName() << std::endl;
  os << "        mValue " << *d.mpValueAccess << " mIValue " << *d.mpIValue << std::endl;
  os << "        mRate " << d.mRate << " mStatus " << d.getStatus() << std::endl;
  os << "    ----CModelValue " << std::endl;

  return os;
}
<commit_msg>Fixed Bug 779. CModelEntity supports now initial expressions. This includes hdnling them in setStatus() and compile().<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/model/CModelValue.cpp,v $
//   $Revision: 1.46 $
//   $Name:  $
//   $Author: shoops $
//   $Date: 2007/10/09 19:07:23 $
// End CVS Header

// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <iostream>
#include <string>
#include <vector>
#include <limits>

#include "copasi.h"

#include "CModel.h"
#include "CModelValue.h"

#include "CopasiDataModel/CCopasiDataModel.h"
#include "function/CExpression.h"
#include "report/CCopasiObjectReference.h"
#include "report/CKeyFactory.h"
#include "utilities/utility.h"

//static
const std::string CModelEntity::StatusName[] =
  {
    "fixed",
    "assignment",
    "reactions",
    "ode",
    "time",
    ""
  };

//static
const char * CModelEntity::XMLStatus[] =
  {
    "fixed",
    "assignment",
    "reactions",
    "ode",
    "time",
    NULL
  };

// the "variable" keyword is used for compatibility reasons. It actually means "this metab is part
// of the reaction network, copasi needs to figure out if it is independent, dependent (moieties) or unused."

CModelEntity::CModelEntity(const std::string & name,
                           const CCopasiContainer * pParent,
                           const std::string & type,
                           const unsigned C_INT32 & flag):
    CCopasiContainer(name, pParent, type, (flag | CCopasiObject::Container | CCopasiObject::ValueDbl | CCopasiObject::ModelEntity)),
    mKey(""),
    mpValueData(NULL),
    mpValueAccess(NULL),
    mpIValue(NULL),
    mRate(0.0),
    mpExpression(NULL),
    mpInitialExpression(NULL),
    mStatus(FIXED),
    mUsed(false),
    mUsedOnce(false),
    mpModel(NULL)
{
  initObjects();

  *mpIValue = 1.0;
  *mpValueData = std::numeric_limits<C_FLOAT64>::quiet_NaN();

  CONSTRUCTOR_TRACE;
}

CModelEntity::CModelEntity(const CModelEntity & src,
                           const CCopasiContainer * pParent):
    CCopasiContainer(src, pParent),
    mKey(""),
    mpValueData(NULL),
    mpValueAccess(NULL),
    mpIValue(NULL),
    mRate(src.mRate),
    mpExpression(new CExpression(*src.mpExpression)),
    mpInitialExpression(new CExpression(*src.mpInitialExpression)),
    mStatus(FIXED),
    mUsed(false),
    mUsedOnce(false),
    mpModel(NULL)
{
  initObjects();

  setStatus(src.mStatus);

  *mpValueData = *src.mpValueData;
  *mpIValue = *src.mpIValue;

  CONSTRUCTOR_TRACE;
}

CModelEntity::~CModelEntity()
{
  if (mpModel)
    mpModel->getStateTemplate().remove(this);

  // After the above call we definitely own the data and
  // therfore must destroy them.

  pdelete(mpValueData);
  pdelete(mpIValue);
  pdelete(mpExpression);
  pdelete(mpInitialExpression);

  DESTRUCTOR_TRACE;
}

const std::string & CModelEntity::getKey() const {return mKey;}

const C_FLOAT64 & CModelEntity::getValue() const {return *mpValueAccess;}

const C_FLOAT64 & CModelEntity::getInitialValue() const
  {
    if (mpInitialExpression != NULL)
      const_cast< CModelEntity * >(this)->refreshInitialValue();

    return *mpIValue;
  }

const CModelEntity::Status & CModelEntity::getStatus() const {return mStatus;}

bool CModelEntity::compile()
{
  bool success = true;

  std::set< const CCopasiObject * > NoDependencies;
  std::vector< CCopasiContainer * > listOfContainer;
  listOfContainer.push_back(mpModel);

  switch (mStatus)
    {
    case ASSIGNMENT:
      success &= mpExpression->compile(listOfContainer);
      mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());

      pdelete(mpInitialExpression);
      mpInitialExpression = CExpression::createInitialExpression(*mpExpression);

      break;

    case ODE:
      mpValueReference->addDirectDependency(this);

      success &= mpExpression->compile(listOfContainer);
      mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());

    default:
      break;
    }

  // Here we handle initial expressions for all types.
  if (getInitialExpression() != "")
    {
      success &= mpInitialExpression->compile(listOfContainer);
      mpIValueReference->setDirectDependencies(mpInitialExpression->getDirectDependencies());
      mpIValueReference->setRefresh(this, &CModelEntity::refreshInitialValue);
    }
  else
    {
      mpIValueReference->setDirectDependencies(NoDependencies);
      mpIValueReference->clearRefresh();
    }

  return success;
}

void CModelEntity::calculate()
{
  switch (mStatus)
    {
    case ASSIGNMENT:
      *mpValueData = mpExpression->calcValue();
      break;

    case ODE:
      mRate = mpExpression->calcValue();
      break;

    default:
      break;
    }
}

void CModelEntity::refreshInitialValue()
{
  switch (mStatus)
    {
    case ASSIGNMENT:
      *mpIValue = mpInitialExpression->calcValue();
      break;

    default:
      break;
    }
}

bool CModelEntity::setExpression(const std::string & expression)
{
  if (isFixed()) return false;

  if (mpExpression == NULL)
    mpExpression = new CExpression;

  if (mpModel)
    mpModel->setCompileFlag(true);

  if (!mpExpression->setInfix(expression)) return false;

  return compile();
}

std::string CModelEntity::getExpression() const
  {
    if (isFixed() || mpExpression == NULL)
      return "";

    mpExpression->updateInfix();
    return mpExpression->getInfix();
  }

CExpression* CModelEntity::getExpressionPtr()
{
  return mpExpression;
}

const CExpression* CModelEntity::getExpressionPtr() const
  {
    return mpExpression;
  }

bool CModelEntity::setExpressionPtr(CExpression* pExpression)
{
  if (isFixed()) return false;

  if (mpExpression)
    pdelete(mpExpression);

  mpExpression = pExpression;

  if (mpModel)
    mpModel->setCompileFlag(true);

  return compile();
}

CExpression* CModelEntity::getInitialExpressionPtr()
{
  return mpInitialExpression;
}

const CExpression* CModelEntity::getInitialExpressionPtr() const
  {
    return mpInitialExpression;
  }

bool CModelEntity::setInitialExpressionPtr(CExpression* pExpression)
{
  if (mStatus == ASSIGNMENT) return false;

  if (mpInitialExpression)
    pdelete(mpInitialExpression);

  mpInitialExpression = pExpression;

  return compile();
}

bool CModelEntity::setInitialExpression(const std::string & expression)
{
  if (mStatus == ASSIGNMENT) return false;

  if (mpInitialExpression == NULL)
    mpInitialExpression = new CExpression;

  return mpInitialExpression->setInfix(expression);
}

std::string CModelEntity::getInitialExpression() const
  {
    if (mStatus == ASSIGNMENT || mpInitialExpression == NULL)
      return "";

    mpInitialExpression->updateInfix();
    return mpInitialExpression->getInfix();
  }

/**
 * Return rate of production of this entity
 */
const C_FLOAT64 & CModelEntity::getRate() const
  {
    return mRate;
  }

CCopasiObject * CModelEntity::getInitialValueReference() const
  {return mpIValueReference;}

CCopasiObject * CModelEntity::getValueReference() const
  {return mpValueReference;}

CCopasiObject * CModelEntity::getRateReference() const
  {return mpRateReference;}

//***********

void CModelEntity::setValue(const C_FLOAT64 & value)
{
  if (mStatus == FIXED) return;

  *mpValueData = value;

#ifdef COPASI_DEBUG
  //if (mStatus == FIXED)
  //std::cout << "warning: set the transient concentration on a fixed entity" << std::endl;
#endif
}

void CModelEntity::setInitialValue(const C_FLOAT64 & initialValue)
{
  *mpIValue = initialValue;
}

void CModelEntity::setRate(const C_FLOAT64 & rate)
{
  mRate = rate;
}

//  ******************

void CModelEntity::setStatus(const CModelEntity::Status & status)
{
  if (mStatus != status)
    {
      if (mpModel != NULL)
        mpModel->setCompileFlag(true);

      mStatus = status;
      this->setValuePtr(mpValueData);

      if (mpModel != NULL)
        mpModel->setCompileFlag(true);

      std::set< const CCopasiObject * > NoDependencies;

      setDirectDependencies(NoDependencies);
      clearRefresh();

      mpIValueReference->setDirectDependencies(NoDependencies);
      mpIValueReference->clearRefresh();

      mpValueReference->setDirectDependencies(NoDependencies);
      mpValueReference->clearRefresh();

      mpRateReference->setDirectDependencies(NoDependencies);
      mpRateReference->clearRefresh();

      switch (mStatus)
        {
        case ASSIGNMENT:
          if (mpExpression == NULL)
            mpExpression = new CExpression;

          pdelete(mpInitialExpression);
          mpInitialExpression = CExpression::createInitialExpression(*mpExpression);

          mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());
          mpValueReference->setRefresh(this, &CModelEntity::calculate);

          mRate = std::numeric_limits<C_FLOAT64>::quiet_NaN();

          mUsed = true;
          mUsedOnce = false;
          break;

        case ODE:
          if (mpExpression == NULL)
            mpExpression = new CExpression;

          mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());
          mpRateReference->setRefresh(this, &CModelEntity::calculate);

          mUsed = true;
          mUsedOnce = false;
          break;

        case REACTIONS:
          pdelete(mpExpression);

          mUsed = true;
          mUsedOnce = false;
          break;

        case TIME:
          pdelete(mpExpression);

          mUsed = true;
          mUsedOnce = false;
          break;

        case FIXED:
          pdelete(mpExpression);

          mRate = 0.0;

          mUsed = false;
          mUsedOnce = false;
          break;
        }
    }
}

void * CModelEntity::getValuePointer() const
{return const_cast<C_FLOAT64 *>(mpValueAccess);}

void CModelEntity::initObjects()
{
  C_FLOAT64 Dummy;

  mpValueReference =
    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("Value",
        Dummy,
        CCopasiObject::ValueDbl));
  mpIValueReference =
    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("InitialValue",
        Dummy,
        CCopasiObject::ValueDbl));

  mpRateReference =
    static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference("Rate", mRate, CCopasiObject::ValueDbl));

  addObjectReference("SBMLId", mSBMLId, CCopasiObject::ValueString);

  mpModel = static_cast<CModel *>(getObjectAncestor("Model"));

  if (mpModel)
    {
      mpModel->getStateTemplate().add(this);
    }
  else
    {
      // This creates the needed values.
      setInitialValuePtr(NULL);
      setValuePtr(NULL);
    }
}

void CModelEntity::setInitialValuePtr(C_FLOAT64 * pInitialValue)
{
  mpIValue = pInitialValue;
  if (!mpIValue) mpIValue = new C_FLOAT64;
  mpIValueReference->setReference(*mpIValue);
}

void CModelEntity::setValuePtr(C_FLOAT64 * pValue)
{
  mpValueData = pValue;
  if (!mpValueData) mpValueData = new C_FLOAT64;

  if (mStatus == FIXED)
    mpValueAccess = mpIValue;
  else
    mpValueAccess = mpValueData;

  mpValueReference->setReference(*mpValueAccess);
}

bool CModelEntity::setObjectParent(const CCopasiContainer * pParent)
{
  CCopasiContainer::setObjectParent(pParent);
  CModel * pNewModel = static_cast<CModel *>(getObjectAncestor("Model"));

  if (mpModel == pNewModel) return true;

  C_FLOAT64 InitialValue = *mpIValue;
  C_FLOAT64 Value = *mpValueData;

  if (mpModel)
    {
      mpModel->getStateTemplate().remove(this);
    }
  else
    {
      pdelete(mpIValue);
      pdelete(mpValueData);
    }

  if (pNewModel)
    {
      pNewModel->getStateTemplate().add(this);
    }
  else
    {
      mpValueData = new C_FLOAT64;
      mpIValue = new C_FLOAT64;
    }

  mpModel = pNewModel;
  *mpIValue = InitialValue;
  *mpValueData = Value;

  return true;
}

std::set< const CCopasiObject * > CModelEntity::getDeletedObjects() const
  {
    std::set< const CCopasiObject * > Deleted;

    Deleted.insert(this);
    Deleted.insert(mpIValueReference);
    Deleted.insert(mpValueReference);
    Deleted.insert(mpRateReference);

    return Deleted;
  }

void CModelEntity::setSBMLId(const std::string& id)
{
  this->mSBMLId = id;
}

const std::string& CModelEntity::getSBMLId() const
  {
    return this->mSBMLId;
  }

void CModelEntity::setUsed(const bool & used)
{mUsed = used;}

const bool & CModelEntity::isUsed() const
  {return mUsed;}

void CModelEntity::setUsedOnce(const bool & usedOnce)
{mUsedOnce = usedOnce;}

const bool & CModelEntity::isUsedOnce() const
  {return mUsedOnce;}

//********************************************************************+

CModelValue::CModelValue(const std::string & name,
                         const CCopasiContainer * pParent):
    CModelEntity(name, pParent, "ModelValue")
{
  mKey = GlobalKeys.add("ModelValue", this);
  initObjects();

  CONSTRUCTOR_TRACE;
}

CModelValue::CModelValue(const CModelValue & src,
                         const CCopasiContainer * pParent):
    CModelEntity(src, pParent)
{
  mKey = GlobalKeys.add("ModelValue", this);
  initObjects();
  CONSTRUCTOR_TRACE;
}

CModelValue::~CModelValue()
{
  GlobalKeys.remove(mKey);

  DESTRUCTOR_TRACE;
}

void CModelValue::initObjects()
{}

std::ostream & operator<<(std::ostream &os, const CModelValue & d)
{
  os << "    ++++CModelValue: " << d.getObjectName() << std::endl;
  os << "        mValue " << *d.mpValueAccess << " mIValue " << *d.mpIValue << std::endl;
  os << "        mRate " << d.mRate << " mStatus " << d.getStatus() << std::endl;
  os << "    ----CModelValue " << std::endl;

  return os;
}
<|endoftext|>


<commit_before>// @(#)root/cont:$Id$
// Author: Rene Brun   28/09/2001

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//
// TProcessID
//
// A TProcessID identifies a ROOT job in a unique way in time and space.
// The TProcessID title consists of a TUUID object which provides a globally
// unique identifier (for more see TUUID.h).
//
// A TProcessID is automatically created by the TROOT constructor.
// When a TFile contains referenced objects (see TRef), the TProcessID
// object is written to the file.
// If a file has been written in multiple sessions (same machine or not),
// a TProcessID is written for each session.
// These objects are used by the class TRef to uniquely identified
// any TObject pointed by a TRef.
//
// When a referenced object is read from a file (its bit kIsReferenced is set),
// this object is entered into the objects table of the corresponding TProcessID.
// Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also
// accessible via TProcessID::fgPIDs (for all files).
// When this object is deleted, it is removed from the table via the cleanup
// mechanism invoked by the TObject destructor.
//
// Each TProcessID has a table (TObjArray *fObjects) that keeps track
// of all referenced objects. If a referenced object has a fUniqueID set,
// a pointer to this unique object may be found via fObjects->At(fUniqueID).
// In the same way, when a TRef::GetObject is called, GetObject uses
// its own fUniqueID to find the pointer to the referenced object.
// See TProcessID::GetObjectWithID and PutObjectWithID.
//
// When a referenced object is deleted, its slot in fObjects is set to null.
//
// See also TProcessUUID: a specialized TProcessID to manage the single list
// of TUUIDs.
//
//////////////////////////////////////////////////////////////////////////

#include "TProcessID.h"
#include "TROOT.h"
#include "TObjArray.h"
#include "TExMap.h"
#include "TVirtualMutex.h"

TObjArray  *TProcessID::fgPIDs   = 0; //pointer to the list of TProcessID
TProcessID *TProcessID::fgPID    = 0; //pointer to the TProcessID of the current session
UInt_t      TProcessID::fgNumber = 0; //Current referenced object instance count
TExMap     *TProcessID::fgObjPIDs= 0; //Table (pointer,pids)
ClassImp(TProcessID)

//______________________________________________________________________________
static inline ULong_t Void_Hash(const void *ptr)
{
   // Return hash value for this object.

   return TString::Hash(&ptr, sizeof(void*));
}

//______________________________________________________________________________
TProcessID::TProcessID()
{
   // Default constructor.

   fCount = 0;
   fObjects = 0;
}

//______________________________________________________________________________
TProcessID::~TProcessID()
{
   // Destructor.

   delete fObjects;
   fObjects = 0;
   R__LOCKGUARD2(gROOTMutex);
   fgPIDs->Remove(this);
}

//______________________________________________________________________________
TProcessID *TProcessID::AddProcessID()
{
   // Static function to add a new TProcessID to the list of PIDs.

   R__LOCKGUARD2(gROOTMutex);

   TProcessID *pid = new TProcessID();

   if (!fgPIDs) {
      fgPID  = pid;
      fgPIDs = new TObjArray(10);
      gROOT->GetListOfCleanups()->Add(fgPIDs);
   }
   UShort_t apid = fgPIDs->GetEntriesFast();
   pid->IncrementCount();

   fgPIDs->Add(pid);
   char name[20];
   sprintf(name,"ProcessID%d",apid);
   pid->SetName(name);
   TUUID u;
   apid = fgPIDs->GetEntriesFast();
   pid->SetTitle(u.AsString());
   return pid;
}

//______________________________________________________________________________
UInt_t TProcessID::AssignID(TObject *obj)
{
   // static function returning the ID assigned to obj
   // If the object is not yet referenced, its kIsReferenced bit is set
   // and its fUniqueID set to the current number of referenced objects so far.

   R__LOCKGUARD2(gROOTMutex);

   UInt_t uid = obj->GetUniqueID() & 0xffffff;
   if (obj == fgPID->GetObjectWithID(uid)) return uid;
   if (obj->TestBit(kIsReferenced)) {
      fgPID->PutObjectWithID(obj,uid);
      return uid;
   }
   fgNumber++;
   obj->SetBit(kIsReferenced);
   uid = fgNumber;
   obj->SetUniqueID(uid);
   fgPID->PutObjectWithID(obj,uid);
   return uid;
}

//______________________________________________________________________________
void TProcessID::CheckInit()
{
   // Initialize fObjects.
   if (!fObjects) fObjects = new TObjArray(100);
}

//______________________________________________________________________________
void TProcessID::Cleanup()
{
   // static function (called by TROOT destructor) to delete all TProcessIDs

   R__LOCKGUARD2(gROOTMutex);

   fgPIDs->Delete();
   gROOT->GetListOfCleanups()->Remove(fgPIDs);
   delete fgPIDs;
}

//______________________________________________________________________________
void TProcessID::Clear(Option_t *)
{
   // delete the TObjArray pointing to referenced objects
   // this function is called by TFile::Close("R")

   delete fObjects; fObjects = 0;
}

//______________________________________________________________________________
Int_t TProcessID::DecrementCount()
{

   // the reference fCount is used to delete the TProcessID
   // in the TFile destructor when fCount = 0

   fCount--;
   if (fCount < 0) fCount = 0;
   return fCount;
}

//______________________________________________________________________________
TProcessID *TProcessID::GetProcessID(UShort_t pid)
{
   // static function returning a pointer to TProcessID number pid in fgPIDs

   return (TProcessID*)fgPIDs->At(pid);
}

//______________________________________________________________________________
UInt_t TProcessID::GetNProcessIDs()
{
   // Return the (static) number of process IDs.
   return fgPIDs ? fgPIDs->GetLast()+1 : 0;
}

//______________________________________________________________________________
TProcessID *TProcessID::GetProcessWithUID(UInt_t uid, const void *obj)
{
   // static function returning a pointer to TProcessID with its pid
   // encoded in the highest byte of uid

   R__LOCKGUARD2(gROOTMutex);

   Int_t pid = (uid>>24)&0xff;
   if (pid==0xff) {
      // Look up the pid in the table (pointer,pid)
      if (fgObjPIDs==0) return 0;
      ULong_t hash = Void_Hash(obj);
      pid = fgObjPIDs->GetValue(hash,(Long_t)obj);
   }
   return (TProcessID*)fgPIDs->At(pid);
}

//______________________________________________________________________________
TProcessID *TProcessID::GetProcessWithUID(const TObject *obj)
{
   // static function returning a pointer to TProcessID with its pid
   // encoded in the highest byte of obj->GetUniqueID()

   return GetProcessWithUID(obj->GetUniqueID(),obj);
}

//______________________________________________________________________________
TProcessID *TProcessID::GetSessionProcessID()
{
   // static function returning the pointer to the session TProcessID

   return fgPID;
}

//______________________________________________________________________________
Int_t TProcessID::IncrementCount()
{
   // Increase the reference count to this object.

   if (!fObjects) fObjects = new TObjArray(100);
   fCount++;
   return fCount;
}

//______________________________________________________________________________
UInt_t TProcessID::GetObjectCount()
{
   // Return the current referenced object count
   // fgNumber is incremented everytime a new object is referenced

   return fgNumber;
}

//______________________________________________________________________________
TObject *TProcessID::GetObjectWithID(UInt_t uidd)
{
   //returns the TObject with unique identifier uid in the table of objects

   Int_t uid = uidd & 0xffffff;  //take only the 24 lower bits

   if (fObjects==0 || uid >= fObjects->GetSize()) return 0;
   return fObjects->UncheckedAt(uid);
}

//______________________________________________________________________________
TProcessID *TProcessID::GetPID()
{
   //static: returns pointer to current TProcessID

   return fgPID;
}

//______________________________________________________________________________
TObjArray *TProcessID::GetPIDs()
{
   //static: returns array of TProcessIDs

   return fgPIDs;
}

//______________________________________________________________________________
Bool_t TProcessID::IsValid(TProcessID *pid)
{
   // static function. return kTRUE if pid is a valid TProcessID

   R__LOCKGUARD2(gROOTMutex);

   if (fgPIDs->IndexOf(pid) >= 0) return kTRUE;
   if (pid == (TProcessID*)gROOT->GetUUIDs())  return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
void TProcessID::PutObjectWithID(TObject *obj, UInt_t uid)
{
   //stores the object at the uid th slot in the table of objects
   //The object uniqueid is set as well as its kMustCleanup bit

   if (uid == 0) uid = obj->GetUniqueID() & 0xffffff;

   if (!fObjects) fObjects = new TObjArray(100);
   fObjects->AddAtAndExpand(obj,uid);

   obj->SetBit(kMustCleanup);
   if ( (obj->GetUniqueID()&0xff000000)==0xff000000 ) {
      // We have more than 255 pids we need to store this
      // pointer in the table(pointer,pid) since there is no
      // more space in fUniqueID
      if (fgObjPIDs==0) fgObjPIDs = new TExMap;
      ULong_t hash = Void_Hash(obj);

      // We use operator() rather than Add() because
      // if the address has already been registered, we want to
      // update it's uniqueID (this can easily happen when the
      // referenced obejct have been stored in a TClonesArray.
      (*fgObjPIDs)(hash, (Long_t)obj) = GetUniqueID();
   }
}

//______________________________________________________________________________
void TProcessID::RecursiveRemove(TObject *obj)
{
   // called by the object destructor
   // remove reference to obj from the current table if it is referenced

   if (!fObjects) return;
   if (!obj->TestBit(kIsReferenced)) return;
   UInt_t uid = obj->GetUniqueID() & 0xffffff;
   if (obj == GetObjectWithID(uid)) fObjects->RemoveAt(uid);
}

//______________________________________________________________________________
void TProcessID::SetObjectCount(UInt_t number)
{
   // static function to set the current referenced object count
   // fgNumber is incremented everytime a new object is referenced

   fgNumber = number;
}
<commit_msg>Fix typo in the documentation<commit_after>// @(#)root/cont:$Id$
// Author: Rene Brun   28/09/2001

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//
// TProcessID
//
// A TProcessID identifies a ROOT job in a unique way in time and space.
// The TProcessID title consists of a TUUID object which provides a globally
// unique identifier (for more see TUUID.h).
//
// A TProcessID is automatically created by the TROOT constructor.
// When a TFile contains referenced objects (see TRef), the TProcessID
// object is written to the file.
// If a file has been written in multiple sessions (same machine or not),
// a TProcessID is written for each session.
// These objects are used by the class TRef to uniquely identified
// any TObject pointed by a TRef.
//
// When a referenced object is read from a file (its bit kIsReferenced is set),
// this object is entered into the objects table of the corresponding TProcessID.
// Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also
// accessible via TProcessID::fgPIDs (for all files).
// When this object is deleted, it is removed from the table via the cleanup
// mechanism invoked by the TObject destructor.
//
// Each TProcessID has a table (TObjArray *fObjects) that keeps track
// of all referenced objects. If a referenced object has a fUniqueID set,
// a pointer to this unique object may be found via fObjects->At(fUniqueID).
// In the same way, when a TRef::GetObject is called, GetObject uses
// its own fUniqueID to find the pointer to the referenced object.
// See TProcessID::GetObjectWithID and PutObjectWithID.
//
// When a referenced object is deleted, its slot in fObjects is set to null.
//
// See also TProcessUUID: a specialized TProcessID to manage the single list
// of TUUIDs.
//
//////////////////////////////////////////////////////////////////////////

#include "TProcessID.h"
#include "TROOT.h"
#include "TObjArray.h"
#include "TExMap.h"
#include "TVirtualMutex.h"

TObjArray  *TProcessID::fgPIDs   = 0; //pointer to the list of TProcessID
TProcessID *TProcessID::fgPID    = 0; //pointer to the TProcessID of the current session
UInt_t      TProcessID::fgNumber = 0; //Current referenced object instance count
TExMap     *TProcessID::fgObjPIDs= 0; //Table (pointer,pids)
ClassImp(TProcessID)

//______________________________________________________________________________
static inline ULong_t Void_Hash(const void *ptr)
{
   // Return hash value for this object.

   return TString::Hash(&ptr, sizeof(void*));
}

//______________________________________________________________________________
TProcessID::TProcessID()
{
   // Default constructor.

   fCount = 0;
   fObjects = 0;
}

//______________________________________________________________________________
TProcessID::~TProcessID()
{
   // Destructor.

   delete fObjects;
   fObjects = 0;
   R__LOCKGUARD2(gROOTMutex);
   fgPIDs->Remove(this);
}

//______________________________________________________________________________
TProcessID *TProcessID::AddProcessID()
{
   // Static function to add a new TProcessID to the list of PIDs.

   R__LOCKGUARD2(gROOTMutex);

   TProcessID *pid = new TProcessID();

   if (!fgPIDs) {
      fgPID  = pid;
      fgPIDs = new TObjArray(10);
      gROOT->GetListOfCleanups()->Add(fgPIDs);
   }
   UShort_t apid = fgPIDs->GetEntriesFast();
   pid->IncrementCount();

   fgPIDs->Add(pid);
   char name[20];
   sprintf(name,"ProcessID%d",apid);
   pid->SetName(name);
   TUUID u;
   apid = fgPIDs->GetEntriesFast();
   pid->SetTitle(u.AsString());
   return pid;
}

//______________________________________________________________________________
UInt_t TProcessID::AssignID(TObject *obj)
{
   // static function returning the ID assigned to obj
   // If the object is not yet referenced, its kIsReferenced bit is set
   // and its fUniqueID set to the current number of referenced objects so far.

   R__LOCKGUARD2(gROOTMutex);

   UInt_t uid = obj->GetUniqueID() & 0xffffff;
   if (obj == fgPID->GetObjectWithID(uid)) return uid;
   if (obj->TestBit(kIsReferenced)) {
      fgPID->PutObjectWithID(obj,uid);
      return uid;
   }
   fgNumber++;
   obj->SetBit(kIsReferenced);
   uid = fgNumber;
   obj->SetUniqueID(uid);
   fgPID->PutObjectWithID(obj,uid);
   return uid;
}

//______________________________________________________________________________
void TProcessID::CheckInit()
{
   // Initialize fObjects.
   if (!fObjects) fObjects = new TObjArray(100);
}

//______________________________________________________________________________
void TProcessID::Cleanup()
{
   // static function (called by TROOT destructor) to delete all TProcessIDs

   R__LOCKGUARD2(gROOTMutex);

   fgPIDs->Delete();
   gROOT->GetListOfCleanups()->Remove(fgPIDs);
   delete fgPIDs;
}

//______________________________________________________________________________
void TProcessID::Clear(Option_t *)
{
   // delete the TObjArray pointing to referenced objects
   // this function is called by TFile::Close("R")

   delete fObjects; fObjects = 0;
}

//______________________________________________________________________________
Int_t TProcessID::DecrementCount()
{

   // the reference fCount is used to delete the TProcessID
   // in the TFile destructor when fCount = 0

   fCount--;
   if (fCount < 0) fCount = 0;
   return fCount;
}

//______________________________________________________________________________
TProcessID *TProcessID::GetProcessID(UShort_t pid)
{
   // static function returning a pointer to TProcessID number pid in fgPIDs

   return (TProcessID*)fgPIDs->At(pid);
}

//______________________________________________________________________________
UInt_t TProcessID::GetNProcessIDs()
{
   // Return the (static) number of process IDs.
   return fgPIDs ? fgPIDs->GetLast()+1 : 0;
}

//______________________________________________________________________________
TProcessID *TProcessID::GetProcessWithUID(UInt_t uid, const void *obj)
{
   // static function returning a pointer to TProcessID with its pid
   // encoded in the highest byte of uid

   R__LOCKGUARD2(gROOTMutex);

   Int_t pid = (uid>>24)&0xff;
   if (pid==0xff) {
      // Look up the pid in the table (pointer,pid)
      if (fgObjPIDs==0) return 0;
      ULong_t hash = Void_Hash(obj);
      pid = fgObjPIDs->GetValue(hash,(Long_t)obj);
   }
   return (TProcessID*)fgPIDs->At(pid);
}

//______________________________________________________________________________
TProcessID *TProcessID::GetProcessWithUID(const TObject *obj)
{
   // static function returning a pointer to TProcessID with its pid
   // encoded in the highest byte of obj->GetUniqueID()

   return GetProcessWithUID(obj->GetUniqueID(),obj);
}

//______________________________________________________________________________
TProcessID *TProcessID::GetSessionProcessID()
{
   // static function returning the pointer to the session TProcessID

   return fgPID;
}

//______________________________________________________________________________
Int_t TProcessID::IncrementCount()
{
   // Increase the reference count to this object.

   if (!fObjects) fObjects = new TObjArray(100);
   fCount++;
   return fCount;
}

//______________________________________________________________________________
UInt_t TProcessID::GetObjectCount()
{
   // Return the current referenced object count
   // fgNumber is incremented everytime a new object is referenced

   return fgNumber;
}

//______________________________________________________________________________
TObject *TProcessID::GetObjectWithID(UInt_t uidd)
{
   //returns the TObject with unique identifier uid in the table of objects

   Int_t uid = uidd & 0xffffff;  //take only the 24 lower bits

   if (fObjects==0 || uid >= fObjects->GetSize()) return 0;
   return fObjects->UncheckedAt(uid);
}

//______________________________________________________________________________
TProcessID *TProcessID::GetPID()
{
   //static: returns pointer to current TProcessID

   return fgPID;
}

//______________________________________________________________________________
TObjArray *TProcessID::GetPIDs()
{
   //static: returns array of TProcessIDs

   return fgPIDs;
}

//______________________________________________________________________________
Bool_t TProcessID::IsValid(TProcessID *pid)
{
   // static function. return kTRUE if pid is a valid TProcessID

   R__LOCKGUARD2(gROOTMutex);

   if (fgPIDs->IndexOf(pid) >= 0) return kTRUE;
   if (pid == (TProcessID*)gROOT->GetUUIDs())  return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
void TProcessID::PutObjectWithID(TObject *obj, UInt_t uid)
{
   //stores the object at the uid th slot in the table of objects
   //The object uniqueid is set as well as its kMustCleanup bit

   if (uid == 0) uid = obj->GetUniqueID() & 0xffffff;

   if (!fObjects) fObjects = new TObjArray(100);
   fObjects->AddAtAndExpand(obj,uid);

   obj->SetBit(kMustCleanup);
   if ( (obj->GetUniqueID()&0xff000000)==0xff000000 ) {
      // We have more than 255 pids we need to store this
      // pointer in the table(pointer,pid) since there is no
      // more space in fUniqueID
      if (fgObjPIDs==0) fgObjPIDs = new TExMap;
      ULong_t hash = Void_Hash(obj);

      // We use operator() rather than Add() because
      // if the address has already been registered, we want to
      // update it's uniqueID (this can easily happen when the
      // referenced object have been stored in a TClonesArray.
      (*fgObjPIDs)(hash, (Long_t)obj) = GetUniqueID();
   }
}

//______________________________________________________________________________
void TProcessID::RecursiveRemove(TObject *obj)
{
   // called by the object destructor
   // remove reference to obj from the current table if it is referenced

   if (!fObjects) return;
   if (!obj->TestBit(kIsReferenced)) return;
   UInt_t uid = obj->GetUniqueID() & 0xffffff;
   if (obj == GetObjectWithID(uid)) fObjects->RemoveAt(uid);
}

//______________________________________________________________________________
void TProcessID::SetObjectCount(UInt_t number)
{
   // static function to set the current referenced object count
   // fgNumber is incremented everytime a new object is referenced

   fgNumber = number;
}
<|endoftext|>


<commit_before>// @(#)root/base:$Id$
// Author: Fons Rademakers   11/10/95

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TStopwatch                                                           //
//                                                                      //
// Stopwatch class. This class returns the real and cpu time between    //
// the start and stop events.                                           //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TStopwatch.h"
#include "TTimeStamp.h"
#include "TString.h"

#if defined(R__UNIX)
#  include <sys/times.h>
#  include <unistd.h>
static Double_t gTicks = 0;
#elif defined(WIN32)
#  include "TError.h"
const Double_t gTicks = 1.0e-7;
#  include "Windows4Root.h"
#endif

ClassImp(TStopwatch)

//______________________________________________________________________________
TStopwatch::TStopwatch()
{
   // Create a stopwatch and start it.

#ifdef R__UNIX
   if (gTicks <= 0.0)
      gTicks = (Double_t)sysconf(_SC_CLK_TCK);
#endif

   fStopRealTime = 0;
   fStopCpuTime  = 0;

   Start();
}

//______________________________________________________________________________
void TStopwatch::Start(Bool_t reset)
{
   // Start the stopwatch. If reset is kTRUE reset the stopwatch before
   // starting it (including the stopwatch counter).
   // Use kFALSE to continue timing after a Stop() without
   // resetting the stopwatch.

   if (reset) {
      fState         = kUndefined;
      fTotalCpuTime  = 0;
      fTotalRealTime = 0;
      fCounter       = 0;
   }
   if (fState != kRunning) {
      fStartRealTime = GetRealTime();
      fStartCpuTime  = GetCPUTime();
   }
   fState = kRunning;
   fCounter++;
}

//______________________________________________________________________________
void TStopwatch::Stop()
{
   // Stop the stopwatch.

   fStopRealTime = GetRealTime();
   fStopCpuTime  = GetCPUTime();

   if (fState == kRunning) {
      fTotalCpuTime  += fStopCpuTime  - fStartCpuTime;
      fTotalRealTime += fStopRealTime - fStartRealTime;
   }
   fState = kStopped;
}

//______________________________________________________________________________
void TStopwatch::Continue()
{
   // Resume a stopped stopwatch. The stopwatch continues counting from the last
   // Start() onwards (this is like the laptimer function).

   if (fState == kUndefined)
      Error("Continue", "stopwatch not started");

   if (fState == kStopped) {
      fTotalCpuTime  -= fStopCpuTime  - fStartCpuTime;
      fTotalRealTime -= fStopRealTime - fStartRealTime;
   }

   fState = kRunning;
}

//______________________________________________________________________________
Double_t TStopwatch::RealTime()
{
   // Return the realtime passed between the start and stop events. If the
   // stopwatch was still running stop it first.

   if (fState == kUndefined)
      Error("RealTime", "stopwatch not started");

   if (fState == kRunning)
      Stop();

   return fTotalRealTime;
}

//______________________________________________________________________________
Double_t TStopwatch::CpuTime()
{
   // Return the cputime passed between the start and stop events. If the
   // stopwatch was still running stop it first.

   if (fState == kUndefined)
      Error("CpuTime", "stopwatch not started");

   if (fState == kRunning)
      Stop();

   return fTotalCpuTime;
}

//______________________________________________________________________________
Double_t TStopwatch::GetRealTime()
{
   // Private static method returning system realtime.

#if defined(R__UNIX)
   return TTimeStamp();
#elif defined(WIN32)
   union {
      FILETIME ftFileTime;
      __int64  ftInt64;
   } ftRealTime; // time the process has spent in kernel mode
   SYSTEMTIME st;
   GetSystemTime(&st);
   SystemTimeToFileTime(&st,&ftRealTime.ftFileTime);
   return (Double_t)ftRealTime.ftInt64 * gTicks;
#endif
}

//______________________________________________________________________________
Double_t TStopwatch::GetCPUTime()
{
   // Private static method returning system CPU time.

#if defined(R__UNIX)
   struct tms cpt;
   times(&cpt);
   return (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks;
#elif defined(WIN32)

   OSVERSIONINFO OsVersionInfo;

   //         Value                      Platform
   //----------------------------------------------------
   //  VER_PLATFORM_WIN32s          Win32s on Windows 3.1
   //  VER_PLATFORM_WIN32_WINDOWS   Win32 on Windows 95
   //  VER_PLATFORM_WIN32_NT        Windows NT
   //
   OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
   GetVersionEx(&OsVersionInfo);
   if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {
      DWORD       ret;
      FILETIME    ftCreate,       // when the process was created
                  ftExit;         // when the process exited

      union {
         FILETIME ftFileTime;
         __int64  ftInt64;
      } ftKernel; // time the process has spent in kernel mode

      union {
         FILETIME ftFileTime;
         __int64  ftInt64;
      } ftUser;   // time the process has spent in user mode

      HANDLE hThread = GetCurrentThread();
      ret = GetThreadTimes (hThread, &ftCreate, &ftExit,
                                     &ftKernel.ftFileTime,
                                     &ftUser.ftFileTime);
      if (ret != TRUE) {
         ret = GetLastError ();
         ::Error ("GetCPUTime", " Error on GetProcessTimes 0x%lx", (int)ret);
      }

      // Process times are returned in a 64-bit structure, as the number of
      // 100 nanosecond ticks since 1 January 1601.  User mode and kernel mode
      // times for this process are in separate 64-bit structures.
      // To convert to floating point seconds, we will:
      //
      // Convert sum of high 32-bit quantities to 64-bit int

      return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks;
   } else
      return GetRealTime();
#endif
}

//______________________________________________________________________________
void TStopwatch::Print(Option_t *opt) const
{
   // Print the real and cpu time passed between the start and stop events.
   // and the number of times (slices) this TStopwatch was called
   // (if this number > 1). If opt="m" print out realtime in milli second
   // precision. If opt="u" print out realtime in micro second precision.

   Double_t  realt = const_cast<TStopwatch*>(this)->RealTime();
   Double_t  cput  = const_cast<TStopwatch*>(this)->CpuTime();

   Int_t  hours = Int_t(realt / 3600);
   realt -= hours * 3600;
   Int_t  min   = Int_t(realt / 60);
   realt -= min * 60;
   Int_t  sec   = Int_t(realt);

   if (realt < 0) realt = 0;
   if (cput  < 0) cput  = 0;

   if (opt && *opt == 'm') {
      if (Counter() > 1) {
         Printf("Real time %d:%02d:%06.3f, CP time %.3f, %d slices", hours, min, realt, cput, Counter());
      } else {
         Printf("Real time %d:%02d:%06.3f, CP time %.3f", hours, min, realt, cput);
      }
   } else if (opt && *opt == 'u') {
      if (Counter() > 1) {
         Printf("Real time %d:%02d:%09.6f, CP time %.3f, %d slices", hours, min, realt, cput, Counter());
      } else {
         Printf("Real time %d:%02d:%09.6f, CP time %.3f", hours, min, realt, cput);
      }
   } else {
      if (Counter() > 1) {
         Printf("Real time %d:%02d:%02d, CP time %.3f, %d slices", hours, min, sec, cput, Counter());
      } else {
         Printf("Real time %d:%02d:%02d, CP time %.3f", hours, min, sec, cput);
      }
   }
}
<commit_msg>From Thiemo Nagel: correction in doc.<commit_after>// @(#)root/base:$Id$
// Author: Fons Rademakers   11/10/95

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TStopwatch                                                           //
//                                                                      //
// Stopwatch class. This class returns the real and cpu time between    //
// the start and stop events.                                           //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TStopwatch.h"
#include "TTimeStamp.h"
#include "TString.h"

#if defined(R__UNIX)
#  include <sys/times.h>
#  include <unistd.h>
static Double_t gTicks = 0;
#elif defined(WIN32)
#  include "TError.h"
const Double_t gTicks = 1.0e-7;
#  include "Windows4Root.h"
#endif

ClassImp(TStopwatch)

//______________________________________________________________________________
TStopwatch::TStopwatch()
{
   // Create a stopwatch and start it.

#ifdef R__UNIX
   if (gTicks <= 0.0)
      gTicks = (Double_t)sysconf(_SC_CLK_TCK);
#endif

   fStopRealTime = 0;
   fStopCpuTime  = 0;

   Start();
}

//______________________________________________________________________________
void TStopwatch::Start(Bool_t reset)
{
   // Start the stopwatch. If reset is kTRUE reset the stopwatch before
   // starting it (including the stopwatch counter).
   // Use kFALSE to continue timing after a Stop() without
   // resetting the stopwatch.

   if (reset) {
      fState         = kUndefined;
      fTotalCpuTime  = 0;
      fTotalRealTime = 0;
      fCounter       = 0;
   }
   if (fState != kRunning) {
      fStartRealTime = GetRealTime();
      fStartCpuTime  = GetCPUTime();
   }
   fState = kRunning;
   fCounter++;
}

//______________________________________________________________________________
void TStopwatch::Stop()
{
   // Stop the stopwatch.

   fStopRealTime = GetRealTime();
   fStopCpuTime  = GetCPUTime();

   if (fState == kRunning) {
      fTotalCpuTime  += fStopCpuTime  - fStartCpuTime;
      fTotalRealTime += fStopRealTime - fStartRealTime;
   }
   fState = kStopped;
}

//______________________________________________________________________________
void TStopwatch::Continue()
{
   // Resume a stopped stopwatch. The stopwatch continues counting from the last
   // Start() onwards (this is like the laptimer function).

   if (fState == kUndefined)
      Error("Continue", "stopwatch not started");

   if (fState == kStopped) {
      fTotalCpuTime  -= fStopCpuTime  - fStartCpuTime;
      fTotalRealTime -= fStopRealTime - fStartRealTime;
   }

   fState = kRunning;
}

//______________________________________________________________________________
Double_t TStopwatch::RealTime()
{
   // Stop the stopwatch (if it is running) and return the realtime (in
   // seconds) passed between the start and stop events.

   if (fState == kUndefined)
      Error("RealTime", "stopwatch not started");

   if (fState == kRunning)
      Stop();

   return fTotalRealTime;
}

//______________________________________________________________________________
Double_t TStopwatch::CpuTime()
{
   // Stop the stopwatch (if it is running) and return the cputime (in
   // seconds) passed between the start and stop events.

   if (fState == kUndefined)
      Error("CpuTime", "stopwatch not started");

   if (fState == kRunning)
      Stop();

   return fTotalCpuTime;
}

//______________________________________________________________________________
Double_t TStopwatch::GetRealTime()
{
   // Private static method returning system realtime.

#if defined(R__UNIX)
   return TTimeStamp();
#elif defined(WIN32)
   union {
      FILETIME ftFileTime;
      __int64  ftInt64;
   } ftRealTime; // time the process has spent in kernel mode
   SYSTEMTIME st;
   GetSystemTime(&st);
   SystemTimeToFileTime(&st,&ftRealTime.ftFileTime);
   return (Double_t)ftRealTime.ftInt64 * gTicks;
#endif
}

//______________________________________________________________________________
Double_t TStopwatch::GetCPUTime()
{
   // Private static method returning system CPU time.

#if defined(R__UNIX)
   struct tms cpt;
   times(&cpt);
   return (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks;
#elif defined(WIN32)

   OSVERSIONINFO OsVersionInfo;

   //         Value                      Platform
   //----------------------------------------------------
   //  VER_PLATFORM_WIN32s          Win32s on Windows 3.1
   //  VER_PLATFORM_WIN32_WINDOWS   Win32 on Windows 95
   //  VER_PLATFORM_WIN32_NT        Windows NT
   //
   OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
   GetVersionEx(&OsVersionInfo);
   if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {
      DWORD       ret;
      FILETIME    ftCreate,       // when the process was created
                  ftExit;         // when the process exited

      union {
         FILETIME ftFileTime;
         __int64  ftInt64;
      } ftKernel; // time the process has spent in kernel mode

      union {
         FILETIME ftFileTime;
         __int64  ftInt64;
      } ftUser;   // time the process has spent in user mode

      HANDLE hThread = GetCurrentThread();
      ret = GetThreadTimes (hThread, &ftCreate, &ftExit,
                                     &ftKernel.ftFileTime,
                                     &ftUser.ftFileTime);
      if (ret != TRUE) {
         ret = GetLastError ();
         ::Error ("GetCPUTime", " Error on GetProcessTimes 0x%lx", (int)ret);
      }

      // Process times are returned in a 64-bit structure, as the number of
      // 100 nanosecond ticks since 1 January 1601.  User mode and kernel mode
      // times for this process are in separate 64-bit structures.
      // To convert to floating point seconds, we will:
      //
      // Convert sum of high 32-bit quantities to 64-bit int

      return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks;
   } else
      return GetRealTime();
#endif
}

//______________________________________________________________________________
void TStopwatch::Print(Option_t *opt) const
{
   // Print the real and cpu time passed between the start and stop events.
   // and the number of times (slices) this TStopwatch was called
   // (if this number > 1). If opt="m" print out realtime in milli second
   // precision. If opt="u" print out realtime in micro second precision.

   Double_t  realt = const_cast<TStopwatch*>(this)->RealTime();
   Double_t  cput  = const_cast<TStopwatch*>(this)->CpuTime();

   Int_t  hours = Int_t(realt / 3600);
   realt -= hours * 3600;
   Int_t  min   = Int_t(realt / 60);
   realt -= min * 60;
   Int_t  sec   = Int_t(realt);

   if (realt < 0) realt = 0;
   if (cput  < 0) cput  = 0;

   if (opt && *opt == 'm') {
      if (Counter() > 1) {
         Printf("Real time %d:%02d:%06.3f, CP time %.3f, %d slices", hours, min, realt, cput, Counter());
      } else {
         Printf("Real time %d:%02d:%06.3f, CP time %.3f", hours, min, realt, cput);
      }
   } else if (opt && *opt == 'u') {
      if (Counter() > 1) {
         Printf("Real time %d:%02d:%09.6f, CP time %.3f, %d slices", hours, min, realt, cput, Counter());
      } else {
         Printf("Real time %d:%02d:%09.6f, CP time %.3f", hours, min, realt, cput);
      }
   } else {
      if (Counter() > 1) {
         Printf("Real time %d:%02d:%02d, CP time %.3f, %d slices", hours, min, sec, cput, Counter());
      } else {
         Printf("Real time %d:%02d:%02d, CP time %.3f", hours, min, sec, cput);
      }
   }
}
<|endoftext|>


<commit_before>/// \file TLogger.cxx
/// \ingroup Base ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2015-07-07
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "ROOT/TLogger.hxx"
#include <iostream>

// pin vtable
ROOT::Experimental::TLogHandler::~TLogHandler() {}

namespace {
class TLogHandlerDefault: public ROOT::Experimental::TLogHandler {
public:
   // Returns false if further emission of this log entry should be suppressed.
   bool Emit(const ROOT::Experimental::TLogEntry &entry) override;
};

bool TLogHandlerDefault::Emit(const ROOT::Experimental::TLogEntry &entry)
{
   constexpr static std::array<const char *, 5> sTag{{"Debug", "Info", "Warning", "Log", "FATAL"}};
   std::cerr << "ROOT ";
   if (!entry.fGroup.empty())
      std::cerr << '[' << entry.fGroup << "] ";
   std::cerr << sTag[static_cast<int>(entry.fLevel)];

   if (!entry.fFile.empty())
      std::cerr << " " << entry.fFile << ':' << entry.fLine;
   if (!entry.fFuncName.empty())
      std::cerr << " in " << entry.fFuncName;
   std::cerr << ":\n"
             << "   " << entry.str();
   return true;
}
} // unnamed namespace

ROOT::Experimental::TLogManager &ROOT::Experimental::TLogManager::Get()
{
   static TLogManager instance(std::make_unique<TLogHandlerDefault>());
   return instance;
}
<commit_msg>Always add a trailing newline to the message.<commit_after>/// \file TLogger.cxx
/// \ingroup Base ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2015-07-07
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "ROOT/TLogger.hxx"
#include <iostream>

// pin vtable
ROOT::Experimental::TLogHandler::~TLogHandler() {}

namespace {
class TLogHandlerDefault: public ROOT::Experimental::TLogHandler {
public:
   // Returns false if further emission of this log entry should be suppressed.
   bool Emit(const ROOT::Experimental::TLogEntry &entry) override;
};

bool TLogHandlerDefault::Emit(const ROOT::Experimental::TLogEntry &entry)
{
   constexpr static std::array<const char *, 5> sTag{{"Debug", "Info", "Warning", "Log", "FATAL"}};
   std::cerr << "ROOT ";
   if (!entry.fGroup.empty())
      std::cerr << '[' << entry.fGroup << "] ";
   std::cerr << sTag[static_cast<int>(entry.fLevel)];

   if (!entry.fFile.empty())
      std::cerr << " " << entry.fFile << ':' << entry.fLine;
   if (!entry.fFuncName.empty())
      std::cerr << " in " << entry.fFuncName;
   std::cerr << ":\n"
             << "   " << entry.str() << '\n';
   return true;
}
} // unnamed namespace

ROOT::Experimental::TLogManager &ROOT::Experimental::TLogManager::Get()
{
   static TLogManager instance(std::make_unique<TLogHandlerDefault>());
   return instance;
}
<|endoftext|>