<commit_before>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * All rights reserved.                                                   *
 *                                                                        *
 * Primary Authors:                                                       *
 *   Indranil Das <indra.das@saha.ac.in>                                  *
 *                                                                        *
 * 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$ */

/** @file   AliHLTMUONTriggerReconstructorComponent.cxx
    @author Indranil Das
    @date
    @brief  Implementation of the trigger DDL reconstructor component. */

#include "AliHLTMUONTriggerReconstructorComponent.h"
#include "AliHLTMUONTriggerReconstructor.h"
#include "AliHLTMUONHitReconstructor.h"
#include "AliHLTMUONConstants.h"
#include "AliHLTMUONDataBlockWriter.h"
#include <cstdlib>
#include <cerrno>
#include <cassert>

namespace
{
	// This is a global object used for automatic component registration,
	// do not use this for calculation.
	AliHLTMUONTriggerReconstructorComponent gAliHLTMUONTriggerReconstructorComponent;

} // end of namespace

ClassImp(AliHLTMUONTriggerReconstructorComponent)

AliHLTMUONTriggerReconstructorComponent::AliHLTMUONTriggerReconstructorComponent() :
	fTrigRec(NULL),
	fDDLDir(""),
	fDDL(0),
	fWarnForUnexpecedBlock(false)
{
}

AliHLTMUONTriggerReconstructorComponent::~AliHLTMUONTriggerReconstructorComponent()
{
}

const char* AliHLTMUONTriggerReconstructorComponent::GetComponentID()
{
	return AliHLTMUONConstants::TriggerReconstructorId();
}

void AliHLTMUONTriggerReconstructorComponent::GetInputDataTypes( std::vector<AliHLTComponentDataType>& list)
{
	list.clear();
	list.push_back( AliHLTMUONConstants::TriggerDDLRawDataType() );
}

AliHLTComponentDataType AliHLTMUONTriggerReconstructorComponent::GetOutputDataType()
{
	return AliHLTMUONConstants::TriggerRecordsBlockDataType();
}

void AliHLTMUONTriggerReconstructorComponent::GetOutputDataSize(
		unsigned long& constBase, double& inputMultiplier
	)
{
	constBase = sizeof(AliHLTMUONTriggerRecordsBlockWriter::HeaderType);
	inputMultiplier = 1;
}

AliHLTComponent* AliHLTMUONTriggerReconstructorComponent::Spawn()
{
	return new AliHLTMUONTriggerReconstructorComponent;
}

int AliHLTMUONTriggerReconstructorComponent::DoInit(int argc, const char** argv)
{
  // perform initialization. We check whether our relative output size is
  // specified in the arguments.

  HLTInfo("Initialising DHLT Trigger Record Component");

  fWarnForUnexpecedBlock = false;
  fTrigRec = new AliHLTMUONTriggerReconstructor();

  // this is just to get rid of the warning "unused parameter"
  if (argc==0 && argv==NULL) {
    HLTError("Arguments missing, no arguments" );
  }

  char lutFileName[500],reglocFileName[500];

  int i = 0;
  char* cpErr;
  while ( i < argc )
    {
      HLTDebug("argv[%d] == %s", i, argv[i] );

      if ( !strcmp( argv[i], "lut" ) ) {
	if ( argc <= i+1 ) {
	  HLTError("LookupTable filename not specified" );
	  return EINVAL; /* Invalid argument */
	}

	sprintf(lutFileName,"%s",argv[i+1]);

	i += 2;
	continue;
      }// lut argument

      if ( !strcmp( argv[i], "ddl" ) ) {
	if ( argc <= i+1 ) {
	  HLTError("DDL number not specified" );
	  return EINVAL;  /* Invalid argument */
	}

	fDDL = strtoul( argv[i+1], &cpErr, 0 );
	if ( *cpErr )
	  {
	    HLTError("Cannot convert '%s' to DDL Number ", argv[i+1] );
	    return EINVAL;
	  }
	//fDDL = atoi(argv[i+1]);

	i += 2;
	continue;
      }// ddl argument

      if ( !strcmp( argv[i], "rawdir" ) ) {
	if ( argc <= i+1 ) {
	  HLTError("DDL directory not specified" );
	  return EINVAL;  /* Invalid argument */
	}

	fDDLDir = argv[i+1] ;
	i += 2;
	continue;
      }// ddl directory argument

      if ( !strcmp( argv[i], "reglocmap" ) ) {
	if ( argc <= i+1 ) {
	  HLTError("Regional to Local Card mapping  filename not specified" );
	  return EINVAL; /* Invalid argument */
	}

	sprintf(reglocFileName,"%s",argv[i+1]);

	i += 2;
	continue;
      }// regtolocalmap argument

      if ( !strcmp( argv[i], "-warn_on_unexpected_block" ) ) {
        fWarnForUnexpecedBlock = true;
	i++;
	continue;
      }

      HLTError("Unknown option '%s'", argv[i] );
      return EINVAL;

    }//while loop

    int lutline = fTrigRec->GetLutLine();
    AliHLTMUONHitReconstructor::DHLTLut* lookupTable = new AliHLTMUONHitReconstructor::DHLTLut[lutline];
    if(!ReadLookUpTable(lookupTable,lutFileName)){
      HLTError("Failed to read lut, lut cannot be read");
      return ENOENT ; /* No such file or directory */
    }else{

      fTrigRec->LoadLookUpTable(lookupTable,fDDL+AliHLTMUONTriggerReconstructor::GetkDDLOffSet());

      AliHLTMUONTriggerReconstructor::RegToLoc regToLocMap[128]; // 16(locCard)*8(regCard)
      if(!ReadRegToLocMap(regToLocMap,reglocFileName)){
	HLTError("Failed to read RegToLocMap file");
	return ENOENT ; /* No such file or directory */
      }

      if(!(fTrigRec->SetRegToLocCardMap(regToLocMap))){
	HLTError("Failed to assign RegToLocMap to TrigRec Class due to memory problem");
	return ENOMEM ; /*cannot allocate memory*/
      }

    }// reading lut

    delete []lookupTable;

    HLTInfo("Initialisation of DHLT Trigger Record Component is done");

    return 0;
}

int AliHLTMUONTriggerReconstructorComponent::DoDeinit()
{
	HLTInfo("Deinitialising DHLT Trigger Record Component");

	if(fTrigRec)
	{
		delete fTrigRec;
		fTrigRec = NULL;
	}
	return 0;
}

int AliHLTMUONTriggerReconstructorComponent::DoEvent(
		const AliHLTComponentEventData& evtData,
		const AliHLTComponentBlockData* blocks,
		AliHLTComponentTriggerData& trigData,
		AliHLTUInt8_t* outputPtr,
		AliHLTUInt32_t& size,
		std::vector<AliHLTComponentBlockData>& outputBlocks
	)
{
	// Process an event
	unsigned long totalSize = 0; // Amount of memory currently consumed in bytes.

	HLTDebug("Processing event %llu with %u input data blocks.",
		evtData.fEventID, evtData.fBlockCnt
	);

	// Loop over all input blocks in the event and run the trigger DDL
	// reconstruction algorithm on the raw data.
	for (AliHLTUInt32_t n = 0; n < evtData.fBlockCnt; n++)
	{
#ifdef __DEBUG
		char id[kAliHLTComponentDataTypefIDsize+1];
		for (int i = 0; i < kAliHLTComponentDataTypefIDsize; i++)
			id[i] = blocks[n].fDataType.fID[i];
		id[kAliHLTComponentDataTypefIDsize] = '\0';
		char origin[kAliHLTComponentDataTypefOriginSize+1];
		for (int i = 0; i < kAliHLTComponentDataTypefOriginSize; i++)
			origin[i] = blocks[n].fDataType.fOrigin[i];
		origin[kAliHLTComponentDataTypefOriginSize] = '\0';
#endif // __DEBUG
		HLTDebug("Handling block: %u, with fDataType.fID = '%s',"
			  " fDataType.fID = '%s', fPtr = %p and fSize = %u bytes.",
			n, static_cast<char*>(id), static_cast<char*>(origin),
			blocks[n].fPtr, blocks[n].fSize
		);

		if (blocks[n].fDataType != AliHLTMUONConstants::TriggerDDLRawDataType())
		{
			// Log a message indicating that we got a data block that we
			// do not know how to handle.
			char id[kAliHLTComponentDataTypefIDsize+1];
			for (int i = 0; i < kAliHLTComponentDataTypefIDsize; i++)
				id[i] = blocks[n].fDataType.fID[i];
			id[kAliHLTComponentDataTypefIDsize] = '\0';
			char origin[kAliHLTComponentDataTypefOriginSize+1];
			for (int i = 0; i < kAliHLTComponentDataTypefOriginSize; i++)
				origin[i] = blocks[n].fDataType.fOrigin[i];
			origin[kAliHLTComponentDataTypefOriginSize] = '\0';

			if (fWarnForUnexpecedBlock)
				HLTWarning("Received a data block of a type we can not handle: %s origin %s",
					static_cast<char*>(id), static_cast<char*>(origin)
				);
			else
				HLTDebug("Received a data block of a type we can not handle: %s origin %s",
					static_cast<char*>(id), static_cast<char*>(origin)
				);

			continue;
		}

		// Create a new output data block and initialise the header.
		AliHLTMUONTriggerRecordsBlockWriter block(outputPtr+totalSize, size-totalSize);
		if (not block.InitCommonHeader())
		{
			HLTError("There is not enough space in the output buffer for the new data block.",
				 " We require at least %u bytes, but have %u bytes left.",
				sizeof(AliHLTMUONTriggerRecordsBlockWriter::HeaderType),
				block.BufferSize()
			);
			break;
		}

		AliHLTUInt32_t totalDDLSize = blocks[n].fSize / sizeof(AliHLTUInt32_t);
		AliHLTUInt32_t ddlRawDataSize = totalDDLSize - fTrigRec->GetkDDLHeaderSize();
		AliHLTUInt32_t* buffer = reinterpret_cast<AliHLTUInt32_t*>(blocks[n].fPtr)
			+ fTrigRec->GetkDDLHeaderSize();
		AliHLTUInt32_t nofTrigRec = block.MaxNumberOfEntries();

		if (not fTrigRec->Run(buffer, ddlRawDataSize, block.GetArray(), nofTrigRec))
		{
			HLTError("Error while processing of trigger DDL reconstruction algorithm.");
			size = totalSize; // Must tell the framework how much buffer space was used.
			return EIO;
		}

		// nofTrigRec should now contain the number of triggers actually found
		// and filled into the output data block, so we can set this number.
		assert( nofTrigRec <= block.MaxNumberOfEntries() );
		block.SetNumberOfEntries(nofTrigRec);

		HLTDebug("Number of trigger records found is %d", nofTrigRec);

		// Fill a block data structure for our output block.
		AliHLTComponentBlockData bd;
		FillBlockData(bd);
		bd.fPtr = outputPtr;
		// This block's start (offset) is after all other blocks written so far.
		bd.fOffset = totalSize;
		bd.fSize = block.BytesUsed();
		bd.fDataType = AliHLTMUONConstants::TriggerRecordsBlockDataType();
		bd.fSpecification = blocks[n].fSpecification;
		outputBlocks.push_back(bd);

		HLTDebug("Created a new output data block at fPtr = %p,"
			  " with fOffset = %u (0x%.X) and fSize = %u bytes.",
			bd.fPtr, bd.fOffset, bd.fOffset, bd.fSize
		);

		// Increase the total amount of data written so far to our output memory.
		totalSize += block.BytesUsed();
	}

	// Finally we set the total size of output memory we consumed.
	size = totalSize;
	return 0;
}

bool AliHLTMUONTriggerReconstructorComponent::ReadLookUpTable(AliHLTMUONHitReconstructor::DHLTLut* lookupTable, const char* lutpath)
{
  if (fDDL < 0 || fDDL >= 2){
    HLTError("DDL number is out of range");
    return false;
  }

  int lutLine = fTrigRec->GetLutLine();

  FILE* fin = fopen(lutpath, "r");
  if (fin == NULL){
    HLTError("Failed to open file: %s",lutpath);
    return false;
  }

  for(int i=0;i<lutLine;i++){
    fscanf(
	   fin,
	   "%d\t%d\t%d\t%f\t%f\t%f\t%d\t%d\n",
	   &lookupTable[i].fIdManuChannel,
	   &lookupTable[i].fIX,
	   &lookupTable[i].fIY,
	   &lookupTable[i].fRealX,
	   &lookupTable[i].fRealY,
	   &lookupTable[i].fRealZ,
	   &lookupTable[i].fPcbZone,
	   &lookupTable[i].fPlane
	   );
  }

  fclose(fin);
  return true;
}

bool AliHLTMUONTriggerReconstructorComponent::ReadRegToLocMap(AliHLTMUONTriggerReconstructor::RegToLoc* regToLocMap,const char* reglocFileName)
{
  int iTrigDDL,iReg,iLoc,locId,switchWord,detElemId[4];
  int index;

  memset(regToLocMap,-1,128*sizeof(AliHLTMUONTriggerReconstructor::RegToLoc));

  char s[100];
  ifstream fin(reglocFileName);

  if(!fin){
    HLTError("Failed to open file %s",reglocFileName);
    return false;
  }

  while(fin.getline(s,100)){
    sscanf(s,"%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d",
	   &iTrigDDL,&iReg,&iLoc,&locId,&switchWord,&detElemId[0],&detElemId[1],&detElemId[2],&detElemId[3]);
    if(iTrigDDL==fDDL){
      index = iReg*16 + iLoc;
      regToLocMap[index].fTrigDDL = iTrigDDL ;
      regToLocMap[index].fRegId = iReg ;
      regToLocMap[index].fLoc = iLoc ;
      regToLocMap[index].fLocId = locId ;
      regToLocMap[index].fSwitch = switchWord ;
      for(int idet = 0; idet<4; idet++)
	regToLocMap[index].fDetElemId[idet] = detElemId[idet] ;
    }// if matches with fDDL
  }//file loop

  fin.close();
  return true;
}
<commit_msg>Temporary hack to prevent error messages during pathological cases with particular types of DDL input data.<commit_after>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * All rights reserved.                                                   *
 *                                                                        *
 * Primary Authors:                                                       *
 *   Indranil Das <indra.das@saha.ac.in>                                  *
 *                                                                        *
 * 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$ */

/** @file   AliHLTMUONTriggerReconstructorComponent.cxx
    @author Indranil Das
    @date
    @brief  Implementation of the trigger DDL reconstructor component. */

#include "AliHLTMUONTriggerReconstructorComponent.h"
#include "AliHLTMUONTriggerReconstructor.h"
#include "AliHLTMUONHitReconstructor.h"
#include "AliHLTMUONConstants.h"
#include "AliHLTMUONDataBlockWriter.h"
#include <cstdlib>
#include <cerrno>
#include <cassert>

namespace
{
	// This is a global object used for automatic component registration,
	// do not use this for calculation.
	AliHLTMUONTriggerReconstructorComponent gAliHLTMUONTriggerReconstructorComponent;

} // end of namespace

ClassImp(AliHLTMUONTriggerReconstructorComponent)

AliHLTMUONTriggerReconstructorComponent::AliHLTMUONTriggerReconstructorComponent() :
	fTrigRec(NULL),
	fDDLDir(""),
	fDDL(0),
	fWarnForUnexpecedBlock(false)
{
}

AliHLTMUONTriggerReconstructorComponent::~AliHLTMUONTriggerReconstructorComponent()
{
}

const char* AliHLTMUONTriggerReconstructorComponent::GetComponentID()
{
	return AliHLTMUONConstants::TriggerReconstructorId();
}

void AliHLTMUONTriggerReconstructorComponent::GetInputDataTypes( std::vector<AliHLTComponentDataType>& list)
{
	list.clear();
	list.push_back( AliHLTMUONConstants::TriggerDDLRawDataType() );
}

AliHLTComponentDataType AliHLTMUONTriggerReconstructorComponent::GetOutputDataType()
{
	return AliHLTMUONConstants::TriggerRecordsBlockDataType();
}

void AliHLTMUONTriggerReconstructorComponent::GetOutputDataSize(
		unsigned long& constBase, double& inputMultiplier
	)
{
	constBase = sizeof(AliHLTMUONTriggerRecordsBlockWriter::HeaderType);
	inputMultiplier = 100;
}

AliHLTComponent* AliHLTMUONTriggerReconstructorComponent::Spawn()
{
	return new AliHLTMUONTriggerReconstructorComponent;
}

int AliHLTMUONTriggerReconstructorComponent::DoInit(int argc, const char** argv)
{
  // perform initialization. We check whether our relative output size is
  // specified in the arguments.

  HLTInfo("Initialising DHLT Trigger Record Component");

  fWarnForUnexpecedBlock = false;
  fTrigRec = new AliHLTMUONTriggerReconstructor();

  // this is just to get rid of the warning "unused parameter"
  if (argc==0 && argv==NULL) {
    HLTError("Arguments missing, no arguments" );
  }

  char lutFileName[500],reglocFileName[500];

  int i = 0;
  char* cpErr;
  while ( i < argc )
    {
      HLTDebug("argv[%d] == %s", i, argv[i] );

      if ( !strcmp( argv[i], "lut" ) ) {
	if ( argc <= i+1 ) {
	  HLTError("LookupTable filename not specified" );
	  return EINVAL; /* Invalid argument */
	}

	sprintf(lutFileName,"%s",argv[i+1]);

	i += 2;
	continue;
      }// lut argument

      if ( !strcmp( argv[i], "ddl" ) ) {
	if ( argc <= i+1 ) {
	  HLTError("DDL number not specified" );
	  return EINVAL;  /* Invalid argument */
	}

	fDDL = strtoul( argv[i+1], &cpErr, 0 );
	if ( *cpErr )
	  {
	    HLTError("Cannot convert '%s' to DDL Number ", argv[i+1] );
	    return EINVAL;
	  }
	//fDDL = atoi(argv[i+1]);

	i += 2;
	continue;
      }// ddl argument

      if ( !strcmp( argv[i], "rawdir" ) ) {
	if ( argc <= i+1 ) {
	  HLTError("DDL directory not specified" );
	  return EINVAL;  /* Invalid argument */
	}

	fDDLDir = argv[i+1] ;
	i += 2;
	continue;
      }// ddl directory argument

      if ( !strcmp( argv[i], "reglocmap" ) ) {
	if ( argc <= i+1 ) {
	  HLTError("Regional to Local Card mapping  filename not specified" );
	  return EINVAL; /* Invalid argument */
	}

	sprintf(reglocFileName,"%s",argv[i+1]);

	i += 2;
	continue;
      }// regtolocalmap argument

      if ( !strcmp( argv[i], "-warn_on_unexpected_block" ) ) {
        fWarnForUnexpecedBlock = true;
	i++;
	continue;
      }

      HLTError("Unknown option '%s'", argv[i] );
      return EINVAL;

    }//while loop

    int lutline = fTrigRec->GetLutLine();
    AliHLTMUONHitReconstructor::DHLTLut* lookupTable = new AliHLTMUONHitReconstructor::DHLTLut[lutline];
    if(!ReadLookUpTable(lookupTable,lutFileName)){
      HLTError("Failed to read lut, lut cannot be read");
      return ENOENT ; /* No such file or directory */
    }else{

      fTrigRec->LoadLookUpTable(lookupTable,fDDL+AliHLTMUONTriggerReconstructor::GetkDDLOffSet());

      AliHLTMUONTriggerReconstructor::RegToLoc regToLocMap[128]; // 16(locCard)*8(regCard)
      if(!ReadRegToLocMap(regToLocMap,reglocFileName)){
	HLTError("Failed to read RegToLocMap file");
	return ENOENT ; /* No such file or directory */
      }

      if(!(fTrigRec->SetRegToLocCardMap(regToLocMap))){
	HLTError("Failed to assign RegToLocMap to TrigRec Class due to memory problem");
	return ENOMEM ; /*cannot allocate memory*/
      }

    }// reading lut

    delete []lookupTable;

    HLTInfo("Initialisation of DHLT Trigger Record Component is done");

    return 0;
}

int AliHLTMUONTriggerReconstructorComponent::DoDeinit()
{
	HLTInfo("Deinitialising DHLT Trigger Record Component");

	if(fTrigRec)
	{
		delete fTrigRec;
		fTrigRec = NULL;
	}
	return 0;
}

int AliHLTMUONTriggerReconstructorComponent::DoEvent(
		const AliHLTComponentEventData& evtData,
		const AliHLTComponentBlockData* blocks,
		AliHLTComponentTriggerData& trigData,
		AliHLTUInt8_t* outputPtr,
		AliHLTUInt32_t& size,
		std::vector<AliHLTComponentBlockData>& outputBlocks
	)
{
	// Process an event
	unsigned long totalSize = 0; // Amount of memory currently consumed in bytes.

	HLTDebug("Processing event %llu with %u input data blocks.",
		evtData.fEventID, evtData.fBlockCnt
	);

	// Loop over all input blocks in the event and run the trigger DDL
	// reconstruction algorithm on the raw data.
	for (AliHLTUInt32_t n = 0; n < evtData.fBlockCnt; n++)
	{
#ifdef __DEBUG
		char id[kAliHLTComponentDataTypefIDsize+1];
		for (int i = 0; i < kAliHLTComponentDataTypefIDsize; i++)
			id[i] = blocks[n].fDataType.fID[i];
		id[kAliHLTComponentDataTypefIDsize] = '\0';
		char origin[kAliHLTComponentDataTypefOriginSize+1];
		for (int i = 0; i < kAliHLTComponentDataTypefOriginSize; i++)
			origin[i] = blocks[n].fDataType.fOrigin[i];
		origin[kAliHLTComponentDataTypefOriginSize] = '\0';
#endif // __DEBUG
		HLTDebug("Handling block: %u, with fDataType.fID = '%s',"
			  " fDataType.fID = '%s', fPtr = %p and fSize = %u bytes.",
			n, static_cast<char*>(id), static_cast<char*>(origin),
			blocks[n].fPtr, blocks[n].fSize
		);

		if (blocks[n].fDataType != AliHLTMUONConstants::TriggerDDLRawDataType())
		{
			// Log a message indicating that we got a data block that we
			// do not know how to handle.
			char id[kAliHLTComponentDataTypefIDsize+1];
			for (int i = 0; i < kAliHLTComponentDataTypefIDsize; i++)
				id[i] = blocks[n].fDataType.fID[i];
			id[kAliHLTComponentDataTypefIDsize] = '\0';
			char origin[kAliHLTComponentDataTypefOriginSize+1];
			for (int i = 0; i < kAliHLTComponentDataTypefOriginSize; i++)
				origin[i] = blocks[n].fDataType.fOrigin[i];
			origin[kAliHLTComponentDataTypefOriginSize] = '\0';

			if (fWarnForUnexpecedBlock)
				HLTWarning("Received a data block of a type we can not handle: %s origin %s",
					static_cast<char*>(id), static_cast<char*>(origin)
				);
			else
				HLTDebug("Received a data block of a type we can not handle: %s origin %s",
					static_cast<char*>(id), static_cast<char*>(origin)
				);

			continue;
		}

		// Create a new output data block and initialise the header.
		AliHLTMUONTriggerRecordsBlockWriter block(outputPtr+totalSize, size-totalSize);
		if (not block.InitCommonHeader())
		{
			HLTError("There is not enough space in the output buffer for the new data block.",
				 " We require at least %u bytes, but have %u bytes left.",
				sizeof(AliHLTMUONTriggerRecordsBlockWriter::HeaderType),
				block.BufferSize()
			);
			break;
		}

		AliHLTUInt32_t totalDDLSize = blocks[n].fSize / sizeof(AliHLTUInt32_t);
		AliHLTUInt32_t ddlRawDataSize = totalDDLSize - fTrigRec->GetkDDLHeaderSize();
		AliHLTUInt32_t* buffer = reinterpret_cast<AliHLTUInt32_t*>(blocks[n].fPtr)
			+ fTrigRec->GetkDDLHeaderSize();
		AliHLTUInt32_t nofTrigRec = block.MaxNumberOfEntries();

		if (not fTrigRec->Run(buffer, ddlRawDataSize, block.GetArray(), nofTrigRec))
		{
			HLTError("Error while processing of trigger DDL reconstruction algorithm.");
			size = totalSize; // Must tell the framework how much buffer space was used.
			return EIO;
		}

		// nofTrigRec should now contain the number of triggers actually found
		// and filled into the output data block, so we can set this number.
		assert( nofTrigRec <= block.MaxNumberOfEntries() );
		block.SetNumberOfEntries(nofTrigRec);

		HLTDebug("Number of trigger records found is %d", nofTrigRec);

		// Fill a block data structure for our output block.
		AliHLTComponentBlockData bd;
		FillBlockData(bd);
		bd.fPtr = outputPtr;
		// This block's start (offset) is after all other blocks written so far.
		bd.fOffset = totalSize;
		bd.fSize = block.BytesUsed();
		bd.fDataType = AliHLTMUONConstants::TriggerRecordsBlockDataType();
		bd.fSpecification = blocks[n].fSpecification;
		outputBlocks.push_back(bd);

		HLTDebug("Created a new output data block at fPtr = %p,"
			  " with fOffset = %u (0x%.X) and fSize = %u bytes.",
			bd.fPtr, bd.fOffset, bd.fOffset, bd.fSize
		);

		// Increase the total amount of data written so far to our output memory.
		totalSize += block.BytesUsed();
	}

	// Finally we set the total size of output memory we consumed.
	size = totalSize;
	return 0;
}

bool AliHLTMUONTriggerReconstructorComponent::ReadLookUpTable(AliHLTMUONHitReconstructor::DHLTLut* lookupTable, const char* lutpath)
{
  if (fDDL < 0 || fDDL >= 2){
    HLTError("DDL number is out of range");
    return false;
  }

  int lutLine = fTrigRec->GetLutLine();

  FILE* fin = fopen(lutpath, "r");
  if (fin == NULL){
    HLTError("Failed to open file: %s",lutpath);
    return false;
  }

  for(int i=0;i<lutLine;i++){
    fscanf(
	   fin,
	   "%d\t%d\t%d\t%f\t%f\t%f\t%d\t%d\n",
	   &lookupTable[i].fIdManuChannel,
	   &lookupTable[i].fIX,
	   &lookupTable[i].fIY,
	   &lookupTable[i].fRealX,
	   &lookupTable[i].fRealY,
	   &lookupTable[i].fRealZ,
	   &lookupTable[i].fPcbZone,
	   &lookupTable[i].fPlane
	   );
  }

  fclose(fin);
  return true;
}

bool AliHLTMUONTriggerReconstructorComponent::ReadRegToLocMap(AliHLTMUONTriggerReconstructor::RegToLoc* regToLocMap,const char* reglocFileName)
{
  int iTrigDDL,iReg,iLoc,locId,switchWord,detElemId[4];
  int index;

  memset(regToLocMap,-1,128*sizeof(AliHLTMUONTriggerReconstructor::RegToLoc));

  char s[100];
  ifstream fin(reglocFileName);

  if(!fin){
    HLTError("Failed to open file %s",reglocFileName);
    return false;
  }

  while(fin.getline(s,100)){
    sscanf(s,"%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d",
	   &iTrigDDL,&iReg,&iLoc,&locId,&switchWord,&detElemId[0],&detElemId[1],&detElemId[2],&detElemId[3]);
    if(iTrigDDL==fDDL){
      index = iReg*16 + iLoc;
      regToLocMap[index].fTrigDDL = iTrigDDL ;
      regToLocMap[index].fRegId = iReg ;
      regToLocMap[index].fLoc = iLoc ;
      regToLocMap[index].fLocId = locId ;
      regToLocMap[index].fSwitch = switchWord ;
      for(int idet = 0; idet<4; idet++)
	regToLocMap[index].fDetElemId[idet] = detElemId[idet] ;
    }// if matches with fDDL
  }//file loop

  fin.close();
  return true;
}
<|endoftext|>


<commit_before>#include "tidyup_state_creators/stateCreatorArmsAtSide.h"
#include <pluginlib/class_list_macros.h>

//PLUGINLIB_DECLARE_CLASS(tidyup_state_creators, state_creator_arms_at_side,
//        tidyup_state_creators::StateCreatorArmsAtSide, continual_planning_executive::StateCreator)
PLUGINLIB_EXPORT_CLASS(tidyup_state_creators::StateCreatorArmsAtSide, continual_planning_executive::StateCreator)

namespace tidyup_state_creators
{
    StateCreatorArmsAtSide::StateCreatorArmsAtSide()
    {
    }
    StateCreatorArmsAtSide::~StateCreatorArmsAtSide()
    {
    }
    void StateCreatorArmsAtSide::initialize(const std::deque<std::string> & arguments)
    {
        ROS_ASSERT(arguments.size() == 3);
        service_name = arguments[0];
        predicate_name = arguments[1];
        predicate_value = arguments[2];
        ros::NodeHandle nh;
        client = nh.serviceClient<tidyup_msgs::ArmsAtSide>(service_name);
        client.waitForExistence();
    }

    bool StateCreatorArmsAtSide::fillState(SymbolicState & state)
    {
        tidyup_msgs::ArmsAtSide srv;
        if (! client.call(srv))
        {
            ROS_ERROR("service call to %s failed!", service_name.c_str());
            return false;
        }
        if (srv.response.right_arm)
            state.setObjectFluent(predicate_name, "right_arm", predicate_value);
        if (srv.response.left_arm)
            state.setObjectFluent(predicate_name, "left_arm", predicate_value);
        return true;
    }
};

<commit_msg>added comments<commit_after>#include "tidyup_state_creators/stateCreatorArmsAtSide.h"
#include <pluginlib/class_list_macros.h>

//PLUGINLIB_DECLARE_CLASS(tidyup_state_creators, state_creator_arms_at_side,
//        tidyup_state_creators::StateCreatorArmsAtSide, continual_planning_executive::StateCreator)
PLUGINLIB_EXPORT_CLASS(tidyup_state_creators::StateCreatorArmsAtSide, continual_planning_executive::StateCreator)

namespace tidyup_state_creators
{
    StateCreatorArmsAtSide::StateCreatorArmsAtSide()
    {
    }
    StateCreatorArmsAtSide::~StateCreatorArmsAtSide()
    {
    }
    void StateCreatorArmsAtSide::initialize(const std::deque<std::string> & arguments)
    {
        ROS_ASSERT(arguments.size() == 3);
        service_name = arguments[0];		// /tidyup/arms_at_side
        predicate_name = arguments[1];		// arm-state
        predicate_value = arguments[2]; 	// arm_at_side
        ros::NodeHandle nh;
        client = nh.serviceClient<tidyup_msgs::ArmsAtSide>(service_name);
        client.waitForExistence();
    }

    bool StateCreatorArmsAtSide::fillState(SymbolicState & state)
    {
        tidyup_msgs::ArmsAtSide srv;
        if (! client.call(srv))
        {
            ROS_ERROR("service call to %s failed!", service_name.c_str());
            return false;
        }
        if (srv.response.right_arm)
            state.setObjectFluent(predicate_name, "right_arm", predicate_value);
        if (srv.response.left_arm)
            state.setObjectFluent(predicate_name, "left_arm", predicate_value);
        return true;
    }
};

<|endoftext|>


<commit_before>/*
  This file is part of KDE Kontact.

  Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@kde.org>
  Copyright (c) 2002-2003 Daniel Molkentin <molkentin@kde.org>

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

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

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

#include "prefs.h"
#include "reminderclient.h"
#include "mainwindow.h"
#include "plugin.h"
#include "uniqueapphandler.h"

#include <pimapplication.h>

#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kstartupinfo.h>
#include <kuniqueapplication.h>
#include <kwindowsystem.h>
#include <kstandarddirs.h>
#include <ktoolinvocation.h>
#include <kservicetypetrader.h>

#include <QLabel>

#include <iostream>

using namespace std;

static const char description[] =
  I18N_NOOP( "KDE personal information manager" );

static const char version[] = "1.3";

class KontactApp : public
#ifdef Q_WS_WIN
KPIM::PimApplication
#else
KUniqueApplication
#endif
{
  Q_OBJECT
  public:
    KontactApp() : mMainWindow( 0 ), mSessionRestored( false ) {
      KIconLoader::global()->addAppDir( "kdepim" );
    }
    ~KontactApp() {}

    /*reimp*/ int newInstance();

    void setMainWindow( Kontact::MainWindow *window ) {
        mMainWindow = window;
        Kontact::UniqueAppHandler::setMainWidget( window );
    }
    void setSessionRestored( bool restored ) {
        mSessionRestored = restored;
    }

  public Q_SLOTS:
    void loadCommandLineOptionsForNewInstance();

  private:
    Kontact::MainWindow *mMainWindow;
    bool mSessionRestored;
};

static void listPlugins()
{
  KComponentData instance( "kontact" ); //Can't use KontactApp -- too late for adding cmdline opts

  KService::List offers = KServiceTypeTrader::self()->query(
    QString::fromLatin1( "Kontact/Plugin" ),
    QString( "[X-KDE-KontactPluginVersion] == %1" ).arg( KONTACT_PLUGIN_VERSION ) );
  for ( KService::List::Iterator it = offers.begin(); it != offers.end(); ++it ) {
    KService::Ptr service = (*it);
    // skip summary only plugins
    QVariant var = service->property( "X-KDE-KontactPluginHasPart" );
    if ( var.isValid() && var.toBool() == false ) {
      continue;
    }
    cout << service->library().remove( "kontact_" ).toLatin1().data() << endl;
  }
}

static void loadCommandLineOptions()
{
  KCmdLineOptions options;
  options.add( "module <module>", ki18n( "Start with a specific Kontact module" ) );
  options.add( "iconify", ki18n( "Start in iconified (minimized) mode" ) );
  options.add( "list", ki18n( "List all possible modules and exit" ) );
  KCmdLineArgs::addCmdLineOptions( options );
}

// Called by KUniqueApplication
void KontactApp::loadCommandLineOptionsForNewInstance()
{
  kDebug();
  KCmdLineArgs::reset(); // forget options defined by other "applications"
  loadCommandLineOptions(); // re-add the kontact options
}

int KontactApp::newInstance()
{
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  QString moduleName;
  if ( Kontact::Prefs::self()->forceStartupPlugin() ) {
    moduleName = Kontact::Prefs::self()->forcedStartupPlugin();
  }
  if ( args->isSet( "module" ) ) {
    moduleName = args->getOption( "module" );
  }
  if ( !mSessionRestored ) {
    if ( !mMainWindow ) {
      mMainWindow = new Kontact::MainWindow();
      if ( !moduleName.isEmpty() ) {
        mMainWindow->setActivePluginModule( moduleName );
      }
      mMainWindow->show();
      Kontact::UniqueAppHandler::setMainWidget( mMainWindow );
      // --iconify is needed in kontact, although kstart can do that too,
      // because kstart returns immediately so it's too early to talk D-Bus to the app.
      if ( args->isSet( "iconify" ) ) {
        KWindowSystem::minimizeWindow( mMainWindow->winId(), false /*no animation*/);
      }
    } else {
      if ( !moduleName.isEmpty() ) {
        mMainWindow->setActivePluginModule( moduleName );
      }
    }
  }

  KPIM::ReminderClient reminderclient;
  reminderclient.startDaemon();

  // Handle startup notification and window activation
  // (The first time it will do nothing except note that it was called)
  return KUniqueApplication::newInstance();
}

int main( int argc, char **argv )
{
  KAboutData about( "kontact", 0, ki18n( "Kontact" ), version, ki18n(description),
                    KAboutData::License_GPL,
                    ki18n( "(C) 2001-2008 The Kontact developers" ),
                    KLocalizedString(), "http://kontact.org" );

  about.addAuthor( ki18n( "Allen Winter" ), KLocalizedString(), "winter@kde.org" );
  about.addAuthor( ki18n( "Rafael Fernández López" ), KLocalizedString(), "ereslibre@kde.org" );
  about.addAuthor( ki18n( "Daniel Molkentin" ), KLocalizedString(), "molkentin@kde.org" );
  about.addAuthor( ki18n( "Don Sanders" ), KLocalizedString(), "sanders@kde.org" );
  about.addAuthor( ki18n( "Cornelius Schumacher" ), KLocalizedString(), "schumacher@kde.org" );
  about.addAuthor( ki18n( "Tobias K\303\266nig" ), KLocalizedString(), "tokoe@kde.org" );
  about.addAuthor( ki18n( "David Faure" ), KLocalizedString(), "faure@kde.org" );
  about.addAuthor( ki18n( "Ingo Kl\303\266cker" ), KLocalizedString(), "kloecker@kde.org" );
  about.addAuthor( ki18n( "Sven L\303\274ppken" ), KLocalizedString(), "sven@kde.org" );
  about.addAuthor( ki18n( "Zack Rusin" ), KLocalizedString(), "zack@kde.org" );
  about.addAuthor( ki18n( "Matthias Hoelzer-Kluepfel" ),
                   ki18n( "Original Author" ), "mhk@kde.org" );
  about.setOrganizationDomain( "kde.org" );

  KCmdLineArgs::init( argc, argv, &about );

  loadCommandLineOptions();
  KUniqueApplication::addCmdLineOptions();
  KCmdLineArgs::addStdCmdLineOptions();

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if ( args->isSet( "list" ) ) {
    listPlugins();
    return 0;
  }

  if ( !KontactApp::start() ) {
    // Already running, brought to the foreground.
    return 0;
  }

  KontactApp app;

  // Qt doesn't treat the system tray as a window, and therefore Qt would quit
  // the event loop when an error message is clicked away while Kontact is in the
  // tray.
  // Rely on KGlobal::ref() and KGlobal::deref() instead, like we did in KDE3.
  // See http://bugs.kde.org/show_bug.cgi?id=163479
  QApplication::setQuitOnLastWindowClosed( false );

  if ( app.restoringSession() ) {
     // There can only be one main window
    if ( KMainWindow::canBeRestored( 1 ) ) {
      Kontact::MainWindow *mainWindow = new Kontact::MainWindow();
      app.setMainWindow( mainWindow );
      app.setSessionRestored( true );
      mainWindow->show();
      mainWindow->restore( 1 );
    }
  }

  bool ret = app.exec();
  qDeleteAll( KMainWindow::memberList() );

  return ret;
}

#include "main.moc"
<commit_msg>Bump version.<commit_after>/*
  This file is part of KDE Kontact.

  Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@kde.org>
  Copyright (c) 2002-2003 Daniel Molkentin <molkentin@kde.org>

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

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

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

#include "prefs.h"
#include "reminderclient.h"
#include "mainwindow.h"
#include "plugin.h"
#include "uniqueapphandler.h"

#include <pimapplication.h>

#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kstartupinfo.h>
#include <kuniqueapplication.h>
#include <kwindowsystem.h>
#include <kstandarddirs.h>
#include <ktoolinvocation.h>
#include <kservicetypetrader.h>

#include <QLabel>

#include <iostream>

using namespace std;

static const char description[] =
  I18N_NOOP( "KDE personal information manager" );

static const char version[] = "1.4";

class KontactApp : public
#ifdef Q_WS_WIN
KPIM::PimApplication
#else
KUniqueApplication
#endif
{
  Q_OBJECT
  public:
    KontactApp() : mMainWindow( 0 ), mSessionRestored( false ) {
      KIconLoader::global()->addAppDir( "kdepim" );
    }
    ~KontactApp() {}

    /*reimp*/ int newInstance();

    void setMainWindow( Kontact::MainWindow *window ) {
        mMainWindow = window;
        Kontact::UniqueAppHandler::setMainWidget( window );
    }
    void setSessionRestored( bool restored ) {
        mSessionRestored = restored;
    }

  public Q_SLOTS:
    void loadCommandLineOptionsForNewInstance();

  private:
    Kontact::MainWindow *mMainWindow;
    bool mSessionRestored;
};

static void listPlugins()
{
  KComponentData instance( "kontact" ); //Can't use KontactApp -- too late for adding cmdline opts

  KService::List offers = KServiceTypeTrader::self()->query(
    QString::fromLatin1( "Kontact/Plugin" ),
    QString( "[X-KDE-KontactPluginVersion] == %1" ).arg( KONTACT_PLUGIN_VERSION ) );
  for ( KService::List::Iterator it = offers.begin(); it != offers.end(); ++it ) {
    KService::Ptr service = (*it);
    // skip summary only plugins
    QVariant var = service->property( "X-KDE-KontactPluginHasPart" );
    if ( var.isValid() && var.toBool() == false ) {
      continue;
    }
    cout << service->library().remove( "kontact_" ).toLatin1().data() << endl;
  }
}

static void loadCommandLineOptions()
{
  KCmdLineOptions options;
  options.add( "module <module>", ki18n( "Start with a specific Kontact module" ) );
  options.add( "iconify", ki18n( "Start in iconified (minimized) mode" ) );
  options.add( "list", ki18n( "List all possible modules and exit" ) );
  KCmdLineArgs::addCmdLineOptions( options );
}

// Called by KUniqueApplication
void KontactApp::loadCommandLineOptionsForNewInstance()
{
  kDebug();
  KCmdLineArgs::reset(); // forget options defined by other "applications"
  loadCommandLineOptions(); // re-add the kontact options
}

int KontactApp::newInstance()
{
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  QString moduleName;
  if ( Kontact::Prefs::self()->forceStartupPlugin() ) {
    moduleName = Kontact::Prefs::self()->forcedStartupPlugin();
  }
  if ( args->isSet( "module" ) ) {
    moduleName = args->getOption( "module" );
  }
  if ( !mSessionRestored ) {
    if ( !mMainWindow ) {
      mMainWindow = new Kontact::MainWindow();
      if ( !moduleName.isEmpty() ) {
        mMainWindow->setActivePluginModule( moduleName );
      }
      mMainWindow->show();
      Kontact::UniqueAppHandler::setMainWidget( mMainWindow );
      // --iconify is needed in kontact, although kstart can do that too,
      // because kstart returns immediately so it's too early to talk D-Bus to the app.
      if ( args->isSet( "iconify" ) ) {
        KWindowSystem::minimizeWindow( mMainWindow->winId(), false /*no animation*/);
      }
    } else {
      if ( !moduleName.isEmpty() ) {
        mMainWindow->setActivePluginModule( moduleName );
      }
    }
  }

  KPIM::ReminderClient reminderclient;
  reminderclient.startDaemon();

  // Handle startup notification and window activation
  // (The first time it will do nothing except note that it was called)
  return KUniqueApplication::newInstance();
}

int main( int argc, char **argv )
{
  KAboutData about( "kontact", 0, ki18n( "Kontact" ), version, ki18n(description),
                    KAboutData::License_GPL,
                    ki18n( "(C) 2001-2008 The Kontact developers" ),
                    KLocalizedString(), "http://kontact.org" );

  about.addAuthor( ki18n( "Allen Winter" ), KLocalizedString(), "winter@kde.org" );
  about.addAuthor( ki18n( "Rafael Fernández López" ), KLocalizedString(), "ereslibre@kde.org" );
  about.addAuthor( ki18n( "Daniel Molkentin" ), KLocalizedString(), "molkentin@kde.org" );
  about.addAuthor( ki18n( "Don Sanders" ), KLocalizedString(), "sanders@kde.org" );
  about.addAuthor( ki18n( "Cornelius Schumacher" ), KLocalizedString(), "schumacher@kde.org" );
  about.addAuthor( ki18n( "Tobias K\303\266nig" ), KLocalizedString(), "tokoe@kde.org" );
  about.addAuthor( ki18n( "David Faure" ), KLocalizedString(), "faure@kde.org" );
  about.addAuthor( ki18n( "Ingo Kl\303\266cker" ), KLocalizedString(), "kloecker@kde.org" );
  about.addAuthor( ki18n( "Sven L\303\274ppken" ), KLocalizedString(), "sven@kde.org" );
  about.addAuthor( ki18n( "Zack Rusin" ), KLocalizedString(), "zack@kde.org" );
  about.addAuthor( ki18n( "Matthias Hoelzer-Kluepfel" ),
                   ki18n( "Original Author" ), "mhk@kde.org" );
  about.setOrganizationDomain( "kde.org" );

  KCmdLineArgs::init( argc, argv, &about );

  loadCommandLineOptions();
  KUniqueApplication::addCmdLineOptions();
  KCmdLineArgs::addStdCmdLineOptions();

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if ( args->isSet( "list" ) ) {
    listPlugins();
    return 0;
  }

  if ( !KontactApp::start() ) {
    // Already running, brought to the foreground.
    return 0;
  }

  KontactApp app;

  // Qt doesn't treat the system tray as a window, and therefore Qt would quit
  // the event loop when an error message is clicked away while Kontact is in the
  // tray.
  // Rely on KGlobal::ref() and KGlobal::deref() instead, like we did in KDE3.
  // See http://bugs.kde.org/show_bug.cgi?id=163479
  QApplication::setQuitOnLastWindowClosed( false );

  if ( app.restoringSession() ) {
     // There can only be one main window
    if ( KMainWindow::canBeRestored( 1 ) ) {
      Kontact::MainWindow *mainWindow = new Kontact::MainWindow();
      app.setMainWindow( mainWindow );
      app.setSessionRestored( true );
      mainWindow->show();
      mainWindow->restore( 1 );
    }
  }

  bool ret = app.exec();
  qDeleteAll( KMainWindow::memberList() );

  return ret;
}

#include "main.moc"
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <queue>

#include <string>
#include <sstream>
#include <iomanip>

#include <boost/thread.hpp>
#include <boost/bind.hpp>

#include <Eigen/Eigen>

#include <ros/ros.h>
#include <tms_msg_ss/SkeletonArray.h>
#include <tms_msg_ss/SkeletonStreamWrapper.h>

#include <for_model01.h>

#define MAX_USERS 12

#define IDENTIFY_RANGE 0.5  // [m]
#define FRONT_ANGLE_RANGE 130  // [deg]

//-----------------------------------------------------------------------------
template <class T>
std::string to_str(const T& t)
{
  std::stringstream ss;
  ss << t;
  return ss.str();
}

//-----------------------------------------------------------------------------
inline tms_msg_ss::Skeleton initialize_skeleton()
{
  tms_msg_ss::Skeleton ret;
  ret.user_id = -1;
  ret.position.resize(JOINT_NUM);
  ret.orientation.resize(JOINT_NUM);
  ret.confidence.resize(JOINT_NUM);
  for(int i=0; i<JOINT_NUM; i++)
  {
    ret.position[i].x = 0.0;
    ret.position[i].y = 0.0;
    ret.position[i].z = 0.0;
    ret.orientation[i].w = 1.0;
    ret.orientation[i].x = 0.0;
    ret.orientation[i].y = 0.0;
    ret.orientation[i].z = 0.0;
    ret.confidence[i] = 0;
  }
  return ret;
}

//-----------------------------------------------------------------------------
class SkeletonIntegrator
{
  public:
    SkeletonIntegrator(const std::vector<int>& camera, ros::NodeHandle& nh);
    ~SkeletonIntegrator();

    void callback(const tms_msg_ss::SkeletonStreamWrapper::ConstPtr& msg);
    void run();
  private:
    ros::NodeHandle& nh_;
    std::vector<int> array;
    tms_msg_ss::SkeletonArray out;
    int tracked_skeleton_num_;
    int tracking_validity[MAX_USERS];
    std::vector<std::map<int, bool> > bFaceStateTable;  // [user_index, [camera_id, is_front?]]

    void listenSkeletonStream();

    // For Debug
    void showStatus();
};

//-----------------------------------------------------------------------------
SkeletonIntegrator::SkeletonIntegrator(const std::vector<int> &camera, ros::NodeHandle& nh) :
  array(camera),
  tracked_skeleton_num_(0),
  nh_(nh)
{
  out.data.resize(MAX_USERS);
  bFaceStateTable.resize(MAX_USERS);
  for (int i = 0; i < MAX_USERS; i++)
  {
    out.data[i] = initialize_skeleton();
    tracking_validity[i] = 0;
    for (std::vector<int>::iterator it = array.begin(); it != array.end(); it++)
    {
      bFaceStateTable[i][*it] = false;
    }
  }
  return;
}

//-----------------------------------------------------------------------------
SkeletonIntegrator::~SkeletonIntegrator()
{
  return;
}

//-----------------------------------------------------------------------------
void SkeletonIntegrator::callback(const tms_msg_ss::SkeletonStreamWrapper::ConstPtr& msg)
{
  tms_msg_ss::Skeleton skeleton = msg->skeleton;
  tms_msg_ss::CameraPosture camera_posture = msg->camera_posture;

  // Transform to world coordinate
  Eigen::Vector3f translation(
      camera_posture.translation.x,
      camera_posture.translation.y,
      camera_posture.translation.z);
  Eigen::Quaternionf rotation(
      camera_posture.rotation.w,
      camera_posture.rotation.x,
      camera_posture.rotation.y,
      camera_posture.rotation.z);

  Eigen::Matrix3f rot_mat = rotation.matrix();
  ROS_INFO("Camera %d status:\n  \
      Position in world:\n    \
      (%3.4f, %3.4f, %3.4f)\n  \
      Rotation in world:\n    \
      x-axis (%3.4f, %3.4f, %3.4f)\n    \
      y-axis (%3.4f, %3.4f, %3.4f)\n    \
      z-axis (%3.4f, %3.4f, %3.4f)\n\
      \n",
        msg->camera_number,
        translation[0], translation[1], translation[2],
        rot_mat(0, 0), rot_mat(1, 0), rot_mat(2, 0),
        rot_mat(0, 1), rot_mat(1, 1), rot_mat(2, 1),
        rot_mat(0, 2), rot_mat(1, 2), rot_mat(2, 2));

  tms_msg_ss::Skeleton integrated_skeleton;
  integrated_skeleton.user_id = 0;
  integrated_skeleton.position.resize(JOINT_NUM);
  integrated_skeleton.orientation.resize(JOINT_NUM);
  integrated_skeleton.confidence.resize(JOINT_NUM);
  for(int i=0; i<JOINT_NUM; i++)
  {
    Eigen::Vector3f pos(
        skeleton.position[i].x,
        skeleton.position[i].y,
        skeleton.position[i].z);
    Eigen::Quaternionf ori(
        skeleton.orientation[i].w,
        skeleton.orientation[i].x,
        skeleton.orientation[i].y,
        skeleton.orientation[i].z);
    pos = rotation.matrix() * pos + translation;
    ori = rotation * ori;
    integrated_skeleton.position[i].x = pos[0];
    integrated_skeleton.position[i].y = pos[1];
    integrated_skeleton.position[i].z = pos[2];
    integrated_skeleton.orientation[i].w = ori.w();
    integrated_skeleton.orientation[i].x = ori.x();
    integrated_skeleton.orientation[i].y = ori.y();
    integrated_skeleton.orientation[i].z = ori.z();
    integrated_skeleton.confidence[i] = skeleton.confidence[i];
  }

  // identify received skeleton
  int i;
  int index, user_id;
  for (i = 0; i < out.data.size(); i++)
  {
    Eigen::Vector3f v1(
        integrated_skeleton.position[SpineMid].x,
        integrated_skeleton.position[SpineMid].y,
        integrated_skeleton.position[SpineMid].z);
    Eigen::Vector3f v2(
        out.data[i].position[SpineMid].x,
        out.data[i].position[SpineMid].y,
        out.data[i].position[SpineMid].z);
    if ((v1-v2).norm() <= IDENTIFY_RANGE)
    {
      index = i;
      user_id = out.data[i].user_id;
      break;
    }
  }
  if (i == MAX_USERS)  // If not detected yet, treat as new skeleton
  {
    user_id = tracked_skeleton_num_;
    for (i=0; i < MAX_USERS; i++)
    {
      if (out.data[i].user_id < 0)  // user_id < 0 means empty
      {
        index = i;
        break;
      }
    }
    if (i == MAX_USERS)
    {
      ROS_INFO("SkeletonIntegrator: Data buffer is full. Discarding data.");
      return;
    }
    tracked_skeleton_num_++;
  }

  // Update skeleton state
  bool &table_ref = bFaceStateTable[index][msg->camera_number];
  integrated_skeleton.user_id = user_id;
  if (msg->face_state == 2)
  {
    // Log face state and storage as valid skeleton
    table_ref = true;
  }
  else
  {
    if (table_ref)
    {
      Eigen::Quaternionf skeleton_rotation(
          integrated_skeleton.orientation[SpineBase].w,
          integrated_skeleton.orientation[SpineBase].x,
          integrated_skeleton.orientation[SpineBase].y,
          integrated_skeleton.orientation[SpineBase].z);
      Eigen::Vector3f skeleton_direction_cam;
      Eigen::Vector3f camera_direction_cam;
      // Calculate skeleton direction (front is y)
      Eigen::Vector3f tmp_x(
          skeleton.position[HipRight].x - skeleton.position[HipLeft].x,
          skeleton.position[HipRight].y - skeleton.position[HipLeft].y,
          skeleton.position[HipRight].z - skeleton.position[HipLeft].z);
      Eigen::Vector3f tmp_z(
          skeleton.position[SpineMid].x - skeleton.position[SpineBase].x,
          skeleton.position[SpineMid].y - skeleton.position[SpineBase].y,
          skeleton.position[SpineMid].z - skeleton.position[SpineBase].z);
      skeleton_direction_cam = (tmp_z.cross(tmp_x)).normalized();
      camera_direction_cam = Eigen::Vector3f::UnitZ();
      // Check that skeleton is facing the camera
      if (skeleton_direction_cam.dot(camera_direction_cam) <= cos(FRONT_ANGLE_RANGE*M_PI/180))
      {
        // storage as valid skeleton
      }
      else
      {
        table_ref = false;
        // Allow only move
        const tms_msg_ss::Skeleton& last_state = out.data[index];
        Eigen::Vector3d translation(
            integrated_skeleton.position[SpineMid].x - last_state.position[SpineMid].x,
            integrated_skeleton.position[SpineMid].y - last_state.position[SpineMid].y,
            integrated_skeleton.position[SpineMid].z - last_state.position[SpineMid].z);
        for (int i = 0; i < integrated_skeleton.position.size(); i++)
        {
          integrated_skeleton.position[i].x = last_state.position[i].x + translation[0];
          integrated_skeleton.position[i].y = last_state.position[i].y + translation[1];
          integrated_skeleton.position[i].z = last_state.position[i].z + translation[2];
        }
      }
    }
    else
    {
      // Allow only move
      const tms_msg_ss::Skeleton& last_state = out.data[index];
      Eigen::Vector3d translation(
          integrated_skeleton.position[SpineMid].x - last_state.position[SpineMid].x,
          integrated_skeleton.position[SpineMid].y - last_state.position[SpineMid].y,
          integrated_skeleton.position[SpineMid].z - last_state.position[SpineMid].z);
      for (int i = 0; i < integrated_skeleton.position.size(); i++)
      {
        integrated_skeleton.position[i].x = last_state.position[i].x + translation[0];
        integrated_skeleton.position[i].y = last_state.position[i].y + translation[1];
        integrated_skeleton.position[i].z = last_state.position[i].z + translation[2];
      }
    }
  }
  out.data[index] = integrated_skeleton;
  tracking_validity[index] = 15;  // reflesh validity

  return;
}

//-----------------------------------------------------------------------------
void SkeletonIntegrator::run()
{
  ros::Rate loop_late(10);

  static boost::thread thread_listener(
      boost::bind(&SkeletonIntegrator::listenSkeletonStream, this));

  ros::Publisher pub =
    nh_.advertise<tms_msg_ss::SkeletonArray>(
        "integrated_skeleton_stream", 1);

  while (ros::ok())
  {
    pub.publish(out);
    for (int i = 0; i<MAX_USERS; i++)
    {
      // decrease validity of skeleton whenever publish
      if (tracking_validity[i] > 0)
      {
        tracking_validity[i]--;
      }

      // eliminate invalid skeletons
      if (tracking_validity[i] == 0)
      {
        out.data[i] = initialize_skeleton();
        for (std::vector<int>::iterator camera_id = array.begin(); camera_id != array.end(); camera_id++)
        {
          bFaceStateTable[i][*camera_id] = false;
        }
      }
    }

    showStatus();
    ros::spinOnce();
    loop_late.sleep();
  }

  return;
}

//-----------------------------------------------------------------------------
void SkeletonIntegrator::listenSkeletonStream()
{
  ros::Rate loop_late(10);
  std::vector<ros::Subscriber> sub(array.size());

  std::cout << "Subscribe ===" << std::endl;
  for (int i=0; i < array.size(); i++)
  {
    std::string topic_name("skeleton_stream_wrapper");
    sub[i] =nh_.subscribe(topic_name.append(to_str<int>(array[i])),
        1,&SkeletonIntegrator::callback, this);
  }

  ros::spin();

  return;
}

//-----------------------------------------------------------------------------
void SkeletonIntegrator::showStatus()
{
  std::stringstream ss;
  ss.fill(' ');

  ss << "User ID" << std::endl;
  for (int i = 0; i < MAX_USERS; i++) { ss << "|" << std::setw(5) << i; }
  ss << "|" << std::endl;
  for (int i = 0; i < MAX_USERS; i++) { ss << "|" << std::setw(5) << out.data[i].user_id; }
  ss << "|" << std::endl << std::endl;;

  ss << "Validity table" << std::endl;
  for (int i = 0; i < MAX_USERS; i++) { ss << "|" << std::setw(2) << i; }
  ss << "|" << std::endl;
  for (int i = 0; i < MAX_USERS; i++) { ss << "|" << std::setw(2) << tracking_validity[i]; }
  ss << "|" << std::endl << std::endl;

  ss << "Face state table" << std::endl;
  for (std::vector<int>::iterator it = array.begin(); it != array.end(); it++)
  {
    if (*it == 0) {continue;}
    ss << "|" << std::setw(2) << *it <<  "|";
    for (int i = 0; i < MAX_USERS; i++)
    {
      if (bFaceStateTable[i][*it])
      {
        ss << "T|";
      }
      else
      {
        ss << "F|";
      }
    }
    ss << std::endl;
  }

  ROS_INFO("%s", ss.str().c_str());
  return;
}

//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
  std::vector<int> cameraID_array;

  ros::init(argc, argv, "skeleton_integrator");

  ros::NodeHandle nh;

  std::string using_numbers_str;
  if (!nh.getParam("using_numbers", using_numbers_str))
  {
    ROS_INFO("SkeletonIntegrator: Need some camera id as arguments. Exiting...");
    return -1;
  }

  std::stringstream ss(using_numbers_str);
  std::string buffer;
  while (std::getline(ss, buffer, ' '))
  {
    cameraID_array.push_back(atoi(buffer.c_str()));
  }

  SkeletonIntegrator integrator(cameraID_array, nh);

  integrator.run();

  return 0;
}
<commit_msg>tms_ss_kinect_v2: try 001<commit_after>#include <iostream>
#include <vector>
#include <queue>

#include <string>
#include <sstream>
#include <iomanip>

#include <boost/thread.hpp>
#include <boost/bind.hpp>

#include <Eigen/Eigen>

#include <ros/ros.h>
#include <tms_msg_ss/SkeletonArray.h>
#include <tms_msg_ss/SkeletonStreamWrapper.h>

#include <for_model01.h>

#define MAX_USERS 12

#define IDENTIFY_RANGE 0.5  // [m]
#define FRONT_ANGLE_RANGE 130  // [deg]

//-----------------------------------------------------------------------------
template <class T>
std::string to_str(const T& t)
{
  std::stringstream ss;
  ss << t;
  return ss.str();
}

//-----------------------------------------------------------------------------
inline tms_msg_ss::Skeleton initialize_skeleton()
{
  tms_msg_ss::Skeleton ret;
  ret.user_id = -1;
  ret.position.resize(JOINT_NUM);
  ret.orientation.resize(JOINT_NUM);
  ret.confidence.resize(JOINT_NUM);
  for(int i=0; i<JOINT_NUM; i++)
  {
    ret.position[i].x = 0.0;
    ret.position[i].y = 0.0;
    ret.position[i].z = 0.0;
    ret.orientation[i].w = 1.0;
    ret.orientation[i].x = 0.0;
    ret.orientation[i].y = 0.0;
    ret.orientation[i].z = 0.0;
    ret.confidence[i] = 0;
  }
  return ret;
}

//-----------------------------------------------------------------------------
class SkeletonIntegrator
{
  public:
    SkeletonIntegrator(const std::vector<int>& camera, ros::NodeHandle& nh);
    ~SkeletonIntegrator();

    void callback(const tms_msg_ss::SkeletonStreamWrapper::ConstPtr& msg);
    void run();
  private:
    ros::NodeHandle& nh_;
    std::vector<int> array;  // using camera's id array
    tms_msg_ss::SkeletonArray out;
    int tracked_skeleton_num_;
    int tracking_validity[MAX_USERS];

    std::vector<std::map<int, bool> > bFaceStateTable;  // [user_index, [camera_id, is_front?]]
    std::vector<std::pair<int, float> > storage_evaluation;  // [user_index, [camera_id, value]]

    void listenSkeletonStream();

    // For Debug
    void showStatus();
};

//-----------------------------------------------------------------------------
SkeletonIntegrator::SkeletonIntegrator(const std::vector<int> &camera, ros::NodeHandle& nh) :
  array(camera),
  tracked_skeleton_num_(0),
  nh_(nh)
{
  out.data.resize(MAX_USERS);
  bFaceStateTable.resize(MAX_USERS);
  for (int i = 0; i < MAX_USERS; i++)
  {
    out.data[i] = initialize_skeleton();
    tracking_validity[i] = 0;
    for (std::vector<int>::iterator it = array.begin(); it != array.end(); it++)
    {
      bFaceStateTable[i][*it] = false;
    }
    storage_evaluation.push_back(std::pair<int, float>(-1, 1));
  }
  return;
}

//-----------------------------------------------------------------------------
SkeletonIntegrator::~SkeletonIntegrator()
{
  return;
}

//-----------------------------------------------------------------------------
void SkeletonIntegrator::callback(const tms_msg_ss::SkeletonStreamWrapper::ConstPtr& msg)
{
  tms_msg_ss::Skeleton skeleton = msg->skeleton;
  tms_msg_ss::CameraPosture camera_posture = msg->camera_posture;

  // Transform to world coordinate
  Eigen::Vector3f translation(
      camera_posture.translation.x,
      camera_posture.translation.y,
      camera_posture.translation.z);
  Eigen::Quaternionf rotation(
      camera_posture.rotation.w,
      camera_posture.rotation.x,
      camera_posture.rotation.y,
      camera_posture.rotation.z);

  Eigen::Matrix3f rot_mat = rotation.matrix();
  ROS_INFO("Camera %d status:\n  \
      Position in world:\n    \
      (%3.4f, %3.4f, %3.4f)\n  \
      Rotation in world:\n    \
      x-axis (%3.4f, %3.4f, %3.4f)\n    \
      y-axis (%3.4f, %3.4f, %3.4f)\n    \
      z-axis (%3.4f, %3.4f, %3.4f)\n\
      \n",
        msg->camera_number,
        translation[0], translation[1], translation[2],
        rot_mat(0, 0), rot_mat(1, 0), rot_mat(2, 0),
        rot_mat(0, 1), rot_mat(1, 1), rot_mat(2, 1),
        rot_mat(0, 2), rot_mat(1, 2), rot_mat(2, 2));

  tms_msg_ss::Skeleton integrated_skeleton;
  integrated_skeleton.user_id = 0;
  integrated_skeleton.position.resize(JOINT_NUM);
  integrated_skeleton.orientation.resize(JOINT_NUM);
  integrated_skeleton.confidence.resize(JOINT_NUM);
  for(int i=0; i<JOINT_NUM; i++)
  {
    Eigen::Vector3f pos(
        skeleton.position[i].x,
        skeleton.position[i].y,
        skeleton.position[i].z);
    Eigen::Quaternionf ori(
        skeleton.orientation[i].w,
        skeleton.orientation[i].x,
        skeleton.orientation[i].y,
        skeleton.orientation[i].z);
    pos = rotation.matrix() * pos + translation;
    ori = rotation * ori;
    integrated_skeleton.position[i].x = pos[0];
    integrated_skeleton.position[i].y = pos[1];
    integrated_skeleton.position[i].z = pos[2];
    integrated_skeleton.orientation[i].w = ori.w();
    integrated_skeleton.orientation[i].x = ori.x();
    integrated_skeleton.orientation[i].y = ori.y();
    integrated_skeleton.orientation[i].z = ori.z();
    integrated_skeleton.confidence[i] = skeleton.confidence[i];
  }

  // identify received skeleton
  int i;
  int index, user_id;
  for (i = 0; i < out.data.size(); i++)
  {
    Eigen::Vector3f v1(
        integrated_skeleton.position[SpineMid].x,
        integrated_skeleton.position[SpineMid].y,
        integrated_skeleton.position[SpineMid].z);
    Eigen::Vector3f v2(
        out.data[i].position[SpineMid].x,
        out.data[i].position[SpineMid].y,
        out.data[i].position[SpineMid].z);
    if ((v1-v2).norm() <= IDENTIFY_RANGE)
    {
      index = i;
      user_id = out.data[i].user_id;
      break;
    }
  }
  if (i == MAX_USERS)  // If not detected yet, treat as new skeleton
  {
    user_id = tracked_skeleton_num_;
    for (i=0; i < MAX_USERS; i++)
    {
      if (out.data[i].user_id < 0)  // user_id < 0 means empty
      {
        index = i;
        break;
      }
    }
    if (i == MAX_USERS)
    {
      ROS_INFO("SkeletonIntegrator: Data buffer is full. Discarding data.");
      return;
    }
    tracked_skeleton_num_++;
  }

  // Update skeleton state
  bool &table_ref = bFaceStateTable[index][msg->camera_number];
  integrated_skeleton.user_id = user_id;

  // Calculate skeleton direction (front is y)
  Eigen::Vector3f tmp_x(
      skeleton.position[HipRight].x - skeleton.position[HipLeft].x,
      skeleton.position[HipRight].y - skeleton.position[HipLeft].y,
      skeleton.position[HipRight].z - skeleton.position[HipLeft].z);
  Eigen::Vector3f tmp_z(
      skeleton.position[SpineMid].x - skeleton.position[SpineBase].x,
      skeleton.position[SpineMid].y - skeleton.position[SpineBase].y,
      skeleton.position[SpineMid].z - skeleton.position[SpineBase].z);
  Eigen::Vector3f skeleton_direction_cam;
  Eigen::Vector3f camera_direction_cam;
  skeleton_direction_cam = (tmp_z.cross(tmp_x)).normalized();
  camera_direction_cam = Eigen::Vector3f::UnitZ();
  float dot_skeleton_camera = skeleton_direction_cam.dot(camera_direction_cam);

  if (msg->face_state == 2)
  {
    // Log face state and storage as valid skeleton
    table_ref = true;
  }
  else
  {
    if (table_ref)
    {
      Eigen::Quaternionf skeleton_rotation(
          integrated_skeleton.orientation[SpineBase].w,
          integrated_skeleton.orientation[SpineBase].x,
          integrated_skeleton.orientation[SpineBase].y,
          integrated_skeleton.orientation[SpineBase].z);
      // Check that skeleton is facing the camera
      if (dot_skeleton_camera <= cos(FRONT_ANGLE_RANGE*M_PI/180))
      {
        // storage as valid skeleton
      }
      else
      {
        table_ref = false;
        // Allow only move
        const tms_msg_ss::Skeleton& last_state = out.data[index];
        Eigen::Vector3d translation(
            integrated_skeleton.position[SpineMid].x - last_state.position[SpineMid].x,
            integrated_skeleton.position[SpineMid].y - last_state.position[SpineMid].y,
            integrated_skeleton.position[SpineMid].z - last_state.position[SpineMid].z);
        for (int i = 0; i < integrated_skeleton.position.size(); i++)
        {
          integrated_skeleton.position[i].x = last_state.position[i].x + translation[0];
          integrated_skeleton.position[i].y = last_state.position[i].y + translation[1];
          integrated_skeleton.position[i].z = last_state.position[i].z + translation[2];
        }
      }
    }
    else
    {
      // Allow only move
      const tms_msg_ss::Skeleton& last_state = out.data[index];
      Eigen::Vector3d translation(
          integrated_skeleton.position[SpineMid].x - last_state.position[SpineMid].x,
          integrated_skeleton.position[SpineMid].y - last_state.position[SpineMid].y,
          integrated_skeleton.position[SpineMid].z - last_state.position[SpineMid].z);
      for (int i = 0; i < integrated_skeleton.position.size(); i++)
      {
        integrated_skeleton.position[i].x = last_state.position[i].x + translation[0];
        integrated_skeleton.position[i].y = last_state.position[i].y + translation[1];
        integrated_skeleton.position[i].z = last_state.position[i].z + translation[2];
      }
    }
  }

  // Choose better data
  if (msg->camera_number == storage_evaluation[index].first ||
      dot_skeleton_camera <= storage_evaluation[index].second)
  {
    out.data[index] = integrated_skeleton;
    tracking_validity[index] = 15;  // reflesh validity
    // Update evaluation
    storage_evaluation[index].first = msg->camera_number;
    storage_evaluation[index].second = dot_skeleton_camera;
  }

  return;
}

//-----------------------------------------------------------------------------
void SkeletonIntegrator::run()
{
  ros::Rate loop_late(10);

  static boost::thread thread_listener(
      boost::bind(&SkeletonIntegrator::listenSkeletonStream, this));

  ros::Publisher pub =
    nh_.advertise<tms_msg_ss::SkeletonArray>(
        "integrated_skeleton_stream", 1);

  while (ros::ok())
  {
    pub.publish(out);
    for (int i = 0; i<MAX_USERS; i++)
    {
      // decrease validity of skeleton whenever publish
      if (tracking_validity[i] > 0)
      {
        tracking_validity[i]--;
      }

      // eliminate invalid skeletons
      if (tracking_validity[i] == 0)
      {
        out.data[i] = initialize_skeleton();
        for (std::vector<int>::iterator camera_id = array.begin(); camera_id != array.end(); camera_id++)
        {
          bFaceStateTable[i][*camera_id] = false;
        }
      }
    }

    showStatus();
    ros::spinOnce();
    loop_late.sleep();
  }

  return;
}

//-----------------------------------------------------------------------------
void SkeletonIntegrator::listenSkeletonStream()
{
  ros::Rate loop_late(10);
  std::vector<ros::Subscriber> sub(array.size());

  std::cout << "Subscribe ===" << std::endl;
  for (int i=0; i < array.size(); i++)
  {
    std::string topic_name("skeleton_stream_wrapper");
    sub[i] =nh_.subscribe(topic_name.append(to_str<int>(array[i])),
        1,&SkeletonIntegrator::callback, this);
  }

  ros::spin();

  return;
}

//-----------------------------------------------------------------------------
void SkeletonIntegrator::showStatus()
{
  std::stringstream ss;
  ss.fill(' ');

  ss << "User ID" << std::endl;
  for (int i = 0; i < MAX_USERS; i++) { ss << "|" << std::setw(5) << i; }
  ss << "|" << std::endl;
  for (int i = 0; i < MAX_USERS; i++) { ss << "|" << std::setw(5) << out.data[i].user_id; }
  ss << "|" << std::endl << std::endl;;

  ss << "Validity table" << std::endl;
  for (int i = 0; i < MAX_USERS; i++) { ss << "|" << std::setw(2) << i; }
  ss << "|" << std::endl;
  for (int i = 0; i < MAX_USERS; i++) { ss << "|" << std::setw(2) << tracking_validity[i]; }
  ss << "|" << std::endl << std::endl;

  ss << "Face state table" << std::endl;
  for (std::vector<int>::iterator it = array.begin(); it != array.end(); it++)
  {
    if (*it == 0) {continue;}
    ss << "|" << std::setw(2) << *it <<  "|";
    for (int i = 0; i < MAX_USERS; i++)
    {
      if (bFaceStateTable[i][*it])
      {
        ss << "T|";
      }
      else
      {
        ss << "F|";
      }
    }
    ss << std::endl;
  }

  ROS_INFO("%s", ss.str().c_str());
  return;
}

//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
  std::vector<int> cameraID_array;

  ros::init(argc, argv, "skeleton_integrator");

  ros::NodeHandle nh;

  std::string using_numbers_str;
  if (!nh.getParam("using_numbers", using_numbers_str))
  {
    ROS_INFO("SkeletonIntegrator: Need some camera id as arguments. Exiting...");
    return -1;
  }

  std::stringstream ss(using_numbers_str);
  std::string buffer;
  while (std::getline(ss, buffer, ' '))
  {
    cameraID_array.push_back(atoi(buffer.c_str()));
  }

  SkeletonIntegrator integrator(cameraID_array, nh);

  integrator.run();

  return 0;
}
<|endoftext|>


<commit_before>#include "ImagePanel.h"

#include <set>

using namespace std;

vector< wxRect > GetCoverage( const wxRect& viewport, const wxRect& canvas, const wxSize& gridSize )
{
    const wxRect clippedViewport( canvas.Intersect( viewport ) );

    vector< wxRect > coverage;
    const int top    = clippedViewport.GetTop()    / gridSize.y;
    const int bottom = clippedViewport.GetBottom() / gridSize.y;
    const int left   = clippedViewport.GetLeft()   / gridSize.x;
    const int right  = clippedViewport.GetRight()  / gridSize.x;
    for( int y = top; y <= bottom; ++y )
    {
        for( int x = left; x <= right; ++x )
        {
            const wxRect candidate( x * gridSize.x, y * gridSize.y, gridSize.x, gridSize.y );
            const wxRect clipped( canvas.Intersect( candidate ) );
            coverage.push_back( clipped );
        }
    }
    return coverage;
}

template< typename T >
T clamp( const T& val, const T& minVal, const T& maxVal )
{
    if( val < minVal )  return minVal;
    if( val > maxVal )  return maxVal;
    return val;
}

wxPoint ClampPosition( const wxRect& viewport, const wxRect& extent )
{
    const wxSize delta( viewport.GetSize() - extent.GetSize() );

    wxPoint newTopLeft( viewport.GetPosition() );

    if( delta.x < 0 )
    {
        // viewport smaller than extent
        int minX = extent.GetPosition().x;
        int maxX = ( extent.GetPosition().x + extent.GetSize().x ) - viewport.GetSize().x;
        newTopLeft.x = clamp( newTopLeft.x, minX, maxX );
    }
    else
    {
        // viewport larger than extent
        newTopLeft.x = extent.GetPosition().x - ( delta.x / 2 );
    }

    if( delta.y < 0 )
    {
        // viewport smaller than extent
        int minY = extent.GetPosition().y;
        int maxY = ( extent.GetPosition().y + extent.GetSize().y ) - viewport.GetSize().y;
        newTopLeft.y = clamp( newTopLeft.y, minY, maxY );
    }
    else
    {
        // viewport larger than extent
        newTopLeft.y = extent.GetPosition().y - ( delta.y / 2 );
    }

    return newTopLeft;
}

wxImagePanel::wxImagePanel( wxWindow* parent )
    : wxWindow( parent, wxID_ANY )
    , mBitmapCache( 128 )   // ~135MB for 128 512x512x4 byte tiles
    , mPosition( 0, 0 )
    , mScale( 1.0 )
    , mImageFactory( this )
{
    // for wxAutoBufferedPaintDC
    SetBackgroundStyle( wxBG_STYLE_PAINT );

    SetBackgroundColour( *wxBLACK );

    Bind( wxEVT_SIZE        , &wxImagePanel::OnSize         , this );
    Bind( wxEVT_PAINT       , &wxImagePanel::OnPaint        , this );
    Bind( wxEVT_KEY_DOWN    , &wxImagePanel::OnKeyDown      , this );
    Bind( wxEVT_KEY_UP      , &wxImagePanel::OnKeyUp        , this );
    Bind( wxEVT_LEFT_DOWN   , &wxImagePanel::OnButtonDown   , this );
    Bind( wxEVT_RIGHT_DOWN  , &wxImagePanel::OnButtonDown   , this );
    Bind( wxEVT_MIDDLE_DOWN , &wxImagePanel::OnButtonDown   , this );
    Bind( wxEVT_MOTION      , &wxImagePanel::OnMotion       , this );
    Bind( wxEVT_THREAD      , &wxImagePanel::OnThread       , this );

    mStipple = wxBitmap( wxImage( "background.png" ) );
}

void wxImagePanel::OnSize( wxSizeEvent& event )
{
    mPosition = ClampPosition( mPosition );

    // invalidate entire panel since we need to redraw everything
    Refresh( true );

    // skip the event so sizers can do their thing
    event.Skip();
}

void wxImagePanel::OnButtonDown( wxMouseEvent& event )
{
    if( event.LeftDown() )
    {
        mLeftPositionStart = mPosition;
        mLeftMouseStart = event.GetPosition();
    }
}

void wxImagePanel::OnMotion( wxMouseEvent& event )
{
    if( event.LeftIsDown() && event.Dragging() )
    {
        wxPoint newPos( mLeftPositionStart - ( event.GetPosition() - mLeftMouseStart ) );
        if( newPos != mPosition )
        {
            ScrollToPosition( newPos );
        }
    }
}

void wxImagePanel::OnIdle( wxIdleEvent & )
{
    wxPoint newPos( mPosition );
    const int step = wxGetKeyState( WXK_CONTROL ) ? 10 : 1;
    if( wxGetKeyState( WXK_LEFT  ) )    newPos += step * wxPoint( -1,  0 );
    if( wxGetKeyState( WXK_RIGHT ) )    newPos += step * wxPoint(  1,  0 );
    if( wxGetKeyState( WXK_UP    ) )    newPos += step * wxPoint(  0, -1 );
    if( wxGetKeyState( WXK_DOWN  ) )    newPos += step * wxPoint(  0,  1 );

    if( newPos == mPosition )
    {
        Unbind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );
        return;
    }

    ScrollToPosition( newPos );

    //event.RequestMore( true );
    //wxMilliSleep( 1 );
}

void wxImagePanel::OnKeyDown( wxKeyEvent& event )
{
    switch( event.GetKeyCode() )
    {
        case WXK_LEFT:
        case WXK_RIGHT:
        case WXK_UP:
        case WXK_DOWN:
            Bind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );
            break;
        default:
            break;
    }
    event.Skip();
}

wxPoint wxImagePanel::ClampPosition( const wxPoint& newPos )
{
    if( NULL == mImage )
    {
        return newPos;
    }

    const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );
    return ::ClampPosition
        (
        wxRect( newPos, GetSize() ),
        wxRect( wxPoint(0,0), scaledSize )
        );
}

void wxImagePanel::OnKeyUp( wxKeyEvent& event )
{
    if( NULL == mImage )
    {
        return;
    }

    switch( event.GetKeyCode() )
    {
        case '=':
        case WXK_ADD:
        case WXK_NUMPAD_ADD:
            SetScale( mScale * 1.1 );
            break;
        case '-':
        case WXK_SUBTRACT:
        case WXK_NUMPAD_SUBTRACT:
            SetScale( mScale / 1.1 );
            break;
        case 'X':
        case WXK_NUMPAD_MULTIPLY:
            {
                const int iMax = max( mImage->GetWidth(), mImage->GetHeight() );
                const int wMin = min( GetSize().x, GetSize().y );
                SetScale( wMin / (double)iMax );
            }
            break;
        case 'Z':
        case WXK_NUMPAD_DIVIDE:
            SetScale( 1.0 );
            break;
        default:
            break;
    }
}

void wxImagePanel::ScrollToPosition( const wxPoint& newPos )
{
    const wxPoint clamped = ClampPosition( newPos );
    wxPoint delta( clamped - mPosition );
    ScrollWindow( -delta.x, -delta.y );
    mPosition = clamped;
}

void wxImagePanel::OnPaint( wxPaintEvent& )
{
    wxPaintDC dc(this);
    //wxAutoBufferedPaintDC dc( this );

    dc.SetDeviceOrigin( -mPosition.x, -mPosition.y );

    dc.Clear();

    if( NULL == mImage )
    {
        return;
    }

    const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );
    const wxRect scaledRect( wxPoint( 0, 0 ), scaledSize );
    const wxSize gridSize( TILE_SIZE, TILE_SIZE );

    // get the set of tiles we need to draw
    set< wxRect, wxRectCmp > covered;
    for( wxRegionIterator upd( GetUpdateRegion() ); upd.HaveRects(); ++upd )
    {
        wxRect rect( upd.GetRect() );
        rect.SetPosition( rect.GetPosition() + mPosition );

        const vector< wxRect > ret = GetCoverage
            (
            rect.Inflate( 1.1, 1.1 ),
            scaledRect,
            gridSize
            );
        covered.insert( ret.begin(), ret.end() );
    }

    dc.SetBrush( wxBrush( mStipple ) );
    dc.SetPen( *wxTRANSPARENT_PEN );

    for( const wxRect& rect : covered )
    {
        wxBitmapPtr bmpPtr;
        if( !mBitmapCache.get( bmpPtr, rect ) )
        {
            if( mQueuedRects.end() == mQueuedRects.find( rect ) )
            {
                mQueuedRects.insert( rect );
                mImageFactory.AddRect( rect );
            }
        }
        else
        {
            dc.DrawRectangle( rect );
            dc.DrawBitmap( *bmpPtr, rect.GetPosition() );
        }
    }
}

void wxImagePanel::SetImage( wxSharedPtr< LinearImage > newImage )
{
    mImage = newImage;
    mQueuedRects.clear();
    mImageFactory.SetImage( mImage, mScale );
    mPosition = ClampPosition( mPosition );
}

void wxImagePanel::SetScale( const double newScale )
{
    mScale = newScale;
    mBitmapCache.clear();
    mPosition = ClampPosition( mPosition );

    // invalidate entire panel since we need to redraw everything
    Refresh( true );

    if( NULL == mImage )
    {
        return;
    }

    mQueuedRects.clear();
    mImageFactory.SetScale( mScale );
}

void wxImagePanel::OnThread( wxThreadEvent& )
{
    wxRect rect;
    SrgbImagePtr image;
    while( mImageFactory.GetImage( rect, image ) )
    {
        wxBitmapPtr bmp
            (
            new wxBitmap
                (
                image->mAlpha.empty()
                ? wxImage( rect.GetWidth(), rect.GetHeight(), &image->mColor[0], true )
                : wxImage( rect.GetWidth(), rect.GetHeight(), &image->mColor[0], &image->mAlpha[0], true )
                )
            );
        mBitmapCache.insert( rect, bmp );

        mQueuedRects.erase( rect );

        const wxRect target( rect.GetPosition() - mPosition, rect.GetSize() );
        const wxRect clipped( GetRect().Intersect( target ) );
        RefreshRect( clipped, true );
    }

    // todo: needed/wanted?
    //Update();
}
<commit_msg>Expand viewing area by 50% in each dimension<commit_after>#include "ImagePanel.h"

#include <set>

using namespace std;

vector< wxRect > GetCoverage( const wxRect& viewport, const wxRect& canvas, const wxSize& gridSize )
{
    const wxRect clippedViewport( canvas.Intersect( viewport ) );

    vector< wxRect > coverage;
    const int top    = clippedViewport.GetTop()    / gridSize.y;
    const int bottom = clippedViewport.GetBottom() / gridSize.y;
    const int left   = clippedViewport.GetLeft()   / gridSize.x;
    const int right  = clippedViewport.GetRight()  / gridSize.x;
    for( int y = top; y <= bottom; ++y )
    {
        for( int x = left; x <= right; ++x )
        {
            const wxRect candidate( x * gridSize.x, y * gridSize.y, gridSize.x, gridSize.y );
            const wxRect clipped( canvas.Intersect( candidate ) );
            coverage.push_back( clipped );
        }
    }
    return coverage;
}

template< typename T >
T clamp( const T& val, const T& minVal, const T& maxVal )
{
    if( val < minVal )  return minVal;
    if( val > maxVal )  return maxVal;
    return val;
}

wxPoint ClampPosition( const wxRect& viewport, const wxRect& extent )
{
    const wxSize delta( viewport.GetSize() - extent.GetSize() );

    wxPoint newTopLeft( viewport.GetPosition() );

    if( delta.x < 0 )
    {
        // viewport smaller than extent
        int minX = extent.GetPosition().x;
        int maxX = ( extent.GetPosition().x + extent.GetSize().x ) - viewport.GetSize().x;
        newTopLeft.x = clamp( newTopLeft.x, minX, maxX );
    }
    else
    {
        // viewport larger than extent
        newTopLeft.x = extent.GetPosition().x - ( delta.x / 2 );
    }

    if( delta.y < 0 )
    {
        // viewport smaller than extent
        int minY = extent.GetPosition().y;
        int maxY = ( extent.GetPosition().y + extent.GetSize().y ) - viewport.GetSize().y;
        newTopLeft.y = clamp( newTopLeft.y, minY, maxY );
    }
    else
    {
        // viewport larger than extent
        newTopLeft.y = extent.GetPosition().y - ( delta.y / 2 );
    }

    return newTopLeft;
}

wxImagePanel::wxImagePanel( wxWindow* parent )
    : wxWindow( parent, wxID_ANY )
    , mBitmapCache( 128 )   // ~135MB for 128 512x512x4 byte tiles
    , mPosition( 0, 0 )
    , mScale( 1.0 )
    , mImageFactory( this )
{
    // for wxAutoBufferedPaintDC
    SetBackgroundStyle( wxBG_STYLE_PAINT );

    SetBackgroundColour( *wxBLACK );

    Bind( wxEVT_SIZE        , &wxImagePanel::OnSize         , this );
    Bind( wxEVT_PAINT       , &wxImagePanel::OnPaint        , this );
    Bind( wxEVT_KEY_DOWN    , &wxImagePanel::OnKeyDown      , this );
    Bind( wxEVT_KEY_UP      , &wxImagePanel::OnKeyUp        , this );
    Bind( wxEVT_LEFT_DOWN   , &wxImagePanel::OnButtonDown   , this );
    Bind( wxEVT_RIGHT_DOWN  , &wxImagePanel::OnButtonDown   , this );
    Bind( wxEVT_MIDDLE_DOWN , &wxImagePanel::OnButtonDown   , this );
    Bind( wxEVT_MOTION      , &wxImagePanel::OnMotion       , this );
    Bind( wxEVT_THREAD      , &wxImagePanel::OnThread       , this );

    mStipple = wxBitmap( wxImage( "background.png" ) );
}

void wxImagePanel::OnSize( wxSizeEvent& event )
{
    mPosition = ClampPosition( mPosition );

    // invalidate entire panel since we need to redraw everything
    Refresh( true );

    // skip the event so sizers can do their thing
    event.Skip();
}

void wxImagePanel::OnButtonDown( wxMouseEvent& event )
{
    if( event.LeftDown() )
    {
        mLeftPositionStart = mPosition;
        mLeftMouseStart = event.GetPosition();
    }
}

void wxImagePanel::OnMotion( wxMouseEvent& event )
{
    if( event.LeftIsDown() && event.Dragging() )
    {
        wxPoint newPos( mLeftPositionStart - ( event.GetPosition() - mLeftMouseStart ) );
        if( newPos != mPosition )
        {
            ScrollToPosition( newPos );
        }
    }
}

void wxImagePanel::OnIdle( wxIdleEvent & )
{
    wxPoint newPos( mPosition );
    const int step = wxGetKeyState( WXK_CONTROL ) ? 10 : 1;
    if( wxGetKeyState( WXK_LEFT  ) )    newPos += step * wxPoint( -1,  0 );
    if( wxGetKeyState( WXK_RIGHT ) )    newPos += step * wxPoint(  1,  0 );
    if( wxGetKeyState( WXK_UP    ) )    newPos += step * wxPoint(  0, -1 );
    if( wxGetKeyState( WXK_DOWN  ) )    newPos += step * wxPoint(  0,  1 );

    if( newPos == mPosition )
    {
        Unbind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );
        return;
    }

    ScrollToPosition( newPos );

    //event.RequestMore( true );
    //wxMilliSleep( 1 );
}

void wxImagePanel::OnKeyDown( wxKeyEvent& event )
{
    switch( event.GetKeyCode() )
    {
        case WXK_LEFT:
        case WXK_RIGHT:
        case WXK_UP:
        case WXK_DOWN:
            Bind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );
            break;
        default:
            break;
    }
    event.Skip();
}

wxPoint wxImagePanel::ClampPosition( const wxPoint& newPos )
{
    if( NULL == mImage )
    {
        return newPos;
    }

    const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );
    return ::ClampPosition
        (
        wxRect( newPos, GetSize() ),
        wxRect( wxPoint(0,0), scaledSize )
        );
}

void wxImagePanel::OnKeyUp( wxKeyEvent& event )
{
    if( NULL == mImage )
    {
        return;
    }

    switch( event.GetKeyCode() )
    {
        case '=':
        case WXK_ADD:
        case WXK_NUMPAD_ADD:
            SetScale( mScale * 1.1 );
            break;
        case '-':
        case WXK_SUBTRACT:
        case WXK_NUMPAD_SUBTRACT:
            SetScale( mScale / 1.1 );
            break;
        case 'X':
        case WXK_NUMPAD_MULTIPLY:
            {
                const int iMax = max( mImage->GetWidth(), mImage->GetHeight() );
                const int wMin = min( GetSize().x, GetSize().y );
                SetScale( wMin / (double)iMax );
            }
            break;
        case 'Z':
        case WXK_NUMPAD_DIVIDE:
            SetScale( 1.0 );
            break;
        default:
            break;
    }
}

void wxImagePanel::ScrollToPosition( const wxPoint& newPos )
{
    const wxPoint clamped = ClampPosition( newPos );
    wxPoint delta( clamped - mPosition );
    ScrollWindow( -delta.x, -delta.y );
    mPosition = clamped;
}

void wxImagePanel::OnPaint( wxPaintEvent& )
{
    wxPaintDC dc(this);
    //wxAutoBufferedPaintDC dc( this );

    dc.SetDeviceOrigin( -mPosition.x, -mPosition.y );

    dc.Clear();

    if( NULL == mImage )
    {
        return;
    }

    const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );
    const wxRect scaledRect( wxPoint( 0, 0 ), scaledSize );
    const wxSize gridSize( TILE_SIZE, TILE_SIZE );

    // get the set of tiles we need to draw
    set< wxRect, wxRectCmp > covered;
    for( wxRegionIterator upd( GetUpdateRegion() ); upd.HaveRects(); ++upd )
    {
        wxRect rect( upd.GetRect() );
        rect.SetPosition( rect.GetPosition() + mPosition );

        const vector< wxRect > ret = GetCoverage
            (
            rect.Inflate( rect.width * 1.5, rect.height * 1.5 ),
            scaledRect,
            gridSize
            );
        covered.insert( ret.begin(), ret.end() );
    }

    dc.SetBrush( wxBrush( mStipple ) );
    dc.SetPen( *wxTRANSPARENT_PEN );

    for( const wxRect& rect : covered )
    {
        wxBitmapPtr bmpPtr;
        if( !mBitmapCache.get( bmpPtr, rect ) )
        {
            if( mQueuedRects.end() == mQueuedRects.find( rect ) )
            {
                mQueuedRects.insert( rect );
                mImageFactory.AddRect( rect );
            }
        }
        else
        {
            dc.DrawRectangle( rect );
            dc.DrawBitmap( *bmpPtr, rect.GetPosition() );
        }
    }
}

void wxImagePanel::SetImage( wxSharedPtr< LinearImage > newImage )
{
    mImage = newImage;
    mQueuedRects.clear();
    mImageFactory.SetImage( mImage, mScale );
    mPosition = ClampPosition( mPosition );
}

void wxImagePanel::SetScale( const double newScale )
{
    mScale = newScale;
    mBitmapCache.clear();
    mPosition = ClampPosition( mPosition );

    // invalidate entire panel since we need to redraw everything
    Refresh( true );

    if( NULL == mImage )
    {
        return;
    }

    mQueuedRects.clear();
    mImageFactory.SetScale( mScale );
}

void wxImagePanel::OnThread( wxThreadEvent& )
{
    wxRect rect;
    SrgbImagePtr image;
    while( mImageFactory.GetImage( rect, image ) )
    {
        wxBitmapPtr bmp
            (
            new wxBitmap
                (
                image->mAlpha.empty()
                ? wxImage( rect.GetWidth(), rect.GetHeight(), &image->mColor[0], true )
                : wxImage( rect.GetWidth(), rect.GetHeight(), &image->mColor[0], &image->mAlpha[0], true )
                )
            );
        mBitmapCache.insert( rect, bmp );

        mQueuedRects.erase( rect );

        const wxRect target( rect.GetPosition() - mPosition, rect.GetSize() );
        const wxRect clipped( GetRect().Intersect( target ) );
        RefreshRect( clipped, true );
    }

    // todo: needed/wanted?
    //Update();
}
<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iostream>
#include <vector>

#include "tensorflow/contrib/tensorboard/db/schema.h"
#include "tensorflow/contrib/tensorboard/db/summary_db_writer.h"
#include "tensorflow/core/lib/db/sqlite.h"
#include "tensorflow/core/lib/io/record_reader.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/core/util/event.pb.h"

namespace tensorflow {
namespace {

template <typename T>
string AddCommas(T n) {
  static_assert(std::is_integral<T>::value, "is_integral");
  string s = strings::StrCat(n);
  if (s.size() > 3) {
    int extra = s.size() / 3 - (s.size() % 3 == 0 ? 1 : 0);
    s.append(extra, 'X');
    int c = 0;
    for (int i = s.size() - 1; i > 0; --i) {
      s[i] = s[i - extra];
      if (++c % 3 == 0) {
        s[--i] = ',';
        --extra;
      }
    }
  }
  return s;
}

int main(int argc, char* argv[]) {
  string path;
  string events;
  string experiment_name;
  string run_name;
  string user_name;
  std::vector<Flag> flag_list = {
      Flag("db", &path, "Path of SQLite DB file"),
      Flag("events", &events, "TensorFlow record proto event log file"),
      Flag("experiment_name", &experiment_name, "The DB experiment_name value"),
      Flag("run_name", &run_name, "The DB run_name value"),
      Flag("user_name", &user_name, "The DB user_name value"),
  };
  string usage = Flags::Usage(argv[0], flag_list);
  bool parse_result = Flags::Parse(&argc, argv, flag_list);
  if (!parse_result || path.empty()) {
    std::cerr << "The loader tool imports tf.Event record files, created by\n"
              << "SummaryFileWriter, into the sorts of SQLite database files\n"
              << "created by SummaryDbWriter.\n\n"
              << "In addition to the flags below, the environment variables\n"
              << "defined by core/lib/db/sqlite.cc can also be set.\n\n"
              << usage;
    return -1;
  }
  port::InitMain(argv[0], &argc, &argv);
  Env* env = Env::Default();

  LOG(INFO) << "Opening SQLite file: " << path;
  Sqlite* db;
  TF_CHECK_OK(Sqlite::Open(
      path, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX,
      &db));
  core::ScopedUnref unref_db(db);

  LOG(INFO) << "Initializing TensorBoard schema";
  TF_CHECK_OK(SetupTensorboardSqliteDb(db));

  LOG(INFO) << "Creating SummaryDbWriter";
  SummaryWriterInterface* db_writer;
  TF_CHECK_OK(CreateSummaryDbWriter(db, experiment_name, run_name, user_name,
                                    env, &db_writer));
  core::ScopedUnref unref(db_writer);

  LOG(INFO) << "Loading TF event log: " << events;
  std::unique_ptr<RandomAccessFile> file;
  TF_CHECK_OK(env->NewRandomAccessFile(events, &file));
  io::RecordReader reader(file.get());

  uint64 start = env->NowMicros();
  uint64 records = 0;
  uint64 offset = 0;
  string record;
  while (true) {
    std::unique_ptr<Event> event = std::unique_ptr<Event>(new Event);
    Status s = reader.ReadRecord(&offset, &record);
    if (s.code() == error::OUT_OF_RANGE) break;
    TF_CHECK_OK(s);
    if (!ParseProtoUnlimited(event.get(), record)) {
      LOG(FATAL) << "Corrupt tf.Event record"
                 << " offset=" << (offset - record.size())
                 << " size=" << static_cast<int>(record.size());
    }
    TF_CHECK_OK(db_writer->WriteEvent(std::move(event)));
    ++records;
  }
  uint64 elapsed = env->NowMicros() - start;
  LOG(INFO) << "Loaded " << AddCommas(offset) << " bytes with "
            << AddCommas(records) << " records at "
            << (elapsed == 0 ? offset : static_cast<uint64>(
                                            offset / (elapsed / 1000000.0)))
            << " bps";
  return 0;
}

}  // namespace
}  // namespace tensorflow

int main(int argc, char* argv[]) { return tensorflow::main(argc, argv); }
<commit_msg>Add the commas back<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iostream>
#include <vector>

#include "tensorflow/contrib/tensorboard/db/schema.h"
#include "tensorflow/contrib/tensorboard/db/summary_db_writer.h"
#include "tensorflow/core/lib/db/sqlite.h"
#include "tensorflow/core/lib/io/record_reader.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/core/util/event.pb.h"

namespace tensorflow {
namespace {

template <typename T>
string AddCommas(T n) {
  static_assert(std::is_integral<T>::value, "is_integral");
  string s = strings::StrCat(n);
  if (s.size() > 3) {
    int extra = s.size() / 3 - (s.size() % 3 == 0 ? 1 : 0);
    s.append(extra, 'X');
    int c = 0;
    for (int i = s.size() - 1; i > 0; --i) {
      s[i] = s[i - extra];
      if (++c % 3 == 0) {
        s[--i] = ',';
        --extra;
      }
    }
  }
  return s;
}

int main(int argc, char* argv[]) {
  string path;
  string events;
  string experiment_name;
  string run_name;
  string user_name;
  std::vector<Flag> flag_list = {
      Flag("db", &path, "Path of SQLite DB file"),
      Flag("events", &events, "TensorFlow record proto event log file"),
      Flag("experiment_name", &experiment_name, "The DB experiment_name value"),
      Flag("run_name", &run_name, "The DB run_name value"),
      Flag("user_name", &user_name, "The DB user_name value"),
  };
  string usage = Flags::Usage(argv[0], flag_list);
  bool parse_result = Flags::Parse(&argc, argv, flag_list);
  if (!parse_result || path.empty()) {
    std::cerr << "The loader tool imports tf.Event record files, created by\n"
              << "SummaryFileWriter, into the sorts of SQLite database files\n"
              << "created by SummaryDbWriter.\n\n"
              << "In addition to the flags below, the environment variables\n"
              << "defined by core/lib/db/sqlite.cc can also be set.\n\n"
              << usage;
    return -1;
  }
  port::InitMain(argv[0], &argc, &argv);
  Env* env = Env::Default();

  LOG(INFO) << "Opening SQLite file: " << path;
  Sqlite* db;
  TF_CHECK_OK(Sqlite::Open(
      path, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX,
      &db));
  core::ScopedUnref unref_db(db);

  LOG(INFO) << "Initializing TensorBoard schema";
  TF_CHECK_OK(SetupTensorboardSqliteDb(db));

  LOG(INFO) << "Creating SummaryDbWriter";
  SummaryWriterInterface* db_writer;
  TF_CHECK_OK(CreateSummaryDbWriter(db, experiment_name, run_name, user_name,
                                    env, &db_writer));
  core::ScopedUnref unref(db_writer);

  LOG(INFO) << "Loading TF event log: " << events;
  std::unique_ptr<RandomAccessFile> file;
  TF_CHECK_OK(env->NewRandomAccessFile(events, &file));
  io::RecordReader reader(file.get());

  uint64 start = env->NowMicros();
  uint64 records = 0;
  uint64 offset = 0;
  string record;
  while (true) {
    std::unique_ptr<Event> event = std::unique_ptr<Event>(new Event);
    Status s = reader.ReadRecord(&offset, &record);
    if (s.code() == error::OUT_OF_RANGE) break;
    TF_CHECK_OK(s);
    if (!ParseProtoUnlimited(event.get(), record)) {
      LOG(FATAL) << "Corrupt tf.Event record"
                 << " offset=" << (offset - record.size())
                 << " size=" << static_cast<int>(record.size());
    }
    TF_CHECK_OK(db_writer->WriteEvent(std::move(event)));
    ++records;
  }
  uint64 elapsed = env->NowMicros() - start;
  uint64 bps = (elapsed == 0 ? offset : static_cast<uint64>(
                                            offset / (elapsed / 1000000.0)));
  LOG(INFO) << "Loaded " << AddCommas(offset) << " bytes with "
            << AddCommas(records) << " records at " << AddCommas(bps) << " bps";
  return 0;
}

}  // namespace
}  // namespace tensorflow

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