<commit_before>
#include "ImageServer.h"
#include <iostream>
#include <stdexcept>
#include <string>
#include <fstream>
#include <assert.h>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
// #include <boost/thread/thread.hpp>
#include <thread>

#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)

// example of a namespace alias
namespace FS = LMFocusStack;
namespace bfs = boost::filesystem;

using FS::ImageServer;

FS::ImageServer::ImageServer(int argc, char ** argv) {

	if (argc < 2)
	{ // settings file not specified, use default
		this->settings_path_ = def_settings_;
	}
	else { // load settings or display help
		settings_path_ = argv[1];
	}
	load_settings(); // could throw invalid settings exception
}

void FS::ImageServer::start_server() {
	std::cout << "Starting server at " << port_
			<< " ..." << std::endl;
	using boost::asio::ip::tcp;

	boost::asio::io_service io_service;

	server_(io_service, port_);

	// io_service.run might not be needed for blocking sever
	//io_service.run();

}

void FS::ImageServer::load_settings() {
	std::ifstream fin;
	#include STR(L10N_LANG)
	try {
		const int BUF_LEN = 4096*2;
		char buffer[BUF_LEN];
		// check if file exists and is a regular file
		// if file doesn't exist create a default file
		bfs::path p (this->settings_path_);
		if ( !bfs::exists(p) )
			create_default_settings ();
		if ( bfs::is_directory(p) )
			throw std::invalid_argument (
				rstr_dirNotFile + settings_path_ );

		fin.open(this->settings_path_);
		if (!fin.good())
			throw std::invalid_argument
				("Cannot access settings file: "
					+ settings_path_);

		// read one line at a time
		while (fin.good()) {
			fin.getline(buffer, BUF_LEN);
			load_settings_line(buffer, BUF_LEN);
		}

	} catch (...) {
		fin.close();
		// destruction of fin should also ensure clousure
		// but just making sure
		throw; // clean-up and re-throw
	}
}

void FS::ImageServer::load_settings_line(const char * buf, const int N) {
	assert( N > 0 );
	//std::cout << "Reading line: " << buf << std::endl;
	const boost::regex re_comment("^[[:space:]]*;");
	const boost::regex re_dbpath (
		"^([[:space:]]*database[[:space:]]=[[:space:]]*)");
	const boost::regex re_port (
		"^([[:space:]]*port[[:space:]]=[[:space:]]*)");
	boost::smatch str_matches;
	if ( boost::regex_search(std::string(buf),
				str_matches, re_comment) ) {
		//std::cout << "Comment found\n";
		return;
	}
	if ( boost::regex_search(std::string(buf),
				str_matches, re_dbpath) ) {
		//std::cout << "Comment found\n";
		db_path_ = buf + str_matches[0].length();
		std::cout << "Setting database path to: "
			  << db_path_ << std::endl;
		return;
	}
	if (boost::regex_search(std::string(buf),
				str_matches, re_port) ) {
	  port_ = std::atoi(buf + str_matches[0].length());
	  return;
	}
}

void FS::ImageServer::create_default_settings() {
	using namespace boost::posix_time;
	using namespace boost::gregorian;

	ptime now = second_clock::local_time();

	std::ofstream fout(settings_path_, std::ofstream::out);

	fout << "; Focus Stacking Image Server settings file V 1.0\n"
		"; Automatically created by " << program_version << "\n"
		"; " << to_simple_string(now) << std::endl <<
		"database = FSImSrvDb\n"
	  "port = 8080\n";

	fout.close();
}

std::map<std::thread::id, FS::ImageServer::state_t> *
	FS::ImageServer::state_map_
	= new std::map<std::thread::id, FS::ImageServer::state_t>();

using boost::asio::ip::tcp;
// Using for echo example
/*void FS::ImageServer::session_(tcp::socket sock)
{
  const std::thread::id tid = std::this_thread::get_id();
  state_t state = waiting_for_start;
  state_map_->insert(std::pair<std::thread::id, state_t>(tid,state));
  for(;;)
    {
      char data[max_msg_len];

      boost::system::error_code error;
      size_t length = sock.read_some(boost::asio::buffer(data), error);
      std::cout << "Read " << length << " bytes from client" << std::endl;
      if (error == boost::asio::error::eof)
	break; // Connection closed cleanly by peer.
      else if (error)

	throw boost::system::system_error(error); // Some other error.

	boost::asio::write(sock, boost::asio::buffer(data, length));
    }

}
*/

FS::ImageServer::state_t FS::ImageServer::get_state_()
{
  const std::thread::id tid = std::this_thread::get_id();
  return (*state_map_)[tid];
}

void FS::ImageServer::set_state_(state_t st)
{
  const std::thread::id tid = std::this_thread::get_id();
  (*state_map_)[tid] = st;
}

void FS::ImageServer::parse_frame_id_(char * data, FrameReadState * rs)
{
  uint i;
  for (i = 0; i < rs->length; i++) {
    rs->header[rs->header_pos] = data[i];
    rs->header_pos++;
    if (rs->header_pos == HEADER_LEN) {
      set_state_(reading_data);
      i++;
      break;
    }
  }
  rs->data_index += i;
}

using namespace std;
int FS::ImageServer::read_settings_()
{
  cout << "Start of read_settings_" << endl;
  string line;
  // Currently unable to open settings file
  ifstream settingsfile (settings_path_);

  cout << settingsfile << endl;

  return 0;
}

using namespace boost::filesystem;
void FS::ImageServer::process_db_()
/* According to DatabaseFormat.md, we need to:
 * 1) read the settings file (.ini),
 * 2) create or update a meta-information file describing the data
 * 3) create or update a UUID file containing the db unique ID
 * 4) create or update a folder for each stack in the db
 * 5) Ensure that the stack's folder equals the stack's UUID
 */
{
  std::cout << "process_db_ method called" << std::endl;
  std::cout << "Settings file exists: " << settings_path_ << std::endl;

  // If a settings_path isn't given then use the /tmp/ directory
  // Assuming linux environment.
  current_path("/tmp/");
  std::cout << "Working directory: " << current_path() << std::endl;

  if (exists(current_path()))
    {
      if (is_directory("FSImSrvDb"))
	{
	  std::cout << "Yes FSImSrvDb is a directory in /tmp/" <<
	    std:: endl <<
	    "File size in folder: " << file_size("FSImSrvDb/uuid")
	    << std::endl;
	  //create_directory("FSImSrvDb/testing");
	  //std::cout << "New directory created: " <<
	  //  is_directory("FSImSrvDb/testing") << std::endl;

	}
      else std::cout << "No FSImSrvDb is not a directory";
    }

}

std::string FS::ImageServer::settings_path_ =
	       "/home/tbonza/projects/FocusStacking/src/ImageServer/FStk.ini";

void FS::ImageServer::process_ping_(tcp::socket& sock)
{
  const char * data = //"\002PONG PING\003";
        "\002PING FocusStacking ImageServer version 0.1 \n"
    "Database: 123e4567e89b12d3a452426655440000\003";
  size_t length = std::strlen(data);
  boost::asio::write(sock, boost::asio::buffer(data, length));
  // reset the state to process the next input
  set_state_(waiting_for_start);
}

void FS::ImageServer::create_new_stack_(tcp::socket& sock)
{

  //const
  const char * data = //"\002PONG PING\003";
        "\002PING FocusStacking ImageServer version 0.1 \n"
    "Database: 123e4567e89b12d3a452426655440000\003";
  size_t length = std::strlen(data);
  boost::asio::write(sock, boost::asio::buffer(data, length));
  // reset the state to process the next input
  set_state_(waiting_for_start);
}

void FS::ImageServer::db_logic_(boost::asio::ip::tcp::socket& sock,
				FrameReadState * rs)
{
  std::string sHead;
  for(size_t i = 0; i < HEADER_LEN; i++) sHead += rs->header[i];
  if (sHead == "PING")
    process_ping_(sock);
  else if (sHead == "GTID")
    create_new_stack_(sock);
}

// Using for not echo example
void FS::ImageServer::session_(tcp::socket sock)
{
  try {
  // get id for the current thread
  const std::thread::id tid = std::this_thread::get_id();
  // when a new connection starts, it's waiting for the start of packet
  state_t state = waiting_for_start;
  state_map_->insert(std::pair<std::thread::id, state_t>(tid,state));
  // read bytes until EOF
  for(;;)
    {
      char data[max_msg_len];
      FrameReadState read_state;

      boost::system::error_code error;
      read_state.length = sock.read_some(
			     boost::asio::buffer(data, max_msg_len),
			     error);
      std::cout << "Read " << read_state.length <<
	" bytes from client" << std::endl;

      // testing process_db_() and read_settings_(),
      // not being called anywhere else.
      std::cout << "Processing ping, testing database" << std::endl;
      process_db_();
      read_settings_();

      if (error == boost::asio::error::eof)
	break; // Connection closed cleanly by peer.
      else if (error)
	throw boost::system::system_error(error); // Some other error.

      while (read_state.data_index != read_state.length) {

	switch(get_state_())
	  {
	  case waiting_for_start:
	    detect_start_msg_(data, &read_state);
	    break;
	  case reading_header:
	    parse_frame_id_(data, &read_state);
	    break;
	  case reading_data:
	    db_logic_(sock, &read_state);
	    break;
	  }

      }
      //boost::asio::write(sock, boost::asio::buffer(data, length));

    }
  }
  catch(std::exception& e)
    {
      std::cerr << "Exception: " << e.what() << std::endl;
    }

}

void FS::ImageServer::server_(boost::asio::io_service& io_service,
			      unsigned short port)
{
  tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
  for (;;)
  {
    //try {
      tcp::socket sock(io_service);
      a.accept(sock);
      // starting a new thread here
      std::thread(session_, std::move(sock)).detach();
      //} catch()
  }
}

void FS::ImageServer::detect_start_msg_(char * data, FrameReadState *rs)
{
  uint i;
  for (i = 0; i < rs->length; i++) {
    if (data[i] == '\002') {
      set_state_(reading_header);
      rs->header_pos = 0;
      i++;
      break;
    }
  }
  rs->data_index += i;
}

<commit_msg>successfully parsed ini file<commit_after>
#include "ImageServer.h"
#include <iostream>
#include <stdexcept>
#include <string>
#include <fstream>
#include <assert.h>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
//#include <boost/property_tree/json_parser.hpp>
// #include <boost/thread/thread.hpp>
#include <thread>

#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)

// example of a namespace alias
namespace FS = LMFocusStack;
namespace bfs = boost::filesystem;

using FS::ImageServer;

FS::ImageServer::ImageServer(int argc, char ** argv) {

	if (argc < 2)
	{ // settings file not specified, use default
		this->settings_path_ = def_settings_;
	}
	else { // load settings or display help
		settings_path_ = argv[1];
	}
	load_settings(); // could throw invalid settings exception
}

void FS::ImageServer::start_server() {
	std::cout << "Starting server at " << port_
			<< " ..." << std::endl;
	using boost::asio::ip::tcp;

	boost::asio::io_service io_service;

	server_(io_service, port_);

	// io_service.run might not be needed for blocking sever
	//io_service.run();

}

void FS::ImageServer::load_settings() {
	std::ifstream fin;
	#include STR(L10N_LANG)
	try {
		const int BUF_LEN = 4096*2;
		char buffer[BUF_LEN];
		// check if file exists and is a regular file
		// if file doesn't exist create a default file
		bfs::path p (this->settings_path_);
		if ( !bfs::exists(p) )
			create_default_settings ();
		if ( bfs::is_directory(p) )
			throw std::invalid_argument (
				rstr_dirNotFile + settings_path_ );

		fin.open(this->settings_path_);
		if (!fin.good())
			throw std::invalid_argument
				("Cannot access settings file: "
					+ settings_path_);

		// read one line at a time
		while (fin.good()) {
			fin.getline(buffer, BUF_LEN);
			load_settings_line(buffer, BUF_LEN);
		}

	} catch (...) {
		fin.close();
		// destruction of fin should also ensure clousure
		// but just making sure
		throw; // clean-up and re-throw
	}
}

void FS::ImageServer::load_settings_line(const char * buf, const int N) {
	assert( N > 0 );
	//std::cout << "Reading line: " << buf << std::endl;
	const boost::regex re_comment("^[[:space:]]*;");
	const boost::regex re_dbpath (
		"^([[:space:]]*database[[:space:]]=[[:space:]]*)");
	const boost::regex re_port (
		"^([[:space:]]*port[[:space:]]=[[:space:]]*)");
	boost::smatch str_matches;
	if ( boost::regex_search(std::string(buf),
				str_matches, re_comment) ) {
		//std::cout << "Comment found\n";
		return;
	}
	if ( boost::regex_search(std::string(buf),
				str_matches, re_dbpath) ) {
		//std::cout << "Comment found\n";
		db_path_ = buf + str_matches[0].length();
		std::cout << "Setting database path to: "
			  << db_path_ << std::endl;
		return;
	}
	if (boost::regex_search(std::string(buf),
				str_matches, re_port) ) {
	  port_ = std::atoi(buf + str_matches[0].length());
	  return;
	}
}

void FS::ImageServer::create_default_settings() {
	using namespace boost::posix_time;
	using namespace boost::gregorian;

	ptime now = second_clock::local_time();

	std::ofstream fout(settings_path_, std::ofstream::out);

	fout << "; Focus Stacking Image Server settings file V 1.0\n"
		"; Automatically created by " << program_version << "\n"
		"; " << to_simple_string(now) << std::endl <<
		"database = FSImSrvDb\n"
	  "port = 8080\n";

	std::cout << "create_default_settings() called" << std::endl <<
	  "settings file created: " << settings_path_ << std::endl;

	fout.close();
}

std::map<std::thread::id, FS::ImageServer::state_t> *
	FS::ImageServer::state_map_
	= new std::map<std::thread::id, FS::ImageServer::state_t>();

using boost::asio::ip::tcp;
// Using for echo example
/*void FS::ImageServer::session_(tcp::socket sock)
{
  const std::thread::id tid = std::this_thread::get_id();
  state_t state = waiting_for_start;
  state_map_->insert(std::pair<std::thread::id, state_t>(tid,state));
  for(;;)
    {
      char data[max_msg_len];

      boost::system::error_code error;
      size_t length = sock.read_some(boost::asio::buffer(data), error);
      std::cout << "Read " << length << " bytes from client" << std::endl;
      if (error == boost::asio::error::eof)
	break; // Connection closed cleanly by peer.
      else if (error)

	throw boost::system::system_error(error); // Some other error.

	boost::asio::write(sock, boost::asio::buffer(data, length));
    }

}
*/

FS::ImageServer::state_t FS::ImageServer::get_state_()
{
  const std::thread::id tid = std::this_thread::get_id();
  return (*state_map_)[tid];
}

void FS::ImageServer::set_state_(state_t st)
{
  const std::thread::id tid = std::this_thread::get_id();
  (*state_map_)[tid] = st;
}

void FS::ImageServer::parse_frame_id_(char * data, FrameReadState * rs)
{
  uint i;
  for (i = 0; i < rs->length; i++) {
    rs->header[rs->header_pos] = data[i];
    rs->header_pos++;
    if (rs->header_pos == HEADER_LEN) {
      set_state_(reading_data);
      i++;
      break;
    }
  }
  rs->data_index += i;
}

using namespace boost::property_tree;
int FS::ImageServer::read_settings_()
{
  std::cout << "Start of read_settings_" << std::endl;

  try {
    ptree pt;
    ini_parser::read_ini("/home/tbonza/projects/FocusStacking/src/ImageServer/FStk.ini", pt);
    //ini_parser::read_ini(settings_path_, pt);
    //json_parser::read_json("/home/tbonza/projects/FocusStacking/src/ImageServer/FStk.json", pt);
    std::cout << pt.get<std::string>
      ("Network.working_directory") <<std::endl;
    std::cout << pt.get<std::string>
      ("Network.database") << std::endl;
    std::cout << pt.get<std::string>
      ("Network.port") << std::endl;

  }
  catch(...){
    std::cout << "Could not read: " << settings_path_ << std::endl;
  }

  return 0;
}

using namespace boost::filesystem;
void FS::ImageServer::process_db_()
/* According to DatabaseFormat.md, we need to:
 * 1) read the settings file (.ini),
 * 2) create or update a meta-information file describing the data
 * 3) create or update a UUID file containing the db unique ID
 * 4) create or update a folder for each stack in the db
 * 5) Ensure that the stack's folder equals the stack's UUID
 */
{
  std::cout << "process_db_ method called" << std::endl;
  std::cout << "Settings file exists: " << settings_path_ << std::endl;

  // If a settings_path isn't given then use the /tmp/ directory
  // Assuming linux environment.
  current_path("/tmp/");
  std::cout << "Working directory: " << current_path() << std::endl;

  if (exists(current_path()))
    {
      if (is_directory("FSImSrvDb"))
	{
	  std::cout << "Yes FSImSrvDb is a directory in /tmp/" <<
	    std:: endl <<
	    "File size in folder: " << file_size("FSImSrvDb/uuid")
	    << std::endl;
	  //create_directory("FSImSrvDb/testing");
	  //std::cout << "New directory created: " <<
	  //  is_directory("FSImSrvDb/testing") << std::endl;

	}
      else std::cout << "No FSImSrvDb is not a directory" << std::endl;
    }

}

std::string FS::ImageServer::settings_path_ =
	       "/home/tbonza/projects/FocusStacking/src/ImageServer/FStk.ini";
// Referencing: https://code.google.com/p/minini/wiki/INI_File_Syntax

void FS::ImageServer::process_ping_(tcp::socket& sock)
{
  const char * data = //"\002PONG PING\003";
        "\002PING FocusStacking ImageServer version 0.1 \n"
    "Database: 123e4567e89b12d3a452426655440000\003";
  size_t length = std::strlen(data);
  boost::asio::write(sock, boost::asio::buffer(data, length));
  // reset the state to process the next input
  set_state_(waiting_for_start);
}

void FS::ImageServer::create_new_stack_(tcp::socket& sock)
{

  //const
  const char * data = //"\002PONG PING\003";
        "\002PING FocusStacking ImageServer version 0.1 \n"
    "Database: 123e4567e89b12d3a452426655440000\003";
  size_t length = std::strlen(data);
  boost::asio::write(sock, boost::asio::buffer(data, length));
  // reset the state to process the next input
  set_state_(waiting_for_start);
}

void FS::ImageServer::db_logic_(boost::asio::ip::tcp::socket& sock,
				FrameReadState * rs)
{
  std::string sHead;
  for(size_t i = 0; i < HEADER_LEN; i++) sHead += rs->header[i];
  if (sHead == "PING")
    process_ping_(sock);
  else if (sHead == "GTID")
    create_new_stack_(sock);
}

// Using for not echo example
void FS::ImageServer::session_(tcp::socket sock)
{
  try {
  // get id for the current thread
  const std::thread::id tid = std::this_thread::get_id();
  // when a new connection starts, it's waiting for the start of packet
  state_t state = waiting_for_start;
  state_map_->insert(std::pair<std::thread::id, state_t>(tid,state));
  // read bytes until EOF
  for(;;)
    {
      char data[max_msg_len];
      FrameReadState read_state;

      boost::system::error_code error;
      read_state.length = sock.read_some(
			     boost::asio::buffer(data, max_msg_len),
			     error);
      std::cout << "Read " << read_state.length <<
	" bytes from client" << std::endl;

      // testing process_db_() and read_settings_(),
      // not being called anywhere else.
      std::cout << "Processing ping, testing database" << std::endl;
      process_db_();
      read_settings_();

      if (error == boost::asio::error::eof)
	break; // Connection closed cleanly by peer.
      else if (error)
	throw boost::system::system_error(error); // Some other error.

      while (read_state.data_index != read_state.length) {

	switch(get_state_())
	  {
	  case waiting_for_start:
	    detect_start_msg_(data, &read_state);
	    break;
	  case reading_header:
	    parse_frame_id_(data, &read_state);
	    break;
	  case reading_data:
	    db_logic_(sock, &read_state);
	    break;
	  }

      }
      //boost::asio::write(sock, boost::asio::buffer(data, length));

    }
  }
  catch(std::exception& e)
    {
      std::cerr << "Exception: " << e.what() << std::endl;
    }

}

void FS::ImageServer::server_(boost::asio::io_service& io_service,
			      unsigned short port)
{
  tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
  for (;;)
  {
    //try {
      tcp::socket sock(io_service);
      a.accept(sock);
      // starting a new thread here
      std::thread(session_, std::move(sock)).detach();
      //} catch()
  }
}

void FS::ImageServer::detect_start_msg_(char * data, FrameReadState *rs)
{
  uint i;
  for (i = 0; i < rs->length; i++) {
    if (data[i] == '\002') {
      set_state_(reading_header);
      rs->header_pos = 0;
      i++;
      break;
    }
  }
  rs->data_index += i;
}

<|endoftext|>


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

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// class for T0 calibration                       TM-AC-AM_6-02-2006
// equalize time shift for each time CFD channel
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include "AliT0CalibTimeEq.h"
#include "AliLog.h"
#include <TFile.h>
#include <TMath.h>
#include <TF1.h>
#include <TSpectrum.h>
#include <TProfile.h>
#include <iostream>

ClassImp(AliT0CalibTimeEq)

//________________________________________________________________
  AliT0CalibTimeEq::AliT0CalibTimeEq():TNamed(),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
  //

}

//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const char* name):TNamed(),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
  //constructor

  TString namst = "Calib_";
  namst += name;
  SetName(namst.Data());
  SetTitle(namst.Data());
}

//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const AliT0CalibTimeEq& calibda):TNamed(calibda),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
// copy constructor
  SetName(calibda.GetName());
  SetTitle(calibda.GetName());

}

//________________________________________________________________
AliT0CalibTimeEq &AliT0CalibTimeEq::operator =(const AliT0CalibTimeEq& calibda)
{
// assignment operator
  SetName(calibda.GetName());
  SetTitle(calibda.GetName());

  return *this;
}

//________________________________________________________________
AliT0CalibTimeEq::~AliT0CalibTimeEq()
{
  //
  // destrictor
}
//________________________________________________________________
void AliT0CalibTimeEq::Reset()
{
  //reset values

  memset(fCFDvalue,0,120*sizeof(Float_t));
  memset(fTimeEq,1,24*sizeof(Float_t));
}

//________________________________________________________________
void  AliT0CalibTimeEq::Print(Option_t*) const
{
  // print time values

  printf("\n	----	PM Arrays	----\n\n");
  printf(" Time delay CFD \n");
  for (Int_t i=0; i<24; i++) printf(" CFD  %f ",fTimeEq[i]);
  printf("\n Mean Vertex %f \n", fMeanVertex);
}

//________________________________________________________________
Bool_t AliT0CalibTimeEq::ComputeOnlineParams(const char* filePhys)
{
  // compute online equalized time
  Double_t mean=0, meanver=0;
  Double_t rms=0, rmsver=0;
  Int_t nent=0;
  Bool_t ok=false;
  gFile = TFile::Open(filePhys);
    if(!gFile) {
    AliError("No input PHYS data found ");
  }
  else
    {
      ok=true;
      Char_t buf1[30];
      for (Int_t i=0; i<24; i++)
	{
	  sprintf(buf1,"CFD1-CFD%d",i+1);
	  TH1F *cfd = (TH1F*) gFile->Get(buf1);
	  if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
	  //      printf(" i = %d buf1 = %s\n", i, buf1);
	  if(cfd) {
	    mean=cfd->GetMean();
	    rms=cfd->GetRMS();
	    nent=cfd->GetEntries();
	    //	    printf ("%f %f %i \n",mean,rms,nent);
	    if(nent<200 || rms>10 ) ok=false;
	  }
	   SetTimeEq(i,mean);
	   SetTimeEqRms(i,rms);
	  if (cfd) delete cfd;
	}
      TH1F *ver = (TH1F*) gFile->Get("hVertex");
      if(!ver) AliWarning("no Vertex histograms collected by PHYS DA for Zvertex");
      if(ver) {
	meanver = ver->GetMean();
	rmsver = ver->GetRMS();
      }
      SetMeanVertex(meanver);
      SetRmsVertex(rmsver);

      gFile->Close();
      delete gFile;

    }
    return ok;
}

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

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// class for T0 calibration                       TM-AC-AM_6-02-2006
// equalize time shift for each time CFD channel
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include "AliT0CalibTimeEq.h"
#include "AliLog.h"
#include <TFile.h>
#include <TMath.h>
#include <TF1.h>
#include <TSpectrum.h>
#include <TProfile.h>
#include <iostream>

ClassImp(AliT0CalibTimeEq)

//________________________________________________________________
  AliT0CalibTimeEq::AliT0CalibTimeEq():TNamed(),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
  //

}

//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const char* name):TNamed(),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
  //constructor

  TString namst = "Calib_";
  namst += name;
  SetName(namst.Data());
  SetTitle(namst.Data());
}

//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const AliT0CalibTimeEq& calibda):TNamed(calibda),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
// copy constructor
  SetName(calibda.GetName());
  SetTitle(calibda.GetName());

}

//________________________________________________________________
AliT0CalibTimeEq &AliT0CalibTimeEq::operator =(const AliT0CalibTimeEq& calibda)
{
// assignment operator
  SetName(calibda.GetName());
  SetTitle(calibda.GetName());

  return *this;
}

//________________________________________________________________
AliT0CalibTimeEq::~AliT0CalibTimeEq()
{
  //
  // destrictor
}
//________________________________________________________________
void AliT0CalibTimeEq::Reset()
{
  //reset values

  memset(fCFDvalue,0,120*sizeof(Float_t));
  memset(fTimeEq,1,24*sizeof(Float_t));
}

//________________________________________________________________
void  AliT0CalibTimeEq::Print(Option_t*) const
{
  // print time values

  printf("\n	----	PM Arrays	----\n\n");
  printf(" Time delay CFD \n");
  for (Int_t i=0; i<24; i++) printf(" CFD  %f ",fTimeEq[i]);
  printf("\n Mean Vertex %f \n", fMeanVertex);
}

//________________________________________________________________
Bool_t AliT0CalibTimeEq::ComputeOnlineParams(const char* filePhys)
{
  // compute online equalized time
  Double_t mean=0, meanver=0;
  Double_t rms=0, rmsver=0;
  Int_t nent=0;
  Bool_t ok=false;
  gFile = TFile::Open(filePhys);
    if(!gFile) {
    AliError("No input PHYS data found ");
  }
  else
    {
      ok=true;
      Char_t buf1[30];
      for (Int_t i=0; i<24; i++)
	{
	  sprintf(buf1,"CFD1-CFD%d",i+1);
	  TH1F *cfd = (TH1F*) gFile->Get(buf1);
	  if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
	  //      printf(" i = %d buf1 = %s\n", i, buf1);
	  if(cfd) {
	    mean=cfd->GetMean();
	    rms=cfd->GetRMS();
	    nent=cfd->GetEntries();
	    //	    printf ("%f %f %i \n",mean,rms,nent);
	    if(nent<500 || rms>5 ) ok=false;
	  }
	   SetTimeEq(i,mean);
	   SetTimeEqRms(i,rms);
	  if (cfd) delete cfd;
	}
      TH1F *ver = (TH1F*) gFile->Get("hVertex");
      if(!ver) AliWarning("no Vertex histograms collected by PHYS DA for Zvertex");
      if(ver) {
	meanver = ver->GetMean();
	rmsver = ver->GetRMS();
      }
      SetMeanVertex(meanver);
      SetRmsVertex(rmsver);

      gFile->Close();
      delete gFile;

    }
    return ok;
}

<|endoftext|>


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

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// class for T0 calibration                       TM-AC-AM_6-02-2006
// equalize time shift for each time CFD channel
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include "AliT0CalibTimeEq.h"
#include "AliLog.h"
#include <TFile.h>
#include <TMath.h>
#include <TF1.h>
#include <TSpectrum.h>
#include <TProfile.h>
#include <iostream>

ClassImp(AliT0CalibTimeEq)

//________________________________________________________________
  AliT0CalibTimeEq::AliT0CalibTimeEq():TNamed(),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
  //

}

//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const char* name):TNamed(),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
  //constructor

  TString namst = "Calib_";
  namst += name;
  SetName(namst.Data());
  SetTitle(namst.Data());
}

//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const AliT0CalibTimeEq& calibda):TNamed(calibda),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
// copy constructor
  SetName(calibda.GetName());
  SetTitle(calibda.GetName());

}

//________________________________________________________________
AliT0CalibTimeEq &AliT0CalibTimeEq::operator =(const AliT0CalibTimeEq& calibda)
{
// assignment operator
  SetName(calibda.GetName());
  SetTitle(calibda.GetName());

  return *this;
}

//________________________________________________________________
AliT0CalibTimeEq::~AliT0CalibTimeEq()
{
  //
  // destrictor
}
//________________________________________________________________
void AliT0CalibTimeEq::Reset()
{
  //reset values

  memset(fCFDvalue,0,120*sizeof(Float_t));
  memset(fTimeEq,1,24*sizeof(Float_t));
}

//________________________________________________________________
void  AliT0CalibTimeEq::Print(Option_t*) const
{
  // print time values

  printf("\n	----	PM Arrays	----\n\n");
  printf(" Time delay CFD \n");
  for (Int_t i=0; i<24; i++) printf(" CFD  %f ",fTimeEq[i]);
  printf("\n Mean Vertex %f \n", fMeanVertex);
}

//________________________________________________________________
Bool_t AliT0CalibTimeEq::ComputeOnlineParams(const char* filePhys)
{
  // compute online equalized time
  Float_t meandiff, sigmadiff, meanver, meancfdtime, sigmacfdtime;
  Double_t rms=0, rmsver=0, rmscfd=0;
  Int_t nent=0;
  Bool_t ok=false;
  gFile = TFile::Open(filePhys);
  if(!gFile) {
    AliError("No input PHYS data found ");
  }
  else
    {
      //    gFile->ls();
      ok=true;
      for (Int_t i=0; i<24; i++)
	{
	  TH1F *cfd = (TH1F*) gFile->Get(Form("CFD1minCFD%d",i+1));
	  TH1F *cfdtime = (TH1F*) gFile->Get(Form("CFD%d",i+1));
	  if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
	  //      printf(" i = %d buf1 = %s\n", i, buf1);
	  if(cfd) {
	    GetMeanAndSigma(cfd, meandiff, sigmadiff);
 	    nent=cfd->GetEntries();
	    if(nent<500 || cfd->GetRMS()>20. ) {
	      ok=false;
	      AliWarning(Form("Data is not good enouph in PMT %i - mean %f rsm %f nentries %i", i,meandiff,sigmadiff , nent));

	    }
	    else
	      {
		ok=false;
		AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i));
	      }
	    if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
	  }
	    //      printf(" i = %d buf1 = %s\n", i, buf1);
	  if(cfdtime) {
	    GetMeanAndSigma(cfdtime,meancfdtime, sigmacfdtime);
 	    nent=cfdtime->GetEntries();
	    if(nent<500 || sigmacfdtime>30. ) {
	      ok=false;
	      AliWarning(Form("Data is not good enouph in PMT %i CFD data - meancfdtime %f rsm %f nentries %i", i,meancfdtime, sigmacfdtime, nent));

	    }
	  }
	  else
	    {
		ok=false;
		AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i));
	      }

	  SetTimeEq(i,meandiff);
	  SetTimeEqRms(i,sigmadiff);
	  SetCFDvalue(i,0,meancfdtime);
	  SetCFDvalue(i,0,sigmacfdtime);
	  if (cfd) delete cfd;
	  if (cfdtime) delete cfdtime;

	}
      TH1F *ver = (TH1F*) gFile->Get("hVertex");
      if(!ver) AliWarning("no T0 histogram collected by PHYS DA ");
      if(ver) {
	meanver = ver->GetMean();
	rmsver = ver->GetRMS();
      }
      SetMeanVertex(meanver);
      SetRmsVertex(rmsver);

      gFile->Close();
      delete gFile;

    }
    return ok;
}

//________________________________________________________________
Bool_t AliT0CalibTimeEq::ComputeOfflineParams(const char* filePhys)
{
  // compute online equalized time
  Float_t meandiff, sigmadiff, meanver, meancfdtime, sigmacfdtime;
  Double_t rms=0, rmsver=0, rmscfd=0;
  Int_t nent=0;
  Bool_t ok=false;
   gFile = TFile::Open(filePhys);
  if(!gFile) {
    AliError("No input PHYS data found ");
  }
  else
    {
      //    gFile->ls();
      ok=true;
      TObjArray * TzeroObj = (TObjArray*) gFile->Get("fTzeroObject");
      for (Int_t i=0; i<24; i++)
	{
	  TH1F *cfddiff = (TH1F*)TzeroObj->At(i);
	  TH1F *cfdtime = (TH1F*)TzeroObj->At(i+24);
	  if(!cfddiff) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
	  //      printf(" i = %d buf1 = %s\n", i, buf1);
	  if(cfddiff) {
 	    GetMeanAndSigma(cfddiff,meandiff, sigmadiff);
 	    nent=cfddiff->GetEntries();
	    if(nent<500 || cfddiff->GetRMS()>20. ) {
	      ok=false;
	      AliWarning(Form("Data is not good enouph in PMT %i - mean %f rsm %f nentries %i", i,meandiff,sigmadiff, nent));

	    }
	    else
	      {
		ok=false;
		AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i));
	      }
	  if(!cfdtime) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
	  //      printf(" i = %d buf1 = %s\n", i, buf1);
	  if(cfdtime) {
	    GetMeanAndSigma(cfdtime,meancfdtime, sigmacfdtime);
 	    nent=cfdtime->GetEntries();
	    if(nent<500 || cfdtime->GetRMS()>30. ) {
	      ok=false;
	      AliWarning(Form("Data is not good enouph in PMT %i CFD data - mean %f rsm %f nentries %i", i,meancfdtime, sigmacfdtime, nent));

	    }
	  }
	  else
	    {
		ok=false;
		AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i));
	      }
	  }

	  SetTimeEq(i,meandiff);
	  SetTimeEqRms(i,sigmadiff);
	  SetCFDvalue(i,0,meancfdtime);
	  SetCFDvalue(i,0,sigmacfdtime);
	  if (cfddiff) delete cfddiff;
	  if (cfdtime) delete cfdtime;

	}
      TH1F *ver = (TH1F*) gFile->Get("hVertex");
      if(!ver) AliWarning("no T0 histogram collected by PHYS DA ");
      if(ver) {
	meanver = ver->GetMean();
	rmsver = ver->GetRMS();
      }
      SetMeanVertex(meanver);
      SetRmsVertex(rmsver);

      gFile->Close();
      delete gFile;

    }
    return ok;
}

//________________________________________________________________________
void AliT0CalibTimeEq::GetMeanAndSigma(TH1F* hist,  Float_t &mean, Float_t &sigma) {

  const double threshold = 0.5;  // threshold level with respect to maximum bin
  const double window = 5.;  //fit window
  double norm  = hist->Integral();  // normalize to one count
  hist->Scale(1./norm);

  double meanEstimate, sigmaEstimate;
  int maxBin;
  maxBin        =  hist->GetMaximumBin(); //position of maximum
  meanEstimate  =  hist->GetBinCenter( maxBin); // mean of gaussian sitting in maximum
  sigmaEstimate = hist->GetRMS();
  TF1* fit= new TF1("fit","gaus", meanEstimate - window*sigmaEstimate, meanEstimate + window*sigmaEstimate);
  fit->SetParameters(hist->GetBinContent(maxBin), meanEstimate, sigmaEstimate);
  hist->Fit("fit","R");

  mean  = (Float_t) fit->GetParameter(1);
  sigma = (Float_t) fit->GetParameter(2);

  delete fit;
}

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

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// class for T0 calibration                       TM-AC-AM_6-02-2006
// equalize time shift for each time CFD channel
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include "AliT0CalibTimeEq.h"
#include "AliLog.h"
#include <TFile.h>
#include <TMath.h>
#include <TF1.h>
#include <TSpectrum.h>
#include <TProfile.h>
#include <iostream>

ClassImp(AliT0CalibTimeEq)

//________________________________________________________________
  AliT0CalibTimeEq::AliT0CalibTimeEq():TNamed(),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
  //

}

//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const char* name):TNamed(),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
  //constructor

  TString namst = "Calib_";
  namst += name;
  SetName(namst.Data());
  SetTitle(namst.Data());
}

//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const AliT0CalibTimeEq& calibda):TNamed(calibda),
				       fMeanVertex(0),
				       fRmsVertex(0)
{
// copy constructor
  SetName(calibda.GetName());
  SetTitle(calibda.GetName());

}

//________________________________________________________________
AliT0CalibTimeEq &AliT0CalibTimeEq::operator =(const AliT0CalibTimeEq& calibda)
{
// assignment operator
  SetName(calibda.GetName());
  SetTitle(calibda.GetName());

  return *this;
}

//________________________________________________________________
AliT0CalibTimeEq::~AliT0CalibTimeEq()
{
  //
  // destrictor
}
//________________________________________________________________
void AliT0CalibTimeEq::Reset()
{
  //reset values

  memset(fCFDvalue,0,120*sizeof(Float_t));
  memset(fTimeEq,1,24*sizeof(Float_t));
}

//________________________________________________________________
void  AliT0CalibTimeEq::Print(Option_t*) const
{
  // print time values

  printf("\n	----	PM Arrays	----\n\n");
  printf(" Time delay CFD \n");
  for (Int_t i=0; i<24; i++) printf(" CFD  %f ",fTimeEq[i]);
  printf("\n Mean Vertex %f \n", fMeanVertex);
}

//________________________________________________________________
Bool_t AliT0CalibTimeEq::ComputeOnlineParams(const char* filePhys)
{
  // compute online equalized time
  Float_t meandiff, sigmadiff, meanver, meancfdtime, sigmacfdtime;
  meandiff = sigmadiff =  meanver = meancfdtime = sigmacfdtime =0;
    // Double_t rms=0, rmscfd=0;
  Double_t rmsver=0;
 Int_t nent=0;
  Bool_t ok=false;
  gFile = TFile::Open(filePhys);
  if(!gFile) {
    AliError("No input PHYS data found ");
  }
  else
    {
      //    gFile->ls();
      ok=true;
      for (Int_t i=0; i<24; i++)
	{
	  TH1F *cfd = (TH1F*) gFile->Get(Form("CFD1minCFD%d",i+1));
	  TH1F *cfdtime = (TH1F*) gFile->Get(Form("CFD%d",i+1));
	  if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
	  //      printf(" i = %d buf1 = %s\n", i, buf1);
	  if(cfd) {
	    GetMeanAndSigma(cfd, meandiff, sigmadiff);
 	    nent=cfd->GetEntries();
	    if(nent<500 || cfd->GetRMS()>20. ) {
	      ok=false;
	      AliWarning(Form("Data is not good enouph in PMT %i - mean %f rsm %f nentries %i", i,meandiff,sigmadiff , nent));

	    }
	    else
	      {
		ok=false;
		AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i));
	      }
	    if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
	  }
	    //      printf(" i = %d buf1 = %s\n", i, buf1);
	  if(cfdtime) {
	    GetMeanAndSigma(cfdtime,meancfdtime, sigmacfdtime);
 	    nent=cfdtime->GetEntries();
	    if(nent<500 || sigmacfdtime>30. ) {
	      ok=false;
	      AliWarning(Form("Data is not good enouph in PMT %i CFD data - meancfdtime %f rsm %f nentries %i", i,meancfdtime, sigmacfdtime, nent));

	    }
	  }
	  else
	    {
		ok=false;
		AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i));
	      }

	  SetTimeEq(i,meandiff);
	  SetTimeEqRms(i,sigmadiff);
	  SetCFDvalue(i,0,meancfdtime);
	  SetCFDvalue(i,0,sigmacfdtime);
	  if (cfd) delete cfd;
	  if (cfdtime) delete cfdtime;

	}
      TH1F *ver = (TH1F*) gFile->Get("hVertex");
      if(!ver) AliWarning("no T0 histogram collected by PHYS DA ");
      if(ver) {
	meanver = ver->GetMean();
	rmsver = ver->GetRMS();
      }
      SetMeanVertex(meanver);
      SetRmsVertex(rmsver);

      gFile->Close();
      delete gFile;

    }
    return ok;
}

//________________________________________________________________
Bool_t AliT0CalibTimeEq::ComputeOfflineParams(const char* filePhys)
{
  // compute online equalized time
  Float_t meandiff, sigmadiff, meanver, meancfdtime, sigmacfdtime;
  meandiff = sigmadiff =  meanver = meancfdtime = sigmacfdtime =0;
  // Double_t rms=0, rmscfd=0;
  Double_t rmsver=0;
  Int_t nent=0;
  Bool_t ok=false;
  gFile = TFile::Open(filePhys);
  if(!gFile) {
    AliError("No input PHYS data found ");
  }
  else
    {
      //    gFile->ls();
      ok=true;
      TObjArray * TzeroObj = (TObjArray*) gFile->Get("fTzeroObject");
      for (Int_t i=0; i<24; i++)
	{
	  TH1F *cfddiff = (TH1F*)TzeroObj->At(i);
	  TH1F *cfdtime = (TH1F*)TzeroObj->At(i+24);
	  if(!cfddiff) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
	  //      printf(" i = %d buf1 = %s\n", i, buf1);
	  if(cfddiff) {
 	    GetMeanAndSigma(cfddiff,meandiff, sigmadiff);
 	    nent=cfddiff->GetEntries();
	    if(nent<500 || cfddiff->GetRMS()>20. ) {
	      ok=false;
	      AliWarning(Form("Data is not good enouph in PMT %i - mean %f rsm %f nentries %i", i,meandiff,sigmadiff, nent));

	    }
	    else
	      {
		ok=false;
		AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i));
	      }
	  if(!cfdtime) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
	  //      printf(" i = %d buf1 = %s\n", i, buf1);
	  if(cfdtime) {
	    GetMeanAndSigma(cfdtime,meancfdtime, sigmacfdtime);
 	    nent=cfdtime->GetEntries();
	    if(nent<500 || cfdtime->GetRMS()>30. ) {
	      ok=false;
	      AliWarning(Form("Data is not good enouph in PMT %i CFD data - mean %f rsm %f nentries %i", i,meancfdtime, sigmacfdtime, nent));

	    }
	  }
	  else
	    {
		ok=false;
		AliWarning(Form("Data is not good enouph in PMT %i , no clean peak", i));
	      }
	  }

	  SetTimeEq(i,meandiff);
	  SetTimeEqRms(i,sigmadiff);
	  SetCFDvalue(i,0,meancfdtime);
	  SetCFDvalue(i,0,sigmacfdtime);
	  if (cfddiff) delete cfddiff;
	  if (cfdtime) delete cfdtime;

	}
      TH1F *ver = (TH1F*) gFile->Get("hVertex");
      if(!ver) AliWarning("no T0 histogram collected by PHYS DA ");
      if(ver) {
	meanver = ver->GetMean();
	rmsver = ver->GetRMS();
      }
      SetMeanVertex(meanver);
      SetRmsVertex(rmsver);

      gFile->Close();
      delete gFile;

    }
    return ok;
}

//________________________________________________________________________
void AliT0CalibTimeEq::GetMeanAndSigma(TH1F* hist,  Float_t &mean, Float_t &sigma) {

  const double window = 5.;  //fit window
  double norm  = hist->Integral();  // normalize to one count
  hist->Scale(1./norm);

  double meanEstimate, sigmaEstimate;
  int maxBin;
  maxBin        =  hist->GetMaximumBin(); //position of maximum
  meanEstimate  =  hist->GetBinCenter( maxBin); // mean of gaussian sitting in maximum
  sigmaEstimate = hist->GetRMS();
  TF1* fit= new TF1("fit","gaus", meanEstimate - window*sigmaEstimate, meanEstimate + window*sigmaEstimate);
  fit->SetParameters(hist->GetBinContent(maxBin), meanEstimate, sigmaEstimate);
  hist->Fit("fit","R");

  mean  = (Float_t) fit->GetParameter(1);
  sigma = (Float_t) fit->GetParameter(2);

  delete fit;
}

<|endoftext|>


<commit_before>/*****************************************************************************
 * Project: BaBar detector at the SLAC PEP-II B-factory
 * Package: RooFitCore
 *    File: $Id: RooCurve.cc,v 1.16 2001/09/19 01:35:29 verkerke Exp $
 * Authors:
 *   DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu
 * History:
 *   29-Apr-2001 DK Created initial version
 *
 * Copyright (C) 2001 Stanford University
 *****************************************************************************/

// -- CLASS DESCRIPTION --
// A RooCurve is a one-dimensional graphical representation of a real-valued function.
// A curve is approximated by straight line segments with endpoints chosen to give
// a "good" approximation to the true curve. The goodness of the approximation is
// controlled by a precision and a resolution parameter. To view the points where
// a function y(x) is actually evaluated to approximate a smooth curve, use:
//
//  RooPlot *p= y.plotOn(x.frame());
//  p->getAttMarker("curve_y")->SetMarkerStyle(20);
//  p->setDrawOptions("curve_y","PL");
//  p->Draw();

// #include "BaBar/BaBar.hh"

#include "RooFitCore/RooCurve.hh"
#include "RooFitCore/RooAbsReal.hh"
#include "RooFitCore/RooArgSet.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooRealIntegral.hh"
#include "RooFitCore/RooRealBinding.hh"
#include "RooFitCore/RooScaledFunc.hh"

#include <iostream.h>
#include <iomanip.h>
#include <math.h>
#include <assert.h>

ClassImp(RooCurve)

static const char rcsid[] =
"$Id: RooCurve.cc,v 1.16 2001/09/19 01:35:29 verkerke Exp $";

RooCurve::RooCurve() {
  initialize();
}

RooCurve::RooCurve(const RooAbsReal &f, RooRealVar &x, Double_t scaleFactor,
		   const RooArgSet *normVars, Double_t prec, Double_t resolution) {
  // Create a 1-dim curve of the value of the specified real-valued expression
  // as a function of x. Use the optional precision parameter to control
  // how precisely the smooth curve is rasterized. Use the optional argument set
  // to specify how the expression should be normalized. Use the optional scale
  // factor to rescale the expression after normalization.

  // grab the function's name and title
  TString name("curve_");
  name.Append(f.GetName());
  SetName(name.Data());
  TString title(f.GetTitle());
  SetTitle(title.Data());
  // append " ( [<funit> ][/ <xunit> ])" to our y-axis label if necessary
  if(0 != strlen(f.getUnit()) || 0 != strlen(x.getUnit())) {
    title.Append(" ( ");
    if(0 != strlen(f.getUnit())) {
      title.Append(f.getUnit());
      title.Append(" ");
    }
    if(0 != strlen(x.getUnit())) {
      title.Append("/ ");
      title.Append(x.getUnit());
      title.Append(" ");
    }
    title.Append(")");
  }
  setYAxisLabel(title.Data());

  RooAbsFunc *funcPtr(0),*rawPtr(0);
  RooRealIntegral *projected(0);
  RooArgSet bindNormSet ;
  if(0 != normVars) {
    RooArgSet vars(*normVars);
    bindNormSet.add(*normVars) ;

    RooAbsArg *found= vars.find(x.GetName());
    if(found) {
      // remove x from the set of vars to be projected
      vars.remove(*found);
    }

    // Remove args from vars that PDF doesn't depend on
    TIterator* iter = vars.createIterator() ;
    RooAbsArg* arg ;
    while(arg=(RooAbsArg*)iter->Next()) {
      if (!f.dependsOn(*arg)) {
	vars.remove(*arg) ;
      }
    }
    delete iter ;

    // project out any remaining normalization variables
    if(vars.getSize() > 0) {
      TString name(f.GetName()) ;
      name.Append("Projected") ;
      TString title(f.GetTitle()) ;
      title.Append(" (Projected)") ;
      projected= new RooRealIntegral(name.Data(),title.Data(),f,vars,&bindNormSet);
      cout << "RooCurve(" << f.GetName() << "): projecting function over " ; vars.Print("1") ; cout << endl ;
      //projected->Print("v") ;
      if(!projected->isValid()) return;
      funcPtr= projected->bindVars(x,&bindNormSet);
    }
  } else {
    bindNormSet.add(x) ;
  }

  if(0 == funcPtr) {
    funcPtr= f.bindVars(x,&bindNormSet);
  }
  // apply a scale factor if necessary
  if(scaleFactor != 1) {
    rawPtr= funcPtr;
    funcPtr= new RooScaledFunc(*rawPtr,scaleFactor);
  }
  assert(0 != funcPtr);

  // calculate the points to add to our curve
  addPoints(*funcPtr,x.getPlotMin(),x.getPlotMax(),x.getPlotBins()+1,prec,resolution);
  initialize();

  // cleanup
  delete funcPtr;
  if(rawPtr) delete rawPtr;
  if(projected) delete projected;
}

RooCurve::RooCurve(const char *name, const char *title, const RooAbsFunc &func,
		   Double_t xlo, Double_t xhi, UInt_t minPoints, Double_t prec, Double_t resolution) {
  SetName(name);
  SetTitle(title);
  addPoints(func,xlo,xhi,minPoints,prec,resolution);
  initialize();
}

RooCurve::~RooCurve() {
}

void RooCurve::initialize() {
  // Perform initialization that is common to all constructors.

  // set default line width in pixels
  SetLineWidth(3);
  // set default line color
  SetLineColor(kBlue);
}

void RooCurve::addPoints(const RooAbsFunc &func, Double_t xlo, Double_t xhi,
			 Int_t minPoints, Double_t prec, Double_t resolution) {
  // Add points calculated with the specified function, over the range (xlo,xhi).
  // Add at least minPoints equally spaced points, and add sufficient points so that
  // the maximum deviation from the final straight-line segements is prec*(ymax-ymin),
  // down to a minimum horizontal spacing of resolution*(xhi-xlo).

  // check the inputs
  if(!func.isValid()) {
    cout << fName << "::addPoints: input function is not valid" << endl;
    return;
  }
  if(minPoints <= 0 || xhi <= xlo) {
    cout << fName << "::addPoints: bad input (nothing added)" << endl;
    return;
  }

  // Perform a coarse scan of the function to estimate its y range.
  // Save the results so we do not have to re-evaluate at the scan points.
  Double_t *yval= new Double_t[minPoints];
  assert(0 != yval);
  Double_t x,dx= (xhi-xlo)/(minPoints-1.);
  for(Int_t step= 0; step < minPoints; step++) {
    x= xlo + step*dx;
    yval[step]= func(&x);
    updateYAxisLimits(yval[step]);
  }

  // store points of the coarse scan and calculate any refinements necessary
  Double_t minDx= resolution*(xhi-xlo);
  Double_t x1,x2= xlo;
  addPoint(xlo,yval[0]);
  for(Int_t step= 1; step < minPoints; step++) {
    x1= x2;
    x2= xlo + step*dx;
    addRange(func,x1,x2,yval[step-1],yval[step],prec,minDx);
  }

  // cleanup
  delete [] yval;
}

void RooCurve::addRange(const RooAbsFunc& func, Double_t x1, Double_t x2,
			Double_t y1, Double_t y2, Double_t prec, Double_t minDx) {
  // Fill the range (x1,x2) with points calculated using func(&x). No point will
  // be added at x1, and a point will always be added at x2. The density of points
  // will be calculated so that the maximum deviation from a straight line
  // approximation is prec*(ymax-ymin) down to the specified minimum horizontal spacing.

  // calculate our value at the midpoint of this range
  Double_t xmid= 0.5*(x1+x2);
  Double_t ymid= func(&xmid);
  // test if the midpoint is sufficiently close to a straight line across this interval
  Double_t dy= ymid - 0.5*(y1+y2);
  if((xmid - x1 >= minDx) && fabs(dy)>0 && fabs(dy) >= prec*(getYAxisMax()-getYAxisMin())) {
    // fill in each subrange
    updateYAxisLimits(ymid);
    addRange(func,x1,xmid,y1,ymid,prec,minDx);
    addRange(func,xmid,x2,ymid,y2,prec,minDx);
  }
  else {
    // add the endpoint
    addPoint(x2,y2);
  }
}

void RooCurve::addPoint(Double_t x, Double_t y) {
  // Add a point with the specified coordinates. Update our y-axis limits.

  Int_t next= GetN();
  SetPoint(next, x, y);
}

Double_t RooCurve::getFitRangeNorm() const {
  return 1;
}

void RooCurve::printToStream(ostream& os, PrintOption opt, TString indent) const {
  // Print info about this histogram to the specified output stream.
  //
  //   Standard: number of entries
  //    Verbose: print points on curve

  oneLinePrint(os,*this);
  RooPlotable::printToStream(os,opt,indent);
  if(opt >= Standard) {
    os << indent << "--- RooCurve ---" << endl;
    Int_t n= GetN();
    os << indent << "  Contains " << n << " points" << endl;
    if(opt >= Verbose) {
      os << indent << "  Graph points:" << endl;
      for(Int_t i= 0; i < n; i++) {
	os << indent << setw(3) << i << ") x = " << fX[i] << " , y = " << fY[i] << endl;
      }
    }
  }
}
<commit_msg>better error message<commit_after>/*****************************************************************************
 * Project: BaBar detector at the SLAC PEP-II B-factory
 * Package: RooFitCore
 *    File: $Id: RooCurve.cc,v 1.17 2001/09/20 01:40:10 verkerke Exp $
 * Authors:
 *   DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu
 * History:
 *   29-Apr-2001 DK Created initial version
 *
 * Copyright (C) 2001 Stanford University
 *****************************************************************************/

// -- CLASS DESCRIPTION --
// A RooCurve is a one-dimensional graphical representation of a real-valued function.
// A curve is approximated by straight line segments with endpoints chosen to give
// a "good" approximation to the true curve. The goodness of the approximation is
// controlled by a precision and a resolution parameter. To view the points where
// a function y(x) is actually evaluated to approximate a smooth curve, use:
//
//  RooPlot *p= y.plotOn(x.frame());
//  p->getAttMarker("curve_y")->SetMarkerStyle(20);
//  p->setDrawOptions("curve_y","PL");
//  p->Draw();

// #include "BaBar/BaBar.hh"

#include "RooFitCore/RooCurve.hh"
#include "RooFitCore/RooAbsReal.hh"
#include "RooFitCore/RooArgSet.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooRealIntegral.hh"
#include "RooFitCore/RooRealBinding.hh"
#include "RooFitCore/RooScaledFunc.hh"

#include <iostream.h>
#include <iomanip.h>
#include <math.h>
#include <assert.h>

ClassImp(RooCurve)

static const char rcsid[] =
"$Id: RooCurve.cc,v 1.17 2001/09/20 01:40:10 verkerke Exp $";

RooCurve::RooCurve() {
  initialize();
}

RooCurve::RooCurve(const RooAbsReal &f, RooRealVar &x, Double_t scaleFactor,
		   const RooArgSet *normVars, Double_t prec, Double_t resolution) {
  // Create a 1-dim curve of the value of the specified real-valued expression
  // as a function of x. Use the optional precision parameter to control
  // how precisely the smooth curve is rasterized. Use the optional argument set
  // to specify how the expression should be normalized. Use the optional scale
  // factor to rescale the expression after normalization.

  // grab the function's name and title
  TString name("curve_");
  name.Append(f.GetName());
  SetName(name.Data());
  TString title(f.GetTitle());
  SetTitle(title.Data());
  // append " ( [<funit> ][/ <xunit> ])" to our y-axis label if necessary
  if(0 != strlen(f.getUnit()) || 0 != strlen(x.getUnit())) {
    title.Append(" ( ");
    if(0 != strlen(f.getUnit())) {
      title.Append(f.getUnit());
      title.Append(" ");
    }
    if(0 != strlen(x.getUnit())) {
      title.Append("/ ");
      title.Append(x.getUnit());
      title.Append(" ");
    }
    title.Append(")");
  }
  setYAxisLabel(title.Data());

  RooAbsFunc *funcPtr(0),*rawPtr(0);
  RooRealIntegral *projected(0);
  RooArgSet bindNormSet ;
  if(0 != normVars) {
    RooArgSet vars(*normVars);
    bindNormSet.add(*normVars) ;

    RooAbsArg *found= vars.find(x.GetName());
    if(found) {
      // remove x from the set of vars to be projected
      vars.remove(*found);
    }

    // Remove args from vars that PDF doesn't depend on
    TIterator* iter = vars.createIterator() ;
    RooAbsArg* arg ;
    while(arg=(RooAbsArg*)iter->Next()) {
      if (!f.dependsOn(*arg)) {
	vars.remove(*arg) ;
      }
    }
    delete iter ;

    // project out any remaining normalization variables
    if(vars.getSize() > 0) {
      TString name(f.GetName()) ;
      name.Append("Projected") ;
      TString title(f.GetTitle()) ;
      title.Append(" (Projected)") ;
      projected= new RooRealIntegral(name.Data(),title.Data(),f,vars,&bindNormSet);
      cout << "RooCurve(" << f.GetName() << "): projecting function over " ; vars.Print("1") ; cout << endl ;
      if(0 == projected || !projected->isValid()) {
	cout << ClassName() << ": cannot integrate out ";
	vars.Print();
	// cleanup and exit
	if(0 != projected) delete projected;
	return;
      }
      funcPtr= projected->bindVars(x,&bindNormSet);
    }
  } else {
    bindNormSet.add(x) ;
  }

  if(0 == funcPtr) {
    funcPtr= f.bindVars(x,&bindNormSet);
  }
  // apply a scale factor if necessary
  if(scaleFactor != 1) {
    rawPtr= funcPtr;
    funcPtr= new RooScaledFunc(*rawPtr,scaleFactor);
  }
  assert(0 != funcPtr);

  // calculate the points to add to our curve
  addPoints(*funcPtr,x.getPlotMin(),x.getPlotMax(),x.getPlotBins()+1,prec,resolution);
  initialize();

  // cleanup
  delete funcPtr;
  if(rawPtr) delete rawPtr;
  if(projected) delete projected;
}

RooCurve::RooCurve(const char *name, const char *title, const RooAbsFunc &func,
		   Double_t xlo, Double_t xhi, UInt_t minPoints, Double_t prec, Double_t resolution) {
  SetName(name);
  SetTitle(title);
  addPoints(func,xlo,xhi,minPoints,prec,resolution);
  initialize();
}

RooCurve::~RooCurve() {
}

void RooCurve::initialize() {
  // Perform initialization that is common to all constructors.

  // set default line width in pixels
  SetLineWidth(3);
  // set default line color
  SetLineColor(kBlue);
}

void RooCurve::addPoints(const RooAbsFunc &func, Double_t xlo, Double_t xhi,
			 Int_t minPoints, Double_t prec, Double_t resolution) {
  // Add points calculated with the specified function, over the range (xlo,xhi).
  // Add at least minPoints equally spaced points, and add sufficient points so that
  // the maximum deviation from the final straight-line segements is prec*(ymax-ymin),
  // down to a minimum horizontal spacing of resolution*(xhi-xlo).

  // check the inputs
  if(!func.isValid()) {
    cout << fName << "::addPoints: input function is not valid" << endl;
    return;
  }
  if(minPoints <= 0 || xhi <= xlo) {
    cout << fName << "::addPoints: bad input (nothing added)" << endl;
    return;
  }

  // Perform a coarse scan of the function to estimate its y range.
  // Save the results so we do not have to re-evaluate at the scan points.
  Double_t *yval= new Double_t[minPoints];
  assert(0 != yval);
  Double_t x,dx= (xhi-xlo)/(minPoints-1.);
  for(Int_t step= 0; step < minPoints; step++) {
    x= xlo + step*dx;
    yval[step]= func(&x);
    updateYAxisLimits(yval[step]);
  }

  // store points of the coarse scan and calculate any refinements necessary
  Double_t minDx= resolution*(xhi-xlo);
  Double_t x1,x2= xlo;
  addPoint(xlo,yval[0]);
  for(Int_t step= 1; step < minPoints; step++) {
    x1= x2;
    x2= xlo + step*dx;
    addRange(func,x1,x2,yval[step-1],yval[step],prec,minDx);
  }

  // cleanup
  delete [] yval;
}

void RooCurve::addRange(const RooAbsFunc& func, Double_t x1, Double_t x2,
			Double_t y1, Double_t y2, Double_t prec, Double_t minDx) {
  // Fill the range (x1,x2) with points calculated using func(&x). No point will
  // be added at x1, and a point will always be added at x2. The density of points
  // will be calculated so that the maximum deviation from a straight line
  // approximation is prec*(ymax-ymin) down to the specified minimum horizontal spacing.

  // calculate our value at the midpoint of this range
  Double_t xmid= 0.5*(x1+x2);
  Double_t ymid= func(&xmid);
  // test if the midpoint is sufficiently close to a straight line across this interval
  Double_t dy= ymid - 0.5*(y1+y2);
  if((xmid - x1 >= minDx) && fabs(dy)>0 && fabs(dy) >= prec*(getYAxisMax()-getYAxisMin())) {
    // fill in each subrange
    updateYAxisLimits(ymid);
    addRange(func,x1,xmid,y1,ymid,prec,minDx);
    addRange(func,xmid,x2,ymid,y2,prec,minDx);
  }
  else {
    // add the endpoint
    addPoint(x2,y2);
  }
}

void RooCurve::addPoint(Double_t x, Double_t y) {
  // Add a point with the specified coordinates. Update our y-axis limits.

  Int_t next= GetN();
  SetPoint(next, x, y);
}

Double_t RooCurve::getFitRangeNorm() const {
  return 1;
}

void RooCurve::printToStream(ostream& os, PrintOption opt, TString indent) const {
  // Print info about this histogram to the specified output stream.
  //
  //   Standard: number of entries
  //    Verbose: print points on curve

  oneLinePrint(os,*this);
  RooPlotable::printToStream(os,opt,indent);
  if(opt >= Standard) {
    os << indent << "--- RooCurve ---" << endl;
    Int_t n= GetN();
    os << indent << "  Contains " << n << " points" << endl;
    if(opt >= Verbose) {
      os << indent << "  Graph points:" << endl;
      for(Int_t i= 0; i < n; i++) {
	os << indent << setw(3) << i << ") x = " << fX[i] << " , y = " << fY[i] << endl;
      }
    }
  }
}
<|endoftext|>


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

#include "AliTPCpolyTrack.h"
#include "TMath.h"

ClassImp(AliTPCpolyTrack)

AliTPCpolyTrack::AliTPCpolyTrack()
{
  Reset();
}

void   AliTPCpolyTrack::Reset()
{
  //
  // reset track
  fSumX = fSumX2= fSumX3=fSumX4 = fSumY=fSumYX=fSumYX2=fSumZ=fSumZX=fSumZX2=fSumW =0;
  fNPoints = 0;
}

void AliTPCpolyTrack::AddPoint(Double_t x, Double_t y, Double_t z,Double_t sy, Double_t sz)
{
  //
  //
  if (fNPoints==0){
    fMaxX = x;
    fMinX = x;
  }else{
    if (x>fMaxX) fMaxX=x;
    if (x<fMinX) fMinX=x;
  }

  Double_t x2 = x*x;
  Double_t w = 2./(sy+sz);
  fSumW += w;
  //
  fSumX       += x*w;
  fSumX2      += x2*w;
  fSumX3      += x2*x*w;
  fSumX4      += x2*x2*w;
  //
  fSumY       +=y*w;
  fSumYX      +=y*x*w;
  fSumYX2     +=y*x2*w;
  //
  fSumZ       +=z*w;
  fSumZX      +=z*x*w;
  fSumZX2     +=z*x2*w;
  //
  fX[fNPoints] = x;
  fY[fNPoints] = y;
  fZ[fNPoints] = z;
  fSY[fNPoints] = sy;
  fSZ[fNPoints] = sz;

  fNPoints++;

}

void  AliTPCpolyTrack::UpdateParameters()
{
  //
  //
  //Update fit parameters
  if (fNPoints>4){
    Fit2(fSumY,fSumYX,fSumYX2,fSumX,fSumX2,fSumX3,fSumX4,fSumW,fA,fB,fC);
    //    Fit2(fSumZ,fSumZX,fSumZX2,fSumX,fSumX2,fSumX3,fSumX4,fNPoints,fD,fE,fF);
    Fit1(fSumZ,fSumZX,fSumX,fSumX2,fSumW,fD,fE,fF);
  }
  else
    {
      Fit1(fSumY,fSumYX,fSumX,fSumX2,fSumW,fA,fB,fC);
      Fit1(fSumZ,fSumZX,fSumX,fSumX2,fSumW,fD,fE,fF);
    }
}

void  AliTPCpolyTrack::Fit2(Double_t fSumY, Double_t fSumYX, Double_t fSumYX2,
	    Double_t fSumX,  Double_t fSumX2, Double_t fSumX3,
	    Double_t fSumX4, Double_t fSumW,
	    Double_t &a, Double_t &b, Double_t &c)
{
  //fit of second order
  Double_t det =
    fSumW* (fSumX2*fSumX4-fSumX3*fSumX3) -
    fSumX*      (fSumX*fSumX4-fSumX3*fSumX2)+
    fSumX2*     (fSumX*fSumX3-fSumX2*fSumX2);

  if (TMath::Abs(det)> 0.000000000000001) {
    a =
      (fSumY * (fSumX2*fSumX4-fSumX3*fSumX3)-
       fSumX *(fSumYX*fSumX4-fSumYX2*fSumX3)+
       fSumX2*(fSumYX*fSumX3-fSumYX2*fSumX2))/det;
    b=
      (fSumW*(fSumYX*fSumX4-fSumX3*fSumYX2)-
      fSumY*(fSumX*fSumX4-fSumX3*fSumX2)+
      fSumX2*(fSumX*fSumYX2-fSumYX*fSumX2))/det;
    c=
      (fSumW*(fSumX2*fSumYX2-fSumYX*fSumX3)-
       fSumX*(fSumX*fSumYX2-fSumYX*fSumX2)+
       fSumY*(fSumX*fSumX3-fSumX2*fSumX2))/det;
  }
}

void  AliTPCpolyTrack::Fit1(Double_t fSumY, Double_t fSumYX,
	      Double_t fSumX,  Double_t fSumX2,
	      Double_t fSumW, Double_t &a, Double_t &b, Double_t &c)
{
  //
  //
  //
  Double_t det = fSumW*fSumX2-fSumX*fSumX;
  if (TMath::Abs(det)> 0.000000000000001) {
    b = (fSumW*fSumYX-fSumX*fSumY)/det;
    a = (fSumX2*fSumY-fSumX*fSumYX)/det;
    c = 0;
  }else{
    a =fSumYX/fSumX;
    b =0;
    c =0;
  }

}

void AliTPCpolyTrack::Refit(AliTPCpolyTrack &track, Double_t deltay, Double_t deltaz)
{
  //
  // refit with cut on distortion
  //
  track.Reset();
  //first refit to temporary
  AliTPCpolyTrack track0;
  track0.Reset;
  for (Int_t i=0;i<fNPoints;i++){
    Double_t y,z;
    GetFitPoint(fX[i],y,z);
    if ( (TMath::Abs(y-fY[i])<deltay)&&(TMath::Abs(z-fZ[i])<deltaz)){
      track0.AddPoint(fX[i],y,z);
    }
  }
  if (track0.GetN()>2)
    track0.UpdateParameters();
  else
    return;
  //
  for (Int_t i=0;i<fNPoints;i++){
    Double_t y,z;
    track0.GetFitPoint(fX[i],y,z);
    if ( (TMath::Abs(y-fY[i])<deltay)&&(TMath::Abs(z-fZ[i])<deltaz)){
      track.AddPoint(fX[i],y,z);
    }
  }
  if (track.GetN()>2)
    track.UpdateParameters();

}

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

#include "AliTPCpolyTrack.h"
#include "TMath.h"

ClassImp(AliTPCpolyTrack)

AliTPCpolyTrack::AliTPCpolyTrack()
{
  Reset();
}

void   AliTPCpolyTrack::Reset()
{
  //
  // reset track
  fSumX = fSumX2= fSumX3=fSumX4 = fSumY=fSumYX=fSumYX2=fSumZ=fSumZX=fSumZX2=fSumW =0;
  fNPoints = 0;
}

void AliTPCpolyTrack::AddPoint(Double_t x, Double_t y, Double_t z,Double_t sy, Double_t sz)
{
  //
  //
  if (fNPoints==0){
    fMaxX = x;
    fMinX = x;
  }else{
    if (x>fMaxX) fMaxX=x;
    if (x<fMinX) fMinX=x;
  }

  Double_t x2 = x*x;
  Double_t w = 2./(sy+sz);
  fSumW += w;
  //
  fSumX       += x*w;
  fSumX2      += x2*w;
  fSumX3      += x2*x*w;
  fSumX4      += x2*x2*w;
  //
  fSumY       +=y*w;
  fSumYX      +=y*x*w;
  fSumYX2     +=y*x2*w;
  //
  fSumZ       +=z*w;
  fSumZX      +=z*x*w;
  fSumZX2     +=z*x2*w;
  //
  fX[fNPoints] = x;
  fY[fNPoints] = y;
  fZ[fNPoints] = z;
  fSY[fNPoints] = sy;
  fSZ[fNPoints] = sz;

  fNPoints++;

}

void  AliTPCpolyTrack::UpdateParameters()
{
  //
  //
  //Update fit parameters
  if (fNPoints>4){
    Fit2(fSumY,fSumYX,fSumYX2,fSumX,fSumX2,fSumX3,fSumX4,fSumW,fA,fB,fC);
    //    Fit2(fSumZ,fSumZX,fSumZX2,fSumX,fSumX2,fSumX3,fSumX4,fNPoints,fD,fE,fF);
    Fit1(fSumZ,fSumZX,fSumX,fSumX2,fSumW,fD,fE,fF);
  }
  else
    {
      Fit1(fSumY,fSumYX,fSumX,fSumX2,fSumW,fA,fB,fC);
      Fit1(fSumZ,fSumZX,fSumX,fSumX2,fSumW,fD,fE,fF);
    }
}

void  AliTPCpolyTrack::Fit2(Double_t fSumY, Double_t fSumYX, Double_t fSumYX2,
	    Double_t fSumX,  Double_t fSumX2, Double_t fSumX3,
	    Double_t fSumX4, Double_t fSumW,
	    Double_t &a, Double_t &b, Double_t &c)
{
  //fit of second order
  Double_t det =
    fSumW* (fSumX2*fSumX4-fSumX3*fSumX3) -
    fSumX*      (fSumX*fSumX4-fSumX3*fSumX2)+
    fSumX2*     (fSumX*fSumX3-fSumX2*fSumX2);

  if (TMath::Abs(det)> 0.000000000000001) {
    a =
      (fSumY * (fSumX2*fSumX4-fSumX3*fSumX3)-
       fSumX *(fSumYX*fSumX4-fSumYX2*fSumX3)+
       fSumX2*(fSumYX*fSumX3-fSumYX2*fSumX2))/det;
    b=
      (fSumW*(fSumYX*fSumX4-fSumX3*fSumYX2)-
      fSumY*(fSumX*fSumX4-fSumX3*fSumX2)+
      fSumX2*(fSumX*fSumYX2-fSumYX*fSumX2))/det;
    c=
      (fSumW*(fSumX2*fSumYX2-fSumYX*fSumX3)-
       fSumX*(fSumX*fSumYX2-fSumYX*fSumX2)+
       fSumY*(fSumX*fSumX3-fSumX2*fSumX2))/det;
  }
}

void  AliTPCpolyTrack::Fit1(Double_t fSumY, Double_t fSumYX,
	      Double_t fSumX,  Double_t fSumX2,
	      Double_t fSumW, Double_t &a, Double_t &b, Double_t &c)
{
  //
  //
  //
  Double_t det = fSumW*fSumX2-fSumX*fSumX;
  if (TMath::Abs(det)> 0.000000000000001) {
    b = (fSumW*fSumYX-fSumX*fSumY)/det;
    a = (fSumX2*fSumY-fSumX*fSumYX)/det;
    c = 0;
  }else{
    a =fSumYX/fSumX;
    b =0;
    c =0;
  }

}

void AliTPCpolyTrack::Refit(AliTPCpolyTrack &track, Double_t deltay, Double_t deltaz)
{
  //
  // refit with cut on distortion
  //
  track.Reset();
  //first refit to temporary
  AliTPCpolyTrack track0;
  track0.Reset();
  for (Int_t i=0;i<fNPoints;i++){
    Double_t y,z;
    GetFitPoint(fX[i],y,z);
    if ( (TMath::Abs(y-fY[i])<deltay)&&(TMath::Abs(z-fZ[i])<deltaz)){
      track0.AddPoint(fX[i],y,z);
    }
  }
  if (track0.GetN()>2)
    track0.UpdateParameters();
  else
    return;
  //
  for (Int_t i=0;i<fNPoints;i++){
    Double_t y,z;
    track0.GetFitPoint(fX[i],y,z);
    if ( (TMath::Abs(y-fY[i])<deltay)&&(TMath::Abs(z-fZ[i])<deltaz)){
      track.AddPoint(fX[i],y,z);
    }
  }
  if (track.GetN()>2)
    track.UpdateParameters();

}

<|endoftext|>


<commit_before>/*
    Copyright (C) 2012  Lasath Fernando <kde@lasath.org>
    Copyright (C) 2012  David Edmundson <kde@davidedmundson.co.uk>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "filters.h"

#include <QImageReader>

#include <KProtocolInfo>
#include <KDebug>

UrlFilter::UrlFilter(QObject *parent)
    : AbstractMessageFilter(parent)
{
}

void UrlFilter::filterMessage(Message &info) {
    QString message = info.mainMessagePart();
    //FIXME: make "Urls" into a constant
    QStringList urls = info.property("Urls").toStringList();

    // link detection
    QRegExp link(QLatin1String("\\b(?:(\\w+)://|(www\\.))([^\\s]+)"));
    int fromIndex = 0;

    while ((fromIndex = message.indexOf(link, fromIndex)) != -1) {
        QString realUrl = link.cap(0);
        QString protocol = link.cap(1);

        //if cap(1) is empty cap(2) was matched -> starts with www.
        const bool startsWithWWW = link.cap(1).isEmpty();

        kDebug() << "Found URL " << realUrl << "with protocol : " << (startsWithWWW ? QLatin1String("http") : protocol);

        // if url has a supported protocol
        if (startsWithWWW || KProtocolInfo::protocols().contains(protocol, Qt::CaseInsensitive)) {

            // text not wanted in a link ( <,> )
            QRegExp unwanted(QLatin1String("(<|>)"));

            if (!realUrl.contains(unwanted)) {
                // string to show to user
                QString shownUrl = realUrl;

                // check for newline and cut link when found
                if (realUrl.contains(QLatin1String(("
")))) {
                    int findIndex = realUrl.indexOf(QLatin1String("
"));
                    realUrl.truncate(findIndex);
                    shownUrl.truncate(findIndex);
                }

                // check prefix
                if (startsWithWWW) {
                    realUrl.prepend(QLatin1String("http://"));
                }

                // if the url is changed, show in chat what the user typed in
                QString link = QLatin1String("") + shownUrl + QLatin1String("");

                message.replace(fromIndex, shownUrl.length(), link);
                // advance position otherwise I end up parsing the same link
                fromIndex += link.length();
            } else {
                fromIndex += realUrl.length();
            }

            urls.append(realUrl);
        } else {
            fromIndex += link.matchedLength();
        }
    }

    info.setProperty("Urls", urls);
    info.setMainMessagePart(message);
}

<commit_msg>Change "Urls" property from QList<QString> to QList<KUrl><commit_after>/*
    Copyright (C) 2012  Lasath Fernando <kde@lasath.org>
    Copyright (C) 2012  David Edmundson <kde@davidedmundson.co.uk>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "filters.h"

#include <QImageReader>

#include <KUrl>
#include <KProtocolInfo>
#include <KDebug>

UrlFilter::UrlFilter(QObject *parent)
    : AbstractMessageFilter(parent)
{
}

void UrlFilter::filterMessage(Message &info) {
    QString message = info.mainMessagePart();
    //FIXME: make "Urls" into a constant
    QVariantList urls = info.property("Urls").toList();

    // link detection
    QRegExp link(QLatin1String("\\b(?:(\\w+)://|(www\\.))([^\\s]+)"));
    int fromIndex = 0;

    while ((fromIndex = message.indexOf(link, fromIndex)) != -1) {
        QString realUrl = link.cap(0);
        QString protocol = link.cap(1);

        //if cap(1) is empty cap(2) was matched -> starts with www.
        const bool startsWithWWW = link.cap(1).isEmpty();

        kDebug() << "Found URL " << realUrl << "with protocol : " << (startsWithWWW ? QLatin1String("http") : protocol);

        // if url has a supported protocol
        if (startsWithWWW || KProtocolInfo::protocols().contains(protocol, Qt::CaseInsensitive)) {

            // text not wanted in a link ( <,> )
            QRegExp unwanted(QLatin1String("(<|>)"));

            if (!realUrl.contains(unwanted)) {
                // string to show to user
                QString shownUrl = realUrl;

                // check for newline and cut link when found
                if (realUrl.contains(QLatin1String(("
")))) {
                    int findIndex = realUrl.indexOf(QLatin1String("
"));
                    realUrl.truncate(findIndex);
                    shownUrl.truncate(findIndex);
                }

                // check prefix
                if (startsWithWWW) {
                    realUrl.prepend(QLatin1String("http://"));
                }

                // if the url is changed, show in chat what the user typed in
                QString link = QLatin1String("") + shownUrl + QLatin1String("");

                message.replace(fromIndex, shownUrl.length(), link);
                // advance position otherwise I end up parsing the same link
                fromIndex += link.length();
            } else {
                fromIndex += realUrl.length();
            }

            urls.append(KUrl(realUrl));
        } else {
            fromIndex += link.matchedLength();
        }
    }

    info.setProperty("Urls", urls);
    info.setMainMessagePart(message);
}

<|endoftext|>


<commit_before>/*
 * byte_offset.cpp
 *
 * An implementation of the byte_offset compression scheme used with CBF
 * images with the hopeful intention of replacing existing Python code for
 * doing this with something quicker. Main routines are:
 *
 * vector<char> compress(vector<int>)
 * vector<int> uncompress(vector<char>)
 *
 */

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

using namespace std;

// unions to assist in byte manipulation

typedef union {
  char b[2];
  short s;
} u_s;

typedef union {
  char b[4];
  int i;
} u_i;

// functions for byte swapping

void byte_swap_short(char * b)
{
  char c;
  c = b[0];
  b[0] = b[1];
  b[1] = c;
  return;
}

void byte_swap_int(char * b)
{
  char c;
  c = b[0];
  b[0] = b[3];
  b[3] = c;
  c = b[1];
  b[1] = b[2];
  b[2] = c;
  return;
}

// helper function: is this machine little endian? CBF files are

bool little_endian()
{
  int i = 0x1;
  char b = ((u_i *) &i)[0].b[0];
  if (b == 0)
    {
      return false;
    }
  else
    {
      return true;
    }
}

// main functions

vector<char> compress(const vector<int> values)
{
  vector<char> packed(0);
  int current = 0;
  int delta, i;
  unsigned int j;
  bool le = little_endian();
  short s;
  char c;
  char * b;

  for (j = 0; j < values.size(); j++)
    {
      delta = values[j] - current;

      if ((-127 < delta) && (delta < 127))
	{
	  c = (char) delta;
	  packed.push_back(c);
	  current += delta;
	  continue;
	}

      packed.push_back(-128);

      if ((-32767 < delta) && (delta < 32767))
	{
	  s = (short) delta;
	  b = ((u_s *) & s)[0].b;

	  if (!le)
	    {
	      byte_swap_short(b);
	    }

	  packed.push_back(b[0]);
	  packed.push_back(b[1]);
	  current += delta;
	  continue;
	}

      s = -32768;
      b = ((u_s *) & s)[0].b;

      if (!le)
	{
	  byte_swap_short(b);
	}

      packed.push_back(b[0]);
      packed.push_back(b[1]);

      if ((-2147483647 < delta) && (delta < 2147483647))
	{
	  i = delta;
	  b = ((u_i *) & i)[0].b;

	  if (!le)
	    {
	      byte_swap_int(b);
	    }

	  packed.push_back(b[0]);
	  packed.push_back(b[1]);
	  packed.push_back(b[2]);
	  packed.push_back(b[3]);
	  current += delta;
	  continue;
	}

      /* FIXME I should not get here */

    }

  return packed;
}

vector<int> uncompress(const vector<char> packed)
{
  vector<int> values(0);
  int current = 0;
  unsigned int j = 0;
  short s;
  char c;
  int i;
  bool le = little_endian();

  while (j < packed.size())
    {
      c = packed[j];
      j += 1;

      if (c != -128)
	{
	  current += c;
	  values.push_back(current);
	  continue;
	}

      ((u_s *) & s)[0].b[0] = packed[j];
      ((u_s *) & s)[0].b[1] = packed[j + 1];
      j += 2;

      if (!le)
	{
	  byte_swap_short((char *) &s);
	}

      if (s != -32768)
	{
	  current += s;
	  values.push_back(current);
	  continue;
	}

      ((u_i *) & i)[0].b[0] = packed[j];
      ((u_i *) & i)[0].b[1] = packed[j + 1];
      ((u_i *) & i)[0].b[2] = packed[j + 2];
      ((u_i *) & i)[0].b[3] = packed[j + 3];
      j += 4;

      if (!le)
	{
	  byte_swap_int((char *) &i);
	}

      current += i;
      values.push_back(current);
    }

  return values;
}

// helper for timing tests

double ms(clock_t t1, clock_t t2)
{
  return 1000.0 * (t2 - t1) / CLOCKS_PER_SEC;
}

// demo / test code

int main(int argc,
	 char ** argv)
{

  vector<int> values(0);

  unsigned int j;
  unsigned int size = 4096 * 4096;
  clock_t start;

  start = clock();

  for (j = 0; j < size; j ++)
    {
      values.push_back((rand() & 0xffff));
    }

  cout << "Generating: " << ms(start, clock()) << endl;

  start = clock();
  vector<char> packed = compress(values);
  cout << "Packing:    " << ms(start, clock()) << endl;

  start = clock();
  vector<int> unpacked = uncompress(packed);
  cout << "Unpacking:  " << ms(start, clock()) << endl;

  for (j = 0; j < unpacked.size(); j ++)
    {
      if (unpacked[j] != values[j])
	{
	  cout << "Error for index " << j << endl;
	}
    }

  return 0;
}

<commit_msg>Typo pointed out by nick in inequalities...<commit_after>/*
 * byte_offset.cpp
 *
 * An implementation of the byte_offset compression scheme used with CBF
 * images with the hopeful intention of replacing existing Python code for
 * doing this with something quicker. Main routines are:
 *
 * vector<char> compress(vector<int>)
 * vector<int> uncompress(vector<char>)
 *
 */

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

using namespace std;

// unions to assist in byte manipulation

typedef union {
  char b[2];
  short s;
} u_s;

typedef union {
  char b[4];
  int i;
} u_i;

// functions for byte swapping

void byte_swap_short(char * b)
{
  char c;
  c = b[0];
  b[0] = b[1];
  b[1] = c;
  return;
}

void byte_swap_int(char * b)
{
  char c;
  c = b[0];
  b[0] = b[3];
  b[3] = c;
  c = b[1];
  b[1] = b[2];
  b[2] = c;
  return;
}

// helper function: is this machine little endian? CBF files are

bool little_endian()
{
  int i = 0x1;
  char b = ((u_i *) &i)[0].b[0];
  if (b == 0)
    {
      return false;
    }
  else
    {
      return true;
    }
}

// main functions

vector<char> compress(const vector<int> values)
{
  vector<char> packed(0);
  int current = 0;
  int delta, i;
  unsigned int j;
  bool le = little_endian();
  short s;
  char c;
  char * b;

  for (j = 0; j < values.size(); j++)
    {
      delta = values[j] - current;

      if ((-127 <= delta) && (delta <= 127))
	{
	  c = (char) delta;
	  packed.push_back(c);
	  current += delta;
	  continue;
	}

      packed.push_back(-128);

      if ((-32767 <= delta) && (delta <= 32767))
	{
	  s = (short) delta;
	  b = ((u_s *) & s)[0].b;

	  if (!le)
	    {
	      byte_swap_short(b);
	    }

	  packed.push_back(b[0]);
	  packed.push_back(b[1]);
	  current += delta;
	  continue;
	}

      s = -32768;
      b = ((u_s *) & s)[0].b;

      if (!le)
	{
	  byte_swap_short(b);
	}

      packed.push_back(b[0]);
      packed.push_back(b[1]);

      if ((-2147483647 <= delta) && (delta <= 2147483647))
	{
	  i = delta;
	  b = ((u_i *) & i)[0].b;

	  if (!le)
	    {
	      byte_swap_int(b);
	    }

	  packed.push_back(b[0]);
	  packed.push_back(b[1]);
	  packed.push_back(b[2]);
	  packed.push_back(b[3]);
	  current += delta;
	  continue;
	}

      /* FIXME I should not get here */

    }

  return packed;
}

vector<int> uncompress(const vector<char> packed)
{
  vector<int> values(0);
  int current = 0;
  unsigned int j = 0;
  short s;
  char c;
  int i;
  bool le = little_endian();

  while (j < packed.size())
    {
      c = packed[j];
      j += 1;

      if (c != -128)
	{
	  current += c;
	  values.push_back(current);
	  continue;
	}

      ((u_s *) & s)[0].b[0] = packed[j];
      ((u_s *) & s)[0].b[1] = packed[j + 1];
      j += 2;

      if (!le)
	{
	  byte_swap_short((char *) &s);
	}

      if (s != -32768)
	{
	  current += s;
	  values.push_back(current);
	  continue;
	}

      ((u_i *) & i)[0].b[0] = packed[j];
      ((u_i *) & i)[0].b[1] = packed[j + 1];
      ((u_i *) & i)[0].b[2] = packed[j + 2];
      ((u_i *) & i)[0].b[3] = packed[j + 3];
      j += 4;

      if (!le)
	{
	  byte_swap_int((char *) &i);
	}

      current += i;
      values.push_back(current);
    }

  return values;
}

// helper for timing tests

double ms(clock_t t1, clock_t t2)
{
  return 1000.0 * (t2 - t1) / CLOCKS_PER_SEC;
}

// demo / test code

int main(int argc,
	 char ** argv)
{

  vector<int> values(0);

  unsigned int j;
  unsigned int size = 4096 * 4096;
  clock_t start;

  start = clock();

  for (j = 0; j < size; j ++)
    {
      values.push_back((rand() & 0xffff));
    }

  cout << "Generating: " << ms(start, clock()) << endl;

  start = clock();
  vector<char> packed = compress(values);
  cout << "Packing:    " << ms(start, clock()) << endl;

  start = clock();
  vector<int> unpacked = uncompress(packed);
  cout << "Unpacking:  " << ms(start, clock()) << endl;

  for (j = 0; j < unpacked.size(); j ++)
    {
      if (unpacked[j] != values[j])
	{
	  cout << "Error for index " << j << endl;
	}
    }

  return 0;
}

<|endoftext|>