<commit_before>/**************************************************************************
 * This file is property of and copyright by the Experimental Nuclear     *
 * Physics Group, Dep. of Physics                                         *
 * University of Oslo, Norway, 2007                                       *
 *                                                                        *
 * Author: Per Thomas Hille <perthi@fys.uio.no> for the ALICE HLT Project.*
 * Contributors are mentioned in the code where appropriate.              *
 * Please report bugs to perthi@fys.uio.no                                *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
#include "AliHLTPHOSFourierComponent.h"
#include "AliHLTPHOSFourier.h"
#include "AliHLTPHOSValidCellDataStruct.h"
#include "AliHLTPHOSRcuCellEnergyDataStruct.h"
#include "AliHLTPHOSSharedMemoryInterface.h"

#include "AliHLTPHOSRcuFFTDataStruct.h"

AliHLTPHOSFourierComponent gAliHLTPHOSFourierComponent;

AliHLTPHOSFourierComponent::AliHLTPHOSFourierComponent(): AliHLTPHOSRcuProcessor(),fFourierPtr(0), fShmPtr(0),fOutPtr(0)
{
  fFourierPtr = new AliHLTPHOSFourier();
  fShmPtr = new AliHLTPHOSSharedMemoryInterface();
}

AliHLTPHOSFourierComponent::~AliHLTPHOSFourierComponent()
{

}

int
AliHLTPHOSFourierComponent::Deinit()
{
  Logging(kHLTLogInfo, "HLT", "PHOS", ",Deinitializing AliHLTPHOSFourierComponent");
  return 0;
}

const char*
AliHLTPHOSFourierComponent::GetComponentID()
{
  return "PhosFourier";
  //     "PhosFourier"
}

AliHLTComponent*
AliHLTPHOSFourierComponent::Spawn()

{
  return new AliHLTPHOSFourierComponent;
}

void
AliHLTPHOSFourierComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list)
{
  const AliHLTComponentDataType* pType=fgkInputDataTypes;

  while (pType->fID!=0)
    {
      list.push_back(*pType);
      pType++;
    }
}

AliHLTComponentDataType
AliHLTPHOSFourierComponent::GetOutputDataType()
{
  return AliHLTPHOSDefinitions::fgkFourierTransform;
  // return AliHLTPHOSDefinitions::fgkCellEnergyDataType;
  // return kAliHLTMultipleDataType;
}

/*
int
AliHLTPHOSFourierComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& tgtList)
{
  tgtList.clear();
  tgtList.push_back(AliHLTPHOSDefinitions::fgkFourierTransform);
  //  tgtList.push_back(kAliHLTDataTypeHwAddr16);
  return tgtList.size();
}
*/

void
AliHLTPHOSFourierComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
{
 //  constBase =1;
//   inputMultiplier = 1;
  // constBase = 30;
  // inputMultiplier = 1.2;
  inputMultiplier = 0.1;
}

int
AliHLTPHOSFourierComponent::DoInit(int /*argc*/, const char** /*argv*/)
{
  cout << "AliHLTPHOSFourierComponent::DoInit !!!!!!!!!! " << endl;
  return 0;
}

/*
int
AliHLTPHOSFourierComponent::DoDeinit()
{

}
*/

int
AliHLTPHOSFourierComponent::DoEvent(const AliHLTComponentEventData& evtData,
				    const AliHLTComponentBlockData* blocks,
				    AliHLTComponentTriggerData& /*trigData*/,
				    AliHLTUInt8_t* outputPtr,
				    AliHLTUInt32_t& size,
				    AliHLTComponentBlockDataList& outputBlocks )
{
  fPhosEventCount ++;
  AliHLTPHOSValidCellDataStruct *currentChannel =0;
  UInt_t offset            = 0;
  UInt_t mysize            = 0;
  UInt_t tSize             = 0;
  const AliHLTComponentBlockData* iter = NULL;
  unsigned long ndx;
  UInt_t specification = 0;

  for( ndx = 0; ndx < evtData.fBlockCnt; ndx++ )
    {
      iter = blocks+ndx;
      if(iter->fDataType != AliHLTPHOSDefinitions::fgkCellEnergyDataType)
	{

	  continue;
	}

      specification = specification|iter->fSpecification;
      AliHLTPHOSRcuCellEnergyDataStruct *cellDataPtr = (AliHLTPHOSRcuCellEnergyDataStruct*)( iter->fPtr);
      AliHLTPHOSRcuFFTDataStruct *fourierOutPtr =  (AliHLTPHOSRcuFFTDataStruct*)outputPtr;
      fShmPtr->SetMemory(cellDataPtr);
      currentChannel = fShmPtr->NextChannel();

      while(currentChannel != 0)
	{
	  Int_t *data;
	  Int_t nsamples = 0;
	  data= fShmPtr->GetRawData(nsamples);
	  fFourierPtr->ProcessFourier(data, nsamples, currentChannel->fZ, currentChannel->fX, currentChannel->fGain  );
	  currentChannel = fShmPtr->NextChannel();
	}

      *fourierOutPtr =  fFourierPtr->GetPSD();

      for(int i=0; i < 500; i++)
	{
	  if(i%16 == 0)
	    {
	      printf("\n");
	    }

	  cout << fourierOutPtr->fGlobalAccumulatedPSD[1][i] <<  "\t";
	}

      mysize += sizeof(AliHLTPHOSRcuFFTDataStruct);
      AliHLTComponentBlockData bd;
      bd.fOffset = offset;
      bd.fSize = mysize;
      bd.fDataType = AliHLTPHOSDefinitions::fgkFourierTransform;
      // bd.fSpecification = 0xFFFFFFFF;
      bd.fSpecification = specification;
      outputBlocks.push_back( bd );

      cout <<"size left is "<<  size  <<"  FourierComponenet: offset ="<< offset << "mysize =" << mysize << "specification =" << specification <<endl;
      tSize += mysize;

      outputPtr += mysize;

      if( tSize > size )
	{
	  cout <<"HLT::AliHLTFourierComponent::DoEvent Too much data Data written over allowed buffer. Amount written:"<< tSize<<"allowed amount"<< size << endl;
	  Logging( kHLTLogFatal, "HLT::AliHLTFourierComponent::DoEvent", "Too much data",
		   "Data written over allowed buffer. Amount written: %lu, allowed amount: %lu." , tSize, size );

	  return EMSGSIZE;
	}

    }

  return 0;

}
<commit_msg>Test<commit_after>/**************************************************************************
 * This file is property of and copyright by the Experimental Nuclear     *
 * Physics Group, Dep. of Physics                                         *
 * University of Oslo, Norway, 2007                                       *
 *                                                                        *
 * Author: Per Thomas Hille <perthi@fys.uio.no> for the ALICE HLT Project.*
 * Contributors are mentioned in the code where appropriate.              *
 * Please report bugs to perthi@fys.uio.no                                *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
#include "AliHLTPHOSFourierComponent.h"
#include "AliHLTPHOSFourier.h"
#include "AliHLTPHOSValidCellDataStruct.h"
#include "AliHLTPHOSRcuCellEnergyDataStruct.h"
#include "AliHLTPHOSSharedMemoryInterface.h"

#include "AliHLTPHOSRcuFFTDataStruct.h"

AliHLTPHOSFourierComponent gAliHLTPHOSFourierComponent;

AliHLTPHOSFourierComponent::AliHLTPHOSFourierComponent(): AliHLTPHOSRcuProcessor(),fFourierPtr(0), fShmPtr(0),fOutPtr(0)
{
  fFourierPtr = new AliHLTPHOSFourier();
  fShmPtr = new AliHLTPHOSSharedMemoryInterface();
}

AliHLTPHOSFourierComponent::~AliHLTPHOSFourierComponent()
{

}

int
AliHLTPHOSFourierComponent::Deinit()
{
  Logging(kHLTLogInfo, "HLT", "PHOS", ",Deinitializing AliHLTPHOSFourierComponent");
  return 0;
}

const char*
AliHLTPHOSFourierComponent::GetComponentID()
{
  return "PhosFourier";
  //     "PhosFourier"
}

AliHLTComponent*
AliHLTPHOSFourierComponent::Spawn()

{
  return new AliHLTPHOSFourierComponent;
}

void
AliHLTPHOSFourierComponent::GetInputDataTypes( vector<AliHLTComponentDataType>& list)
{
  const AliHLTComponentDataType* pType=fgkInputDataTypes;

  while (pType->fID!=0)
    {
      list.push_back(*pType);
      pType++;
    }
}

AliHLTComponentDataType
AliHLTPHOSFourierComponent::GetOutputDataType()
{
  return AliHLTPHOSDefinitions::fgkFourierTransform;
  // return AliHLTPHOSDefinitions::fgkCellEnergyDataType;
  // return kAliHLTMultipleDataType;
}

/*
int
AliHLTPHOSFourierComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& tgtList)
{
  tgtList.clear();
  tgtList.push_back(AliHLTPHOSDefinitions::fgkFourierTransform);
  //  tgtList.push_back(kAliHLTDataTypeHwAddr16);
  return tgtList.size();
}
*/

void
AliHLTPHOSFourierComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier)
{
 //  constBase =1;
//   inputMultiplier = 1;
  // constBase = 30;
  // inputMultiplier = 1.2;
  inputMultiplier = 0.1;
}

int
AliHLTPHOSFourierComponent::DoInit(int /*argc*/, const char** /*argv*/)
{
  cout << "AliHLTPHOSFourierComponent::DoInit !!!!!!!!!! " << endl;
  return 0;
}

/*
int
AliHLTPHOSFourierComponent::DoDeinit()
{

}
*/

int
AliHLTPHOSFourierComponent::DoEvent(const AliHLTComponentEventData& evtData,
				    const AliHLTComponentBlockData* blocks,
				    AliHLTComponentTriggerData& /*trigData*/,
				    AliHLTUInt8_t* outputPtr,
				    AliHLTUInt32_t& size,
				    AliHLTComponentBlockDataList& outputBlocks )
{
  fPhosEventCount ++;
  AliHLTPHOSValidCellDataStruct *currentChannel =0;
  UInt_t offset            = 0;
  UInt_t mysize            = 0;
  UInt_t tSize             = 0;
  const AliHLTComponentBlockData* iter = NULL;
  unsigned long ndx;
  UInt_t specification = 0;

  for( ndx = 0; ndx < evtData.fBlockCnt; ndx++ )
    {
      iter = blocks+ndx;
      if(iter->fDataType != AliHLTPHOSDefinitions::fgkCellEnergyDataType)
	{

	  continue;
	}

      specification = specification|iter->fSpecification;
      AliHLTPHOSRcuCellEnergyDataStruct *cellDataPtr = (AliHLTPHOSRcuCellEnergyDataStruct*)( iter->fPtr);
      AliHLTPHOSRcuFFTDataStruct *fourierOutPtr =  (AliHLTPHOSRcuFFTDataStruct*)outputPtr;
      fShmPtr->SetMemory(cellDataPtr);
      currentChannel = fShmPtr->NextChannel();

      while(currentChannel != 0)
	{
	  Int_t *data;
	  Int_t nsamples = 0;
	  data= fShmPtr->GetRawData(nsamples);
	  fFourierPtr->ProcessFourier(data, nsamples, currentChannel->fZ, currentChannel->fX, currentChannel->fGain  );
	  currentChannel = fShmPtr->NextChannel();
	}

      *fourierOutPtr =  fFourierPtr->GetPSD();

      for(int i=0; i < 500; i++)
	{
	  if(i%16 == 0)
	    {
	      printf("\n");
	    }

	  cout << fourierOutPtr->fGlobalAccumulatedPSD[1][i] <<  "\t";
	}

      mysize += sizeof(AliHLTPHOSRcuFFTDataStruct);
      AliHLTComponentBlockData bd;
      bd.fOffset = offset;
      bd.fSize = mysize;
      bd.fDataType = AliHLTPHOSDefinitions::fgkFourierTransform;
      // bd.fSpecification = 0xFFFFFFFF;
      bd.fSpecification = specification;
      outputBlocks.push_back( bd );

      cout <<"size left is "<<  size  <<"  FourierComponenet: offset ="<< offset << "mysize =" << mysize << "specification =" << specification <<endl;
      tSize += mysize;

      outputPtr += mysize;

      if( tSize > size )
	{
	  cout <<"HLT::AliHLTFourierComponent::DoEvent Too much data Data written over allowed buffer. Amount written:"<< tSize<<"allowed amount"<< size << endl;
	  Logging( kHLTLogFatal, "HLT::AliHLTFourierComponent::DoEvent", "Too much data",
		   "Data written over allowed buffer. Amount written: %lu, allowed amount: %lu." , tSize, size );

	  return EMSGSIZE;
	}

    }

  return 0;

}
<|endoftext|>


<commit_before>/*
 @ 0xCCCCCCCC
*/

#include "stdafx.h"

#include "gtest\gtest.h"
#include <Windows.h>

#include <iostream>
#include <thread>
#include <vector>

#include "kbase\file_util.h"
#include "kbase\logging.h"

using namespace kbase;

namespace {

void ThreadFn(int id)
{
    std::cout << "thread " << id << std::endl;
    LOG(INFO) << "The thread " << id << " is currently running";
}

bool Boolean(bool b)
{
    std::cout << "Boolean() is called\n";
    return b;
}

}   // namespace

TEST(LoggingTest, MT)
{
    LoggingSettings settings;
    settings.log_item_options = LogItemOptions::ENABLE_ALL;
    ConfigureLoggingSettings(settings);

    std::vector<std::thread> vth;
    for (int i = 0; i < 5; ++i) {
        vth.emplace_back(ThreadFn, i);
    }

    std::cout << "all are prepared" << std::endl;
    for (auto& th : vth) {
        th.join();
    }
}

TEST(LoggingTest, MinLevelAndConditionalLogging)
{
    LoggingSettings logging_settings;
    logging_settings.min_severity_level = LogSeverity::LOG_ERROR;
    logging_settings.logging_destination = LoggingDestination::LOG_TO_ALL;
    ConfigureLoggingSettings(logging_settings);
    LOG(WARNING) << "LOG(WARNING)";
    LOG_IF(ERROR, Boolean(true)) << "LOG_IF(ERROR, Boolean(true))";
    LOG_IF(ERROR, Boolean(false)) << "LOG_IF(ERROR, Boolean(false))";
    DLOG(INFO) << "DLOG(INFO)";
    DLOG(ERROR) << "DLOG(ERROR)";
    DLOG_IF(FATAL, Boolean(true)) << "DLOG_IF(FATAL, Boolean(true))";
    DLOG_IF(FATAL, Boolean(false)) << "DLOG_IF(FATAL, Boolean(false))";
}

TEST(LoggingTest, CustomLogFileName)
{
    PathString log_name = L"my_test_debug.log";
    LoggingSettings logging_settings;
    logging_settings.log_file_path = log_name;
    ConfigureLoggingSettings(logging_settings);
    LOG(INFO) << "testing customized log file name";
    ASSERT_TRUE(PathExists(FilePath(log_name)));
}<commit_msg>UnitTest: update testcase for logging.<commit_after>/*
 @ 0xCCCCCCCC
*/

#include "stdafx.h"

#include "gtest\gtest.h"
#include <Windows.h>

#include <iostream>
#include <thread>
#include <vector>

#include "kbase\file_util.h"
#include "kbase\logging.h"

using namespace kbase;

namespace {

void ThreadFn(int id)
{
    std::cout << "thread " << id << std::endl;
    LOG(INFO) << "The thread " << id << " is currently running";
}

bool Boolean(bool b)
{
    std::cout << "Boolean() is called\n";
    return b;
}

}   // namespace

TEST(LoggingTest, MT)
{
    LoggingSettings settings;
    settings.log_item_options = LogItemOptions::ENABLE_ALL;
    ConfigureLoggingSettings(settings);

    std::vector<std::thread> vth;
    for (int i = 0; i < 5; ++i) {
        vth.emplace_back(ThreadFn, i);
    }

    std::cout << "all are prepared" << std::endl;
    for (auto& th : vth) {
        th.join();
    }
}

TEST(LoggingTest, MinLevelAndConditionalLogging)
{
    LoggingSettings logging_settings;
    logging_settings.min_severity_level = LogSeverity::LOG_ERROR;
    logging_settings.logging_destination = LoggingDestination::LOG_TO_ALL;
    ConfigureLoggingSettings(logging_settings);
    LOG(WARNING) << "LOG(WARNING)";
    LOG_IF(ERROR, Boolean(true)) << "LOG_IF(ERROR, Boolean(true))";
    LOG_IF(ERROR, Boolean(false)) << "LOG_IF(ERROR, Boolean(false))";
    DLOG(INFO) << "DLOG(INFO)";
    DLOG(ERROR) << "DLOG(ERROR)";
    DLOG_IF(FATAL, Boolean(true)) << "DLOG_IF(FATAL, Boolean(true))";
    DLOG_IF(FATAL, Boolean(false)) << "DLOG_IF(FATAL, Boolean(false))";
}

TEST(LoggingTest, CustomLogFileName)
{
    PathString log_name = L"my_test_debug.log";
    LoggingSettings logging_settings;
    logging_settings.log_file_path = log_name;
    ConfigureLoggingSettings(logging_settings);
    LOG(INFO) << "testing customized log file name";
    ASSERT_TRUE(PathExists(FilePath(log_name)));
}

TEST(LoggingTest, FatalLevelCallStack)
{
    ConfigureLoggingSettings(LoggingSettings());
    LOG(FATAL) << "simulate issuing a fatal error";
}<|endoftext|>


<commit_before>#include "encoderSensor.h"

#include <utils/tracer.h>

using namespace trikKitInterpreter::robotModel::real::parts;
using namespace interpreterBase::robotModel;

EncoderSensor::EncoderSensor(DeviceInfo const &info, PortInfo const &port
		, utils::TcpRobotCommunicator &tcpRobotCommunicator)
	: interpreterBase::robotModel::robotParts::EncoderSensor(info, port)
	, mRobotCommunicator(tcpRobotCommunicator)
{
	connect(&mRobotCommunicator, &utils::TcpRobotCommunicator::newScalarSensorData
			, this, &EncoderSensor::onIncomingData);
}

void EncoderSensor::read()
{
	mRobotCommunicator.requestData(port().name());
}

void EncoderSensor::onIncomingData(QString const &portName, int value)
{
	if (portName == port().name()) {
		emit newData(value);
	}
}

void EncoderSensor::nullify()
{
}
<commit_msg>Encoder nullification supported in interpreter<commit_after>#include "encoderSensor.h"

#include <qrutils/inFile.h>

using namespace trikKitInterpreter::robotModel::real::parts;
using namespace interpreterBase::robotModel;

EncoderSensor::EncoderSensor(DeviceInfo const &info, PortInfo const &port
		, utils::TcpRobotCommunicator &tcpRobotCommunicator)
	: interpreterBase::robotModel::robotParts::EncoderSensor(info, port)
	, mRobotCommunicator(tcpRobotCommunicator)
{
	connect(&mRobotCommunicator, &utils::TcpRobotCommunicator::newScalarSensorData
			, this, &EncoderSensor::onIncomingData);
}

void EncoderSensor::read()
{
	mRobotCommunicator.requestData(port().name());
}

void EncoderSensor::onIncomingData(QString const &portName, int value)
{
	if (portName == port().name()) {
		emit newData(value);
	}
}

void EncoderSensor::nullify()
{
	QString const pathToCommand = ":/trikQts/templates/.t";
	QString const directCommand = utils::InFile::readAll(pathToCommand).replace("@@PORT@@", port().name());
	mRobotCommunicator.runDirectCommand(directCommand);
}
<|endoftext|>


<commit_before>#include<set>
#include <algorithm>    // std::random_shuffle
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand
#define N 10
#define M 5
using namespace std;

set< pair<long, long> > pairs;
set< pair<long, long> > :: iterator it;

int main(){
        vector<long> nums;
        std::srand ( unsigned ( std::time(0) ) );
        long i=0;
        for(i=0; i<N; i++)
                nums.push_back(rand()%i);
        random_shuffle( nums.begin(), nums.end());
        long totaldone = 0;
        long num = 0;
        long leftInM = M;
        long totalNum;
        long i = 0;
        while(totaldone<N){
          if(num%M == M-1){
            totalNum = leftInM;
          }else if(leftInM){
            totalNum = rand()%leftInM;
          }else totalNum = 0;
          while(totalNum){
            if(nums[i] == -1 || nums[i] == num ||
                  pairs.count(make_pair(num, nums[i]))>0 ||
                  pairs.count(make_pair(nums[i], num))>0){
              i = (i+1)%N;
            }
            if(num<nums[i])
              pairs.count(make_pair(num, nums[i]));
            else
              pairs.count(make_pair(nums[i], num));
            nums[i] = -1;
            totalNum--;
            leftInM--;
          }
          num++;
          if(num%M == 0) leftInM = M;
        }
        for(it =pairs.begin(); it!=pairs.end(); it++)
          cout << (*it).first << " " << (*it).second << endl;
        return 0;
}
<commit_msg>Update createEdges.cpp<commit_after>#include<set>
#include <vector>    // std::random_shuffle
#include <iostream>    // std::random_shuffle
#include <algorithm>    // std::random_shuffle
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand
#define N 1000000
#define M 1000
using namespace std;

set< pair<long, long> > pairs;
set< pair<long, long> > :: iterator it;

int main(){
        vector<long> nums;
        std::srand ( unsigned ( std::time(0) ) );
        long i=0;
        for(i=0; i<N; i++)
                nums.push_back(rand()%N);
        random_shuffle( nums.begin(), nums.end());
        long totaldone = 0;
        long num = 0;
        long leftInM = N/M;
        long totalNum;
        i = 0;
        while(pairs.size()<N){
          if(num%M == M-1){
            totalNum = leftInM;
          }else if(leftInM){
            totalNum = rand()%leftInM;
          }else totalNum = 0;
         // cout << "totalNum=" << totalNum << endl;
          while(totalNum){
            if(nums[i] == -1 || nums[i] == num ||
                  pairs.count(make_pair(num, nums[i]))>0 ||
                  pairs.count(make_pair(nums[i], num))>0){
                        i = (i+1)%N;
                        continue;
            }
            if(num<nums[i])
              pairs.insert(make_pair(num, nums[i]));
            else
              pairs.insert(make_pair(nums[i], num));
            //  cout << nums[i] << " " << num << " - " << pairs.size()  << endl;
            nums[i] = -1;
            totalNum--;
            leftInM--;
          }
          num = (num+1)%N;
          if(num%M == 0) leftInM = N/M;
        }
        for(it =pairs.begin(); it!=pairs.end(); it++)
          cout << (*it).first << " " << (*it).second << endl;
        return 0;
}
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIIrrlichtResourceProvider.cpp
    created:    12/22/2004
    author:     Thomas Suter

    purpose: Implements Irrlicht specific ResourceProvider
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUIIrrlichtResourceProvider.h"
#include "CEGUIExceptions.h"
#include <IReadFile.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
IrrlichtResourceProvider::IrrlichtResourceProvider(irr::io::IFileSystem& fs):
    DefaultResourceProvider(),
    d_fsys(fs)
{
    d_fsys.grab();
}

//----------------------------------------------------------------------------//
IrrlichtResourceProvider::~IrrlichtResourceProvider()
{
    d_fsys.drop();
}

//----------------------------------------------------------------------------//
void IrrlichtResourceProvider::loadRawDataContainer(const String& filename,
                                                    RawDataContainer& output,
                                                    const String& resourceGroup)
{
    String final_filename(getFinalFilename(filename, resourceGroup));

    if (!d_fsys.existFile(final_filename.c_str()))
    {
        String sMsg("IrrlichtResourceProvider::loadRawDataContainer: "
                    "Filename supplied for loading must be valid");
        sMsg += " [" + final_filename + "]";
        CEGUI_THROW(InvalidRequestException(sMsg));
    }

    irr::u8* input;
    irr::u32 input_size;
    irr::io::IReadFile* f = d_fsys.createAndOpenFile(final_filename.c_str());
    input_size = f->getSize();
    input = new irr::u8[input_size];
    f->read(input, input_size);
    f->drop();

    output.setData(input);
    output.setSize(input_size);
}

//----------------------------------------------------------------------------//
void IrrlichtResourceProvider::unloadRawDataContainer(RawDataContainer& data)
{
    if (data.getDataPtr())
    {
        delete[] data.getDataPtr();
        data.setData(0);
        data.setSize(0);
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<commit_msg>FIX: Ensure IrrlichtResourceProvider correctly detects when a file does not open successfully (as opposed to just checking that it exists).  See: http://www.cegui.org.uk/mantis/view.php?id=395<commit_after>/***********************************************************************
    filename:   CEGUIIrrlichtResourceProvider.cpp
    created:    12/22/2004
    author:     Thomas Suter

    purpose: Implements Irrlicht specific ResourceProvider
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUIIrrlichtResourceProvider.h"
#include "CEGUIExceptions.h"
#include <IReadFile.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
IrrlichtResourceProvider::IrrlichtResourceProvider(irr::io::IFileSystem& fs):
    DefaultResourceProvider(),
    d_fsys(fs)
{
    d_fsys.grab();
}

//----------------------------------------------------------------------------//
IrrlichtResourceProvider::~IrrlichtResourceProvider()
{
    d_fsys.drop();
}

//----------------------------------------------------------------------------//
void IrrlichtResourceProvider::loadRawDataContainer(const String& filename,
                                                    RawDataContainer& output,
                                                    const String& resourceGroup)
{
    String final_filename(getFinalFilename(filename, resourceGroup));

    irr::u8* input;
    irr::u32 input_size;
    irr::io::IReadFile* f = d_fsys.createAndOpenFile(final_filename.c_str());

    if (!f)
    {
        String sMsg("IrrlichtResourceProvider::loadRawDataContainer: "
                    "Filename supplied for loading must be valid");
        sMsg += " [" + final_filename + "]";
        CEGUI_THROW(InvalidRequestException(sMsg));
    }

    input_size = f->getSize();
    input = new irr::u8[input_size];
    f->read(input, input_size);
    f->drop();

    output.setData(input);
    output.setSize(input_size);
}

//----------------------------------------------------------------------------//
void IrrlichtResourceProvider::unloadRawDataContainer(RawDataContainer& data)
{
    if (data.getDataPtr())
    {
        delete[] data.getDataPtr();
        data.setData(0);
        data.setSize(0);
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>#include "TString.h"
class AliAnalysisDataContainer;
class TNamed;
AliAnalysisTaskMeanPtV2Corr* AddTaskMeanPtV2Corr(TString name = "name", Bool_t IsMC=kFALSE, TString stage = "weights",
                                                  TString efficiencyPath = "", TString meanPtPath="", TString NUAPath="", TString subfix="")
{
  Int_t StageSwitch = 0;
  if(stage.Contains("weights")) StageSwitch=1;
  if(stage.Contains("meanpt")) StageSwitch=2;
  if(stage.Contains("full")) StageSwitch=3;
  if(stage.Contains("ALICEMpt")) StageSwitch=4;
  if(stage.Contains("ALICECov")) StageSwitch=5;
  if(stage.Contains("FBSpectra")) StageSwitch=6;
  if(stage.Contains("Efficiency")) StageSwitch=7;
  if(StageSwitch==0) return 0;

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) return 0x0;
  if (!mgr->GetInputEventHandler())	return 0x0;
  // if(IsMC) {
  //   if(!mgr->GetMCtruthEventHandler()) {
  //     Error("AddTaskMeanPtV2Corr","Could not get MC truth handler");
  //     return NULL;
  //   };
  //   AliMCEventHandler *handler = (AliMCEventHandler*)mgr->GetMCtruthEventHandler();
  //   handler->SetReadTR(kTRUE);
  // };
  TString fileName = AliAnalysisManager::GetCommonFileName();
  AliAnalysisTaskMeanPtV2Corr* task = new AliAnalysisTaskMeanPtV2Corr(name.Data(), IsMC, stage);
  if(!task)
    return 0x0;
  mgr->AddTask(task); // add your task to the manager
  AliAnalysisDataContainer* cInput0 = mgr->GetCommonInputContainer();
  mgr->ConnectInput(task,0,cInput0);
  //Producing weights
  if(StageSwitch==1) {
    AliAnalysisDataContainer *weightCont = mgr->CreateContainer("WeightList",TList::Class(),AliAnalysisManager::kOutputContainer,"AnalysisResults.root");
    mgr->ConnectOutput(task,1,weightCont);
    return task;
  }
  //Load input mean pt
  if(StageSwitch==2) {
    TObjArray *AllContainers = mgr->GetContainers();
    if(!AllContainers->FindObject("Efficiency")) {
      if(efficiencyPath.IsNull()) AliFatal("Weight path not provided!\n");
      if(efficiencyPath.Contains("alien:")) TGrid::Connect("alien:");
      TFile *tfWeights = TFile::Open(efficiencyPath.Data()); //"alien:///alice/cern.ch/user/v/vvislavi/MeanPts/MergedWeights.root"
      if(!tfWeights) AliFatal("Could not open weights file\n");
      if(tfWeights->IsZombie()) AliFatal("Weight file is a zombie\n");
      TList *fList = (TList*)tfWeights->Get("EffAndFD");
      if(!fList) { AliFatal("Could not fetch the weight list!\n"); return; };
      AliAnalysisDataContainer *cEff = mgr->CreateContainer("Efficiency",TList::Class(), AliAnalysisManager::kInputContainer);
      cEff->SetData(fList);
      mgr->ConnectInput(task,1,cEff);
    } else mgr->ConnectInput(task,1,(AliAnalysisDataContainer*)AllContainers->FindObject("Efficiency"));

    TString l_ContName=subfix.IsNull()?"":("_" + subfix);
    AliAnalysisDataContainer *cOutputMPT = mgr->CreateContainer(Form("MPTProfileList%s",l_ContName.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,1,cOutputMPT);
    return task;
  };
  //Full
  if(StageSwitch==3) {
    TObjArray *AllContainers = mgr->GetContainers();
    if(!AllContainers->FindObject("Weights")) {
      if(efficiencyPath.IsNull()) AliFatal("Weight path not provided!\n");
      if(efficiencyPath.Contains("alien:")) TGrid::Connect("alien:");
      TFile *tfWeights = TFile::Open(efficiencyPath.Data());
      TList *fList = (TList*)tfWeights->Get("WeightList");
      AliAnalysisDataContainer *cWeights = mgr->CreateContainer("WeightList",TList::Class(), AliAnalysisManager::kInputContainer);
      cWeights->SetData(fList);
      mgr->ConnectInput(task,1,cWeights);
    };
    if(!AllContainers->FindObject("InputMeanPt")) {
      if(meanPtPath.IsNull()) AliFatal("Mean pT path not provided!\n");
      if((!efficiencyPath.Contains("alien:")) && meanPtPath.Contains("alien:")) TGrid::Connect("alien:"); //Only connect if not connected yet
      TFile *tfMPT = TFile::Open(meanPtPath.Data()); //"alien:///alice/cern.ch/user/v/vvislavi/MeanPts/MeanPts_05_20.root"
      TList *fMPTList = (TList*)tfMPT->Get("MPTProfileList");
      if(!fMPTList) AliFatal("fMPT list from file not fetcehd!");
      AliAnalysisDataContainer *cInMPT = mgr->CreateContainer("InputMeanPt",TList::Class(), AliAnalysisManager::kInputContainer);
      cInMPT->SetData(fMPTList);
      mgr->ConnectInput(task,2,cInMPT);
    };
    if(!AllContainers->FindObject("NUACorr")) {
      if(NUAPath.IsNull()) AliFatal("AdHoc NUA path not provided!\n");
      if((!efficiencyPath.Contains("alien:")) && !meanPtPath.Contains("alien:") && NUAPath.Contains("alien:") ) TGrid::Connect("alien:"); //Only connect if not connected yet
      TFile *tfNUA = TFile::Open(NUAPath.Data()); //"alien:///alice/cern.ch/user/v/vvislavi/MeanPts/MeanPts_05_20.root"
      TList *fNUAList = (TList*)tfNUA->Get("PIDWeights");
      AliAnalysisDataContainer *cInNUA = mgr->CreateContainer("NUACorr",TList::Class(), AliAnalysisManager::kInputContainer);
      cInNUA->SetData(fNUAList);
      mgr->ConnectInput(task,3,cInNUA);
    };

    AliAnalysisDataContainer *cOutputMPT = mgr->CreateContainer("MPTDiff",TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,1,cOutputMPT);
    AliAnalysisDataContainer *cOutputFC  = mgr->CreateContainer("FlowCont",AliGFWFlowContainer::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,2,cOutputFC);
    AliAnalysisDataContainer *cOutputCov  = mgr->CreateContainer("Covariance",TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,3,cOutputCov);
    return task;
  };
  if(StageSwitch==4) {
    AliAnalysisDataContainer *cOutputMPT = mgr->CreateContainer("MPTProfileList",TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,1,cOutputMPT);
    return task;
  }
  if(StageSwitch==5) {
    TObjArray *AllContainers = mgr->GetContainers();
    if(meanPtPath.IsNull()) AliFatal("Input weights not set\n");
    if(!AllContainers->FindObject("InputMeanPt")) {
      if(meanPtPath.Contains("alien:")) TGrid::Connect("alien:"); //Only connect if not connected yet
      TFile *tfMPT = TFile::Open(meanPtPath.Data()); //"alien:///alice/cern.ch/user/v/vvislavi/MeanPts/MeanPts_05_20.root"
      TList *fMPTList = (TList*)tfMPT->Get("MPTProfileList");
      if(!fMPTList) AliFatal("fMPT list from file not fetcehd!");
      AliAnalysisDataContainer *cInMPT = mgr->CreateContainer("InputMeanPt",TList::Class(), AliAnalysisManager::kInputContainer);
      cInMPT->SetData(fMPTList);
      mgr->ConnectInput(task,1,cInMPT);
    } else mgr->ConnectInput(task,1,(AliAnalysisDataContainer*)AllContainers->FindObject("InputMeanPt"));
    AliAnalysisDataContainer *cOutputMPT = mgr->CreateContainer("OutputList",TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,1,cOutputMPT);
  }
  if(StageSwitch==6) { //Producing Pt spectra with filter bit
    AliAnalysisDataContainer *cOutputSpectra = mgr->CreateContainer("PtSpectra",TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,1,cOutputSpectra);
    return task;
  }
  if(StageSwitch==7) { //Producing Pt spectra with filter bit
    TString l_ContName=subfix.IsNull()?"":("_" + subfix);
    AliAnalysisDataContainer *spectraCont = mgr->CreateContainer(Form("SpectraList%s",l_ContName.Data()),TList::Class(),AliAnalysisManager::kOutputContainer,"AnalysisResults.root");
    mgr->ConnectOutput(task,1,spectraCont);
    return task;
  }

  return 0;
}
<commit_msg>AddTaskMeanPtV2Corr should work with root6 now<commit_after>#include "TString.h"
class AliAnalysisDataContainer;
class TNamed;
AliAnalysisTaskMeanPtV2Corr* AddTaskMeanPtV2Corr(TString name = "name", Bool_t IsMC=kFALSE, TString stage = "weights",
                                                  TString efficiencyPath = "", TString meanPtPath="", TString NUAPath="", TString subfix="")
{
  Int_t StageSwitch = 0;
  if(stage.Contains("weights")) StageSwitch=1;
  if(stage.Contains("meanpt")) StageSwitch=2;
  if(stage.Contains("full")) StageSwitch=3;
  if(stage.Contains("ALICEMpt")) StageSwitch=4;
  if(stage.Contains("ALICECov")) StageSwitch=5;
  if(stage.Contains("FBSpectra")) StageSwitch=6;
  if(stage.Contains("Efficiency")) StageSwitch=7;
  if(StageSwitch==0) return 0;

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) return 0x0;
  if (!mgr->GetInputEventHandler())	return 0x0;
  // if(IsMC) {
  //   if(!mgr->GetMCtruthEventHandler()) {
  //     Error("AddTaskMeanPtV2Corr","Could not get MC truth handler");
  //     return NULL;
  //   };
  //   AliMCEventHandler *handler = (AliMCEventHandler*)mgr->GetMCtruthEventHandler();
  //   handler->SetReadTR(kTRUE);
  // };
  TString fileName = AliAnalysisManager::GetCommonFileName();
  AliAnalysisTaskMeanPtV2Corr* task = new AliAnalysisTaskMeanPtV2Corr(name.Data(), IsMC, stage);
  if(!task)
    return 0x0;
  mgr->AddTask(task); // add your task to the manager
  AliAnalysisDataContainer* cInput0 = mgr->GetCommonInputContainer();
  mgr->ConnectInput(task,0,cInput0);
  //Producing weights
  if(StageSwitch==1) {
    AliAnalysisDataContainer *weightCont = mgr->CreateContainer("WeightList",TList::Class(),AliAnalysisManager::kOutputContainer,"AnalysisResults.root");
    mgr->ConnectOutput(task,1,weightCont);
    return task;
  }
  //Load input mean pt
  if(StageSwitch==2) {
    TObjArray *AllContainers = mgr->GetContainers();
    if(!AllContainers->FindObject("Efficiency")) {
      if(efficiencyPath.IsNull()) { printf("Efficiency path not provided!\n"); return 0; };
      if(efficiencyPath.Contains("alien:")) TGrid::Connect("alien:");
      TFile *tfWeights = TFile::Open(efficiencyPath.Data()); //"alien:///alice/cern.ch/user/v/vvislavi/MeanPts/MergedWeights.root"
      if(!tfWeights) { printf("Could not open efficiency file\n"); return 0; };
      if(tfWeights->IsZombie()) { printf("Efficiency file is a zombie\n"); return 0; };
      TList *fList = (TList*)tfWeights->Get("EffAndFD");
      if(!fList) { printf("Could not fetch the efficiency list!\n"); return 0; };
      AliAnalysisDataContainer *cEff = mgr->CreateContainer("Efficiency",TList::Class(), AliAnalysisManager::kInputContainer);
      cEff->SetData(fList);
      mgr->ConnectInput(task,1,cEff);
    } else mgr->ConnectInput(task,1,(AliAnalysisDataContainer*)AllContainers->FindObject("Efficiency"));

    TString l_ContName=subfix.IsNull()?"":("_" + subfix);
    AliAnalysisDataContainer *cOutputMPT = mgr->CreateContainer(Form("MPTProfileList%s",l_ContName.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,1,cOutputMPT);
    return task;
  };
  //Full
  if(StageSwitch==3) {
    TObjArray *AllContainers = mgr->GetContainers();
    if(!AllContainers->FindObject("Weights")) {
      if(efficiencyPath.IsNull()) { printf("Weight path not provided!\n"); return 0; };
      if(efficiencyPath.Contains("alien:")) TGrid::Connect("alien:");
      TFile *tfWeights = TFile::Open(efficiencyPath.Data());
      TList *fList = (TList*)tfWeights->Get("WeightList");
      AliAnalysisDataContainer *cWeights = mgr->CreateContainer("WeightList",TList::Class(), AliAnalysisManager::kInputContainer);
      cWeights->SetData(fList);
      mgr->ConnectInput(task,1,cWeights);
    };
    if(!AllContainers->FindObject("InputMeanPt")) {
      if(meanPtPath.IsNull()) { printf("Mean pT path not provided!\n"); return 0; };
      if((!efficiencyPath.Contains("alien:")) && meanPtPath.Contains("alien:")) TGrid::Connect("alien:"); //Only connect if not connected yet
      TFile *tfMPT = TFile::Open(meanPtPath.Data()); //"alien:///alice/cern.ch/user/v/vvislavi/MeanPts/MeanPts_05_20.root"
      TList *fMPTList = (TList*)tfMPT->Get("MPTProfileList");
      if(!fMPTList) { printf("fMPT list from file not fetcehd!"); return 0; };
      AliAnalysisDataContainer *cInMPT = mgr->CreateContainer("InputMeanPt",TList::Class(), AliAnalysisManager::kInputContainer);
      cInMPT->SetData(fMPTList);
      mgr->ConnectInput(task,2,cInMPT);
    };
    if(!AllContainers->FindObject("NUACorr")) {
      if(NUAPath.IsNull()) { printf("NUA path not provided!\n"); return 0; };
      if((!efficiencyPath.Contains("alien:")) && !meanPtPath.Contains("alien:") && NUAPath.Contains("alien:") ) TGrid::Connect("alien:"); //Only connect if not connected yet
      TFile *tfNUA = TFile::Open(NUAPath.Data()); //"alien:///alice/cern.ch/user/v/vvislavi/MeanPts/MeanPts_05_20.root"
      TList *fNUAList = (TList*)tfNUA->Get("PIDWeights");
      AliAnalysisDataContainer *cInNUA = mgr->CreateContainer("NUACorr",TList::Class(), AliAnalysisManager::kInputContainer);
      cInNUA->SetData(fNUAList);
      mgr->ConnectInput(task,3,cInNUA);
    };

    AliAnalysisDataContainer *cOutputMPT = mgr->CreateContainer("MPTDiff",TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,1,cOutputMPT);
    AliAnalysisDataContainer *cOutputFC  = mgr->CreateContainer("FlowCont",AliGFWFlowContainer::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,2,cOutputFC);
    AliAnalysisDataContainer *cOutputCov  = mgr->CreateContainer("Covariance",TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,3,cOutputCov);
    return task;
  };
  if(StageSwitch==4) {
    AliAnalysisDataContainer *cOutputMPT = mgr->CreateContainer("MPTProfileList",TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,1,cOutputMPT);
    return task;
  }
  if(StageSwitch==5) {
    TObjArray *AllContainers = mgr->GetContainers();
    if(meanPtPath.IsNull()) { printf("Input weights not set\n"); return 0; };
    if(!AllContainers->FindObject("InputMeanPt")) {
      if(meanPtPath.Contains("alien:")) TGrid::Connect("alien:"); //Only connect if not connected yet
      TFile *tfMPT = TFile::Open(meanPtPath.Data()); //"alien:///alice/cern.ch/user/v/vvislavi/MeanPts/MeanPts_05_20.root"
      TList *fMPTList = (TList*)tfMPT->Get("MPTProfileList");
      if(!fMPTList) { printf("fMPT list from file not fetcehd!"); return 0; };
      AliAnalysisDataContainer *cInMPT = mgr->CreateContainer("InputMeanPt",TList::Class(), AliAnalysisManager::kInputContainer);
      cInMPT->SetData(fMPTList);
      mgr->ConnectInput(task,1,cInMPT);
    } else mgr->ConnectInput(task,1,(AliAnalysisDataContainer*)AllContainers->FindObject("InputMeanPt"));
    AliAnalysisDataContainer *cOutputMPT = mgr->CreateContainer("OutputList",TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,1,cOutputMPT);
  }
  if(StageSwitch==6) { //Producing Pt spectra with filter bit
    AliAnalysisDataContainer *cOutputSpectra = mgr->CreateContainer("PtSpectra",TList::Class(), AliAnalysisManager::kOutputContainer, "AnalysisResults.root");
    mgr->ConnectOutput(task,1,cOutputSpectra);
    return task;
  }
  if(StageSwitch==7) { //Producing Pt spectra with filter bit
    TString l_ContName=subfix.IsNull()?"":("_" + subfix);
    AliAnalysisDataContainer *spectraCont = mgr->CreateContainer(Form("SpectraList%s",l_ContName.Data()),TList::Class(),AliAnalysisManager::kOutputContainer,"AnalysisResults.root");
    mgr->ConnectOutput(task,1,spectraCont);
    return task;
  }

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/renderer_host/accelerated_surface_container_linux.h"

#include <X11/Xlib.h>
#include <X11/extensions/Xcomposite.h>

#include "base/lazy_instance.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/angle/include/EGL/egl.h"
#include "third_party/angle/include/EGL/eglext.h"
#include "ui/gfx/gl/gl_bindings.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/gl_surface_egl.h"
#include "ui/gfx/gl/gl_surface_glx.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/transform.h"

namespace {

class AcceleratedSurfaceContainerLinuxEGL
    : public AcceleratedSurfaceContainerLinux {
 public:
  explicit AcceleratedSurfaceContainerLinuxEGL(const gfx::Size& size);

  virtual bool Initialize(uint64* surface_id) OVERRIDE;

  // TextureGL implementation
  virtual void Draw(const ui::TextureDrawParams& params,
                    const gfx::Rect& clip_bounds_in_texture) OVERRIDE;

 private:
  virtual ~AcceleratedSurfaceContainerLinuxEGL();

  void* image_;

  DISALLOW_COPY_AND_ASSIGN(AcceleratedSurfaceContainerLinuxEGL);
};

class AcceleratedSurfaceContainerLinuxGLX
    : public AcceleratedSurfaceContainerLinux {
 public:
  explicit AcceleratedSurfaceContainerLinuxGLX(const gfx::Size& size);

  virtual bool Initialize(uint64* surface_id) OVERRIDE;

  // TextureGL implementation
  virtual void Draw(const ui::TextureDrawParams& params,
                    const gfx::Rect& clip_bounds_in_texture) OVERRIDE;

 protected:
  static bool InitializeOneOff();

  static base::LazyInstance<GLXFBConfig> fbconfig_;

 private:
  virtual ~AcceleratedSurfaceContainerLinuxGLX();

  XID pixmap_;
  XID glx_pixmap_;

  DISALLOW_COPY_AND_ASSIGN(AcceleratedSurfaceContainerLinuxGLX);
};

class AcceleratedSurfaceContainerLinuxOSMesa
    : public AcceleratedSurfaceContainerLinux {
 public:
  explicit AcceleratedSurfaceContainerLinuxOSMesa(const gfx::Size& size);

  virtual bool Initialize(uint64* surface_id) OVERRIDE;

  // TextureGL implementation
  virtual void Draw(const ui::TextureDrawParams& params,
                    const gfx::Rect& clip_bounds_in_texture) OVERRIDE;

  // Some implementations of this class use shared memory, this gives the handle
  // to the shared buffer, which is part of the surface container.
  // When shared memory is not used, this will return
  // TransportDIB::DefaultHandleValue().
  virtual TransportDIB::Handle Handle() const OVERRIDE;

 private:
  virtual ~AcceleratedSurfaceContainerLinuxOSMesa();

  scoped_ptr<TransportDIB> shared_mem_;

  DISALLOW_COPY_AND_ASSIGN(AcceleratedSurfaceContainerLinuxOSMesa);
};

class ScopedPtrXFree {
 public:
  void operator()(void* x) const {
    ::XFree(x);
  }
};

// static
base::LazyInstance<GLXFBConfig> AcceleratedSurfaceContainerLinuxGLX::fbconfig_(
    base::LINKER_INITIALIZED);

AcceleratedSurfaceContainerLinuxEGL::AcceleratedSurfaceContainerLinuxEGL(
    const gfx::Size& size)
    : AcceleratedSurfaceContainerLinux(size),
      image_(NULL) {
}

bool AcceleratedSurfaceContainerLinuxEGL::Initialize(uint64* surface_id) {
  ui::SharedResources* instance = ui::SharedResources::GetInstance();
  DCHECK(instance);
  instance->MakeSharedContextCurrent();

  image_ = eglCreateImageKHR(
      gfx::GLSurfaceEGL::GetHardwareDisplay(), EGL_NO_CONTEXT,
      EGL_NATIVE_PIXMAP_KHR, reinterpret_cast<void*>(*surface_id), NULL);

  glGenTextures(1, &texture_id_);
  glBindTexture(GL_TEXTURE_2D, texture_id_);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image_);
  glFlush();

  return true;
}

AcceleratedSurfaceContainerLinuxEGL::~AcceleratedSurfaceContainerLinuxEGL() {
  ui::SharedResources* instance = ui::SharedResources::GetInstance();
  DCHECK(instance);
  instance->MakeSharedContextCurrent();

  eglDestroyImageKHR(gfx::GLSurfaceEGL::GetHardwareDisplay(), image_);
  glFlush();
}

void AcceleratedSurfaceContainerLinuxEGL::Draw(
    const ui::TextureDrawParams& params,
    const gfx::Rect& clip_bounds_in_texture) {
  ui::SharedResources* instance = ui::SharedResources::GetInstance();
  DCHECK(instance);

  ui::TextureDrawParams modified_params = params;
  modified_params.vertically_flipped = true;

  DrawInternal(*instance->program_no_swizzle(),
               modified_params,
               clip_bounds_in_texture);
}

AcceleratedSurfaceContainerLinuxGLX::AcceleratedSurfaceContainerLinuxGLX(
    const gfx::Size& size)
    : AcceleratedSurfaceContainerLinux(size),
      pixmap_(0),
      glx_pixmap_(0) {
}

bool AcceleratedSurfaceContainerLinuxGLX::Initialize(uint64* surface_id) {
  ui::SharedResources* instance = ui::SharedResources::GetInstance();
  DCHECK(instance);
  instance->MakeSharedContextCurrent();

  if (!AcceleratedSurfaceContainerLinuxGLX::InitializeOneOff())
    return false;

  // Create pixmap from window.
  // We receive a window here rather than a pixmap directly because drivers
  // require (or required) that the pixmap used to create the GL texture be
  // created in the same process as the texture.
  Display* dpy = instance->GetDisplay();
  pixmap_ = XCompositeNameWindowPixmap(dpy, *surface_id);

  // Wrap the pixmap in a GLXPixmap
  const int pixmapAttribs[] = {
    GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
    GLX_TEXTURE_FORMAT_EXT, GLX_TEXTURE_FORMAT_RGB_EXT,
    0
  };

  glx_pixmap_ = glXCreatePixmap(
      dpy, fbconfig_.Get(), pixmap_, pixmapAttribs);

  // Create texture.
  glGenTextures(1, &texture_id_);
  glBindTexture(GL_TEXTURE_2D, texture_id_);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

  return true;
}

AcceleratedSurfaceContainerLinuxGLX::~AcceleratedSurfaceContainerLinuxGLX() {
  ui::SharedResources* instance = ui::SharedResources::GetInstance();
  DCHECK(instance);
  instance->MakeSharedContextCurrent();

  Display* dpy = instance->GetDisplay();
  if (glx_pixmap_)
    glXDestroyGLXPixmap(dpy, glx_pixmap_);
  if (pixmap_)
    XFreePixmap(dpy, pixmap_);
}

void AcceleratedSurfaceContainerLinuxGLX::Draw(
    const ui::TextureDrawParams& params,
    const gfx::Rect& clip_bounds_in_texture) {
  ui::SharedResources* instance = ui::SharedResources::GetInstance();
  DCHECK(instance);

  Display* dpy = instance->GetDisplay();

  glBindTexture(GL_TEXTURE_2D, texture_id_);
  glXBindTexImageEXT(dpy, glx_pixmap_, GLX_FRONT_LEFT_EXT, NULL);
  DrawInternal(*instance->program_no_swizzle(),
               params,
               clip_bounds_in_texture);
  glXReleaseTexImageEXT(dpy, glx_pixmap_, GLX_FRONT_LEFT_EXT);
}

// static
bool AcceleratedSurfaceContainerLinuxGLX::InitializeOneOff()
{
  static bool initialized = false;
  if (initialized)
    return true;

  ui::SharedResources* instance = ui::SharedResources::GetInstance();
  DCHECK(instance);

  Display* dpy = instance->GetDisplay();
  int event_base, error_base;
  if (XCompositeQueryExtension(dpy, &event_base, &error_base)) {
    int major = 0, minor = 2;
    XCompositeQueryVersion(dpy, &major, &minor);
    if (major == 0 && minor < 2) {
      LOG(ERROR) << "Pixmap from window not supported.";
      return false;
    }
  }

  // Wrap the pixmap in a GLXPixmap
  int screen = DefaultScreen(dpy);
  XWindowAttributes gwa;
  XGetWindowAttributes(dpy, RootWindow(dpy, screen), &gwa);
  unsigned int visualid = XVisualIDFromVisual(gwa.visual);

  int nfbconfigs, config;
  scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> fbconfigs(
      glXGetFBConfigs(dpy, screen, &nfbconfigs));

  for (config = 0; config < nfbconfigs; config++) {
    XVisualInfo* visinfo = glXGetVisualFromFBConfig(
        dpy, fbconfigs.get()[config]);
    if (!visinfo || visinfo->visualid != visualid)
      continue;

    int value;
    glXGetFBConfigAttrib(dpy,
                         fbconfigs.get()[config],
                         GLX_DRAWABLE_TYPE,
                         &value);
    if (!(value & GLX_PIXMAP_BIT))
      continue;

    glXGetFBConfigAttrib(dpy,
                         fbconfigs.get()[config],
                         GLX_BIND_TO_TEXTURE_TARGETS_EXT,
                         &value);
    if (!(value & GLX_TEXTURE_2D_BIT_EXT))
      continue;

    glXGetFBConfigAttrib(dpy,
                         fbconfigs.get()[config],
                         GLX_BIND_TO_TEXTURE_RGB_EXT,
                         &value);
    if (value == GL_FALSE)
      continue;

    break;
  }

  if (config == nfbconfigs) {
    LOG(ERROR)
      << "Could not find configuration suitable for binding a pixmap "
      << "as a texture.";
    return false;
  }

  fbconfig_.Get() = fbconfigs.get()[config];

  initialized = true;
  return initialized;
}

AcceleratedSurfaceContainerLinuxOSMesa::AcceleratedSurfaceContainerLinuxOSMesa(
    const gfx::Size& size)
      : AcceleratedSurfaceContainerLinux(size) {
}

bool AcceleratedSurfaceContainerLinuxOSMesa::Initialize(uint64* surface_id) {
  static uint32 next_id = 1;

  ui::SharedResources* instance = ui::SharedResources::GetInstance();
  DCHECK(instance);
  instance->MakeSharedContextCurrent();

  // We expect to make the id here, so don't want the other end giving us one
  DCHECK_EQ(*surface_id, static_cast<uint64>(0));

  // It's possible that this ID gneration could clash with IDs from other
  // AcceleratedSurfaceContainerLinux* objects, however we should never have
  // ids active from more than one type at the same time, so we have free
  // reign of the id namespace.
  *surface_id = next_id++;

  shared_mem_.reset(
      TransportDIB::Create(size_.GetArea() * 4,  // GL_RGBA=4 B/px
                           *surface_id));
  // Create texture.
  glGenTextures(1, &texture_id_);
  glBindTexture(GL_TEXTURE_2D, texture_id_);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

  // we generate the ID to be used here.
  return true;
}

void AcceleratedSurfaceContainerLinuxOSMesa::Draw(
    const ui::TextureDrawParams& params,
    const gfx::Rect& clip_bounds_in_texture) {
  ui::SharedResources* instance = ui::SharedResources::GetInstance();
  DCHECK(instance);

  if (shared_mem_.get()) {
    glBindTexture(GL_TEXTURE_2D, texture_id_);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
                 size_.width(), size_.height(), 0,
                 GL_RGBA, GL_UNSIGNED_BYTE, shared_mem_->memory());

    DrawInternal(*instance->program_no_swizzle(),
                 params,
                 clip_bounds_in_texture);
  }
}

TransportDIB::Handle AcceleratedSurfaceContainerLinuxOSMesa::Handle() const {
  if (shared_mem_.get())
    return shared_mem_->handle();
  else
    return TransportDIB::DefaultHandleValue();
}

AcceleratedSurfaceContainerLinuxOSMesa::
    ~AcceleratedSurfaceContainerLinuxOSMesa() {
}

}  // namespace

AcceleratedSurfaceContainerLinux::AcceleratedSurfaceContainerLinux(
    const gfx::Size& size) : TextureGL(size) {
}

TransportDIB::Handle AcceleratedSurfaceContainerLinux::Handle() const {
  return TransportDIB::DefaultHandleValue();
}

// static
AcceleratedSurfaceContainerLinux*
AcceleratedSurfaceContainerLinux::CreateAcceleratedSurfaceContainer(
    const gfx::Size& size) {
  switch (gfx::GetGLImplementation()) {
    case gfx::kGLImplementationDesktopGL:
      return new AcceleratedSurfaceContainerLinuxGLX(size);
    case gfx::kGLImplementationEGLGLES2:
      return new AcceleratedSurfaceContainerLinuxEGL(size);
    case gfx::kGLImplementationOSMesaGL:
      return new AcceleratedSurfaceContainerLinuxOSMesa(size);
    default:
      NOTREACHED();
      return NULL;
  }
}

void AcceleratedSurfaceContainerLinux::SetCanvas(
    const SkCanvas& canvas,
    const gfx::Point& origin,
    const gfx::Size& overall_size) {
  NOTREACHED();
}

<commit_msg>Unnecessary file.<commit_after><|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef __itkBSplineSyNImageRegistrationMethod_hxx
#define __itkBSplineSyNImageRegistrationMethod_hxx

#include "itkBSplineSyNImageRegistrationMethod.h"

#include "itkBSplineSmoothingOnUpdateDisplacementFieldTransformParametersAdaptor.h"
#include "itkComposeDisplacementFieldsImageFilter.h"
#include "itkImportImageFilter.h"
#include "itkInvertDisplacementFieldImageFilter.h"
#include "itkIterationReporter.h"
#include "itkMultiplyImageFilter.h"
#include "itkWindowConvergenceMonitoringFunction.h"

namespace itk
{
/**
 * Constructor
 */
template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::BSplineSyNImageRegistrationMethod()
{
}

template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::~BSplineSyNImageRegistrationMethod()
{
}

template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
void
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::InitializeRegistrationAtEachLevel( const SizeValueType level )
{
  Superclass::InitializeRegistrationAtEachLevel( level );

  typedef BSplineSmoothingOnUpdateDisplacementFieldTransformParametersAdaptor<OutputTransformType> BSplineDisplacementFieldTransformAdaptorType;

  if( level == 0 )
    {
    this->m_FixedToMiddleTransform->SetSplineOrder( this->m_OutputTransform->GetSplineOrder() );
    this->m_FixedToMiddleTransform->SetNumberOfControlPointsForTheUpdateField(
      dynamic_cast<BSplineDisplacementFieldTransformAdaptorType *>( this->m_TransformParametersAdaptorsPerLevel[0].GetPointer() )->GetNumberOfControlPointsForTheUpdateField() );
    this->m_FixedToMiddleTransform->SetNumberOfControlPointsForTheTotalField(
      dynamic_cast<BSplineDisplacementFieldTransformAdaptorType *>( this->m_TransformParametersAdaptorsPerLevel[0].GetPointer() )->GetNumberOfControlPointsForTheTotalField() );

    this->m_MovingToMiddleTransform->SetSplineOrder( this->m_OutputTransform->GetSplineOrder() );
    this->m_MovingToMiddleTransform->SetNumberOfControlPointsForTheUpdateField(
      dynamic_cast<BSplineDisplacementFieldTransformAdaptorType *>( this->m_TransformParametersAdaptorsPerLevel[0].GetPointer() )->GetNumberOfControlPointsForTheUpdateField() );
    this->m_MovingToMiddleTransform->SetNumberOfControlPointsForTheTotalField(
      dynamic_cast<BSplineDisplacementFieldTransformAdaptorType *>( this->m_TransformParametersAdaptorsPerLevel[0].GetPointer() )->GetNumberOfControlPointsForTheTotalField() );
    }
}

/*
 * Start the optimization at each level.  We just do a basic gradient descent operation.
 */
template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
void
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::StartOptimization()
{
  typedef DisplacementFieldTransform<RealType, ImageDimension> DisplacementFieldTransformType;
  const DisplacementVectorType zeroVector( 0.0 );
  typedef ImageDuplicator<DisplacementFieldType> DisplacementFieldDuplicatorType;
  typename VirtualImageType::ConstPointer virtualDomainImage = this->m_Metric->GetVirtualDomainImage();

  // Monitor the convergence
  typedef itk::Function::WindowConvergenceMonitoringFunction<double> ConvergenceMonitoringType;
  ConvergenceMonitoringType::Pointer convergenceMonitoring = ConvergenceMonitoringType::New();
  convergenceMonitoring->SetWindowSize( 10 );

  typedef IdentityTransform<RealType, ImageDimension> IdentityTransformType;
  typename IdentityTransformType::Pointer identityTransform;
  identityTransform = IdentityTransformType::New();

  IterationReporter reporter( this, 0, 1 );

  this->m_CurrentIteration = 0;
  this->m_IsConverged = false;
  while( this->m_CurrentIteration++ < this->m_NumberOfIterationsPerLevel[this->m_CurrentLevel] && !this->m_IsConverged )
    {
    typename CompositeTransformType::Pointer fixedComposite = CompositeTransformType::New();
    fixedComposite->AddTransform( this->m_FixedInitialTransform );
    fixedComposite->AddTransform( this->m_FixedToMiddleTransform->GetInverseTransform() );
    fixedComposite->FlattenTransformQueue();
    fixedComposite->SetOnlyMostRecentTransformToOptimizeOn();

    typename CompositeTransformType::Pointer movingComposite = CompositeTransformType::New();
    movingComposite->AddTransform( this->m_CompositeTransform );
    movingComposite->AddTransform( this->m_MovingToMiddleTransform->GetInverseTransform() );
    movingComposite->FlattenTransformQueue();
    movingComposite->SetOnlyMostRecentTransformToOptimizeOn();

    // Compute the update fields (to both moving and fixed images) and smooth

    MeasureType fixedMetricValue = 0.0;
    MeasureType movingMetricValue = 0.0;

    DisplacementFieldPointer fixedToMiddleSmoothUpdateField;
    DisplacementFieldPointer movingToMiddleSmoothUpdateField;
    if( this->m_DownsampleImagesForMetricDerivatives )
      {
      typedef ResampleImageFilter<MovingImageType, MovingImageType> MovingResamplerType;
      typename MovingResamplerType::Pointer movingResampler = MovingResamplerType::New();
      movingResampler->SetTransform( movingComposite );
      movingResampler->SetInput( this->m_MovingSmoothImage );
      movingResampler->SetSize( virtualDomainImage->GetRequestedRegion().GetSize() );
      movingResampler->SetOutputOrigin( virtualDomainImage->GetOrigin() );
      movingResampler->SetOutputSpacing( virtualDomainImage->GetSpacing() );
      movingResampler->SetOutputDirection( virtualDomainImage->GetDirection() );
      movingResampler->SetDefaultPixelValue( 0 );
      movingResampler->Update();

      typedef ResampleImageFilter<FixedImageType, FixedImageType> FixedResamplerType;
      typename FixedResamplerType::Pointer fixedResampler = FixedResamplerType::New();
      fixedResampler->SetTransform( fixedComposite );
      fixedResampler->SetInput( this->m_FixedSmoothImage );
      fixedResampler->SetSize( virtualDomainImage->GetRequestedRegion().GetSize() );
      fixedResampler->SetOutputOrigin( virtualDomainImage->GetOrigin() );
      fixedResampler->SetOutputSpacing( virtualDomainImage->GetSpacing() );
      fixedResampler->SetOutputDirection( virtualDomainImage->GetDirection() );
      fixedResampler->SetDefaultPixelValue( 0 );
      fixedResampler->Update();

      typename DisplacementFieldType::Pointer identityField = DisplacementFieldType::New();
      identityField->CopyInformation( virtualDomainImage );
      identityField->SetRegions( virtualDomainImage->GetRequestedRegion() );
      identityField->Allocate();
      identityField->FillBuffer( zeroVector );

      typename DisplacementFieldTransformType::Pointer identityDisplacementFieldTransform = DisplacementFieldTransformType::New();
      identityDisplacementFieldTransform->SetDisplacementField( identityField );

      fixedToMiddleSmoothUpdateField = this->ComputeUpdateField( fixedResampler->GetOutput(), identityTransform,
        movingResampler->GetOutput(), identityDisplacementFieldTransform, movingMetricValue );
      movingToMiddleSmoothUpdateField = this->ComputeUpdateField( movingResampler->GetOutput(), identityTransform,
        fixedResampler->GetOutput(), identityDisplacementFieldTransform, fixedMetricValue );
      }
    else
      {
      fixedToMiddleSmoothUpdateField = this->ComputeUpdateField( this->m_FixedSmoothImage, fixedComposite,
        this->m_MovingSmoothImage, movingComposite, movingMetricValue );
      movingToMiddleSmoothUpdateField = this->ComputeUpdateField( this->m_MovingSmoothImage, movingComposite,
        this->m_FixedSmoothImage, fixedComposite, fixedMetricValue );
      }
    if ( this->m_AverageMidPointGradients )
      {
      ImageRegionIteratorWithIndex<DisplacementFieldType> ItF( fixedToMiddleSmoothUpdateField, fixedToMiddleSmoothUpdateField->GetLargestPossibleRegion() );
      for( ItF.GoToBegin(); !ItF.IsAtEnd(); ++ItF )
        {
        ItF.Set( ItF.Get() - movingToMiddleSmoothUpdateField->GetPixel( ItF.GetIndex() ) );
        movingToMiddleSmoothUpdateField->SetPixel( ItF.GetIndex(), -ItF.Get() );
        }
      }

    // Add the update field to both displacement fields (from fixed/moving to middle image) and then smooth

    typedef ComposeDisplacementFieldsImageFilter<DisplacementFieldType> ComposerType;

    typename ComposerType::Pointer fixedComposer = ComposerType::New();
    fixedComposer->SetDisplacementField( fixedToMiddleSmoothUpdateField );
    fixedComposer->SetWarpingField( this->m_FixedToMiddleTransform->GetDisplacementField() );
    fixedComposer->Update();

    DisplacementFieldPointer fixedToMiddleSmoothTotalFieldTmp = this->BSplineSmoothDisplacementField( fixedComposer->GetOutput(),
      this->m_FixedToMiddleTransform->GetNumberOfControlPointsForTheTotalField() );

    typename ComposerType::Pointer movingComposer = ComposerType::New();
    movingComposer->SetDisplacementField( movingToMiddleSmoothUpdateField );
    movingComposer->SetWarpingField( this->m_MovingToMiddleTransform->GetDisplacementField() );
    movingComposer->Update();

    DisplacementFieldPointer movingToMiddleSmoothTotalFieldTmp = this->BSplineSmoothDisplacementField( movingComposer->GetOutput(),
      this->m_MovingToMiddleTransform->GetNumberOfControlPointsForTheTotalField() );

    // Iteratively estimate the inverse fields.

    DisplacementFieldPointer fixedToMiddleSmoothTotalFieldInverse = this->InvertDisplacementField( fixedToMiddleSmoothTotalFieldTmp, this->m_FixedToMiddleTransform->GetInverseDisplacementField() );
    DisplacementFieldPointer fixedToMiddleSmoothTotalField = this->InvertDisplacementField( fixedToMiddleSmoothTotalFieldInverse, fixedToMiddleSmoothTotalFieldTmp );

    DisplacementFieldPointer movingToMiddleSmoothTotalFieldInverse = this->InvertDisplacementField( movingToMiddleSmoothTotalFieldTmp, this->m_MovingToMiddleTransform->GetInverseDisplacementField() );
    DisplacementFieldPointer movingToMiddleSmoothTotalField = this->InvertDisplacementField( movingToMiddleSmoothTotalFieldInverse, movingToMiddleSmoothTotalFieldTmp );

    // Assign the displacement fields and their inverses to the proper transforms.
    this->m_FixedToMiddleTransform->SetDisplacementField( fixedToMiddleSmoothTotalField );
    this->m_FixedToMiddleTransform->SetInverseDisplacementField( fixedToMiddleSmoothTotalFieldInverse );

    this->m_MovingToMiddleTransform->SetDisplacementField( movingToMiddleSmoothTotalField );
    this->m_MovingToMiddleTransform->SetInverseDisplacementField( movingToMiddleSmoothTotalFieldInverse );

    this->m_CurrentMetricValue = 0.5 * ( movingMetricValue + fixedMetricValue );

    convergenceMonitoring->AddEnergyValue( this->m_CurrentMetricValue );
    this->m_CurrentConvergenceValue = convergenceMonitoring->GetConvergenceValue();

    if( this->m_CurrentConvergenceValue < this->m_ConvergenceThreshold )
      {
      this->m_IsConverged = true;
      }
    reporter.CompletedStep();
    }
}

template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
typename BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>::DisplacementFieldPointer
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::ComputeUpdateField( const FixedImageType * fixedImage, const TransformBaseType * fixedTransform, const MovingImageType * movingImage, const TransformBaseType * movingTransform, MeasureType & value )
{
  typename VirtualImageType::ConstPointer virtualDomainImage = this->m_Metric->GetVirtualDomainImage();

  // pre calculate the voxel distance to be used in properly scaling the gradient.

  this->m_Metric->SetFixedImage( fixedImage );
  this->m_Metric->SetFixedTransform( const_cast<TransformBaseType *>( fixedTransform ) );
  this->m_Metric->SetMovingImage( movingImage );
  this->m_Metric->SetMovingTransform( const_cast<TransformBaseType *>( movingTransform ) );
  this->m_Metric->Initialize();

  typedef typename MetricType::DerivativeType MetricDerivativeType;
  const typename MetricDerivativeType::SizeValueType metricDerivativeSize = virtualDomainImage->GetLargestPossibleRegion().GetNumberOfPixels() * ImageDimension;
  MetricDerivativeType metricDerivative( metricDerivativeSize );

  metricDerivative.Fill( NumericTraits<typename MetricDerivativeType::ValueType>::Zero );
  this->m_Metric->GetValueAndDerivative( value, metricDerivative );

  // we rescale the update velocity field at each time point.
  // we first need to convert to a displacement field to look
  // at the max norm of the field.

  const SizeValueType numberOfPixels = static_cast<SizeValueType>( metricDerivative.Size() / ImageDimension );
  const bool importFilterWillReleaseMemory = false;

  // Brad L. says I should feel bad about using a reinterpret_cast.  I do feel bad.

  DisplacementVectorType *metricDerivativeFieldPointer = reinterpret_cast<DisplacementVectorType *>( metricDerivative.data_block() );

  typedef ImportImageFilter<DisplacementVectorType, ImageDimension> ImporterType;
  typename ImporterType::Pointer importer = ImporterType::New();
  importer->SetImportPointer( metricDerivativeFieldPointer, numberOfPixels, importFilterWillReleaseMemory );
  importer->SetRegion( virtualDomainImage->GetBufferedRegion() );
  importer->SetOrigin( virtualDomainImage->GetOrigin() );
  importer->SetSpacing( virtualDomainImage->GetSpacing() );
  importer->SetDirection( virtualDomainImage->GetDirection() );
  importer->Update();

  DisplacementFieldPointer updateField = this->BSplineSmoothDisplacementField( importer->GetOutput(), this->m_FixedToMiddleTransform->GetNumberOfControlPointsForTheUpdateField() );

  typename DisplacementFieldType::SpacingType spacing = updateField->GetSpacing();
  ImageRegionConstIterator<DisplacementFieldType> ItF( updateField, updateField->GetLargestPossibleRegion() );

  RealType maxNorm = NumericTraits<RealType>::NonpositiveMin();
  for( ItF.GoToBegin(); !ItF.IsAtEnd(); ++ItF )
    {
    DisplacementVectorType vector = ItF.Get();

    RealType localNorm = 0;
    for( unsigned int d = 0; d < ImageDimension; d++ )
      {
      localNorm += vnl_math_sqr( vector[d] / spacing[d] );
      }
    localNorm = vcl_sqrt( localNorm );

    if( localNorm > maxNorm )
      {
      maxNorm = localNorm;
      }
    }

  RealType scale = this->m_LearningRate / maxNorm;

  typedef Image<RealType, ImageDimension> RealImageType;

  typedef MultiplyImageFilter<DisplacementFieldType, RealImageType, DisplacementFieldType> MultiplierType;
  typename MultiplierType::Pointer multiplier = MultiplierType::New();
  multiplier->SetInput( updateField );
  multiplier->SetConstant( scale );

  typename DisplacementFieldType::Pointer scaledUpdateField = multiplier->GetOutput();
  scaledUpdateField->Update();
  scaledUpdateField->DisconnectPipeline();

  return scaledUpdateField;
}

template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
typename BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>::DisplacementFieldPointer
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::BSplineSmoothDisplacementField( const DisplacementFieldType * field, const ArrayType & numberOfControlPoints )
{
  typedef ImageDuplicator<DisplacementFieldType> DuplicatorType;
  typename DuplicatorType::Pointer duplicator = DuplicatorType::New();
  duplicator->SetInputImage( field );
  duplicator->Update();

  DisplacementFieldPointer smoothField = duplicator->GetOutput();

  for( unsigned int d = 0; d < numberOfControlPoints.Size(); d++ )
    {
    if( numberOfControlPoints[d] <= 0 )
      {
      return smoothField;
      }
    }

  typename BSplineFilterType::Pointer bspliner = BSplineFilterType::New();
  bspliner->SetDisplacementField( field );
  bspliner->SetNumberOfControlPoints( numberOfControlPoints );
  bspliner->SetSplineOrder( this->m_FixedToMiddleTransform->GetSplineOrder() );
  bspliner->SetNumberOfFittingLevels( 1 );
  bspliner->SetEnforceStationaryBoundary( true );
  bspliner->SetEstimateInverse( false );
  bspliner->Update();

  smoothField = bspliner->GetOutput();

  return smoothField;
}

} // end namespace itk

#endif
<commit_msg>STYLE:  More unnecessary variables removal.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef __itkBSplineSyNImageRegistrationMethod_hxx
#define __itkBSplineSyNImageRegistrationMethod_hxx

#include "itkBSplineSyNImageRegistrationMethod.h"

#include "itkBSplineSmoothingOnUpdateDisplacementFieldTransformParametersAdaptor.h"
#include "itkComposeDisplacementFieldsImageFilter.h"
#include "itkImportImageFilter.h"
#include "itkInvertDisplacementFieldImageFilter.h"
#include "itkIterationReporter.h"
#include "itkMultiplyImageFilter.h"
#include "itkWindowConvergenceMonitoringFunction.h"

namespace itk
{
/**
 * Constructor
 */
template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::BSplineSyNImageRegistrationMethod()
{
}

template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::~BSplineSyNImageRegistrationMethod()
{
}

template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
void
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::InitializeRegistrationAtEachLevel( const SizeValueType level )
{
  Superclass::InitializeRegistrationAtEachLevel( level );

  typedef BSplineSmoothingOnUpdateDisplacementFieldTransformParametersAdaptor<OutputTransformType> BSplineDisplacementFieldTransformAdaptorType;

  if( level == 0 )
    {
    this->m_FixedToMiddleTransform->SetSplineOrder( this->m_OutputTransform->GetSplineOrder() );
    this->m_FixedToMiddleTransform->SetNumberOfControlPointsForTheUpdateField(
      dynamic_cast<BSplineDisplacementFieldTransformAdaptorType *>( this->m_TransformParametersAdaptorsPerLevel[0].GetPointer() )->GetNumberOfControlPointsForTheUpdateField() );
    this->m_FixedToMiddleTransform->SetNumberOfControlPointsForTheTotalField(
      dynamic_cast<BSplineDisplacementFieldTransformAdaptorType *>( this->m_TransformParametersAdaptorsPerLevel[0].GetPointer() )->GetNumberOfControlPointsForTheTotalField() );

    this->m_MovingToMiddleTransform->SetSplineOrder( this->m_OutputTransform->GetSplineOrder() );
    this->m_MovingToMiddleTransform->SetNumberOfControlPointsForTheUpdateField(
      dynamic_cast<BSplineDisplacementFieldTransformAdaptorType *>( this->m_TransformParametersAdaptorsPerLevel[0].GetPointer() )->GetNumberOfControlPointsForTheUpdateField() );
    this->m_MovingToMiddleTransform->SetNumberOfControlPointsForTheTotalField(
      dynamic_cast<BSplineDisplacementFieldTransformAdaptorType *>( this->m_TransformParametersAdaptorsPerLevel[0].GetPointer() )->GetNumberOfControlPointsForTheTotalField() );
    }
}

/*
 * Start the optimization at each level.  We just do a basic gradient descent operation.
 */
template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
void
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::StartOptimization()
{
  typedef DisplacementFieldTransform<RealType, ImageDimension> DisplacementFieldTransformType;
  const DisplacementVectorType zeroVector( 0.0 );
  typedef ImageDuplicator<DisplacementFieldType> DisplacementFieldDuplicatorType;
  typename VirtualImageType::ConstPointer virtualDomainImage = this->m_Metric->GetVirtualDomainImage();

  // Monitor the convergence
  typedef itk::Function::WindowConvergenceMonitoringFunction<double> ConvergenceMonitoringType;
  ConvergenceMonitoringType::Pointer convergenceMonitoring = ConvergenceMonitoringType::New();
  convergenceMonitoring->SetWindowSize( this->m_ConvergenceWindowSize );

  typedef IdentityTransform<RealType, ImageDimension> IdentityTransformType;
  typename IdentityTransformType::Pointer identityTransform;
  identityTransform = IdentityTransformType::New();

  IterationReporter reporter( this, 0, 1 );

  while( this->m_CurrentIteration++ < this->m_NumberOfIterationsPerLevel[this->m_CurrentLevel] && !this->m_IsConverged )
    {
    typename CompositeTransformType::Pointer fixedComposite = CompositeTransformType::New();
    fixedComposite->AddTransform( this->m_FixedInitialTransform );
    fixedComposite->AddTransform( this->m_FixedToMiddleTransform->GetInverseTransform() );
    fixedComposite->FlattenTransformQueue();
    fixedComposite->SetOnlyMostRecentTransformToOptimizeOn();

    typename CompositeTransformType::Pointer movingComposite = CompositeTransformType::New();
    movingComposite->AddTransform( this->m_CompositeTransform );
    movingComposite->AddTransform( this->m_MovingToMiddleTransform->GetInverseTransform() );
    movingComposite->FlattenTransformQueue();
    movingComposite->SetOnlyMostRecentTransformToOptimizeOn();

    // Compute the update fields (to both moving and fixed images) and smooth

    MeasureType fixedMetricValue = 0.0;
    MeasureType movingMetricValue = 0.0;

    DisplacementFieldPointer fixedToMiddleSmoothUpdateField;
    DisplacementFieldPointer movingToMiddleSmoothUpdateField;
    if( this->m_DownsampleImagesForMetricDerivatives )
      {
      typedef ResampleImageFilter<MovingImageType, MovingImageType> MovingResamplerType;
      typename MovingResamplerType::Pointer movingResampler = MovingResamplerType::New();
      movingResampler->SetTransform( movingComposite );
      movingResampler->SetInput( this->m_MovingSmoothImage );
      movingResampler->SetSize( virtualDomainImage->GetRequestedRegion().GetSize() );
      movingResampler->SetOutputOrigin( virtualDomainImage->GetOrigin() );
      movingResampler->SetOutputSpacing( virtualDomainImage->GetSpacing() );
      movingResampler->SetOutputDirection( virtualDomainImage->GetDirection() );
      movingResampler->SetDefaultPixelValue( 0 );
      movingResampler->Update();

      typedef ResampleImageFilter<FixedImageType, FixedImageType> FixedResamplerType;
      typename FixedResamplerType::Pointer fixedResampler = FixedResamplerType::New();
      fixedResampler->SetTransform( fixedComposite );
      fixedResampler->SetInput( this->m_FixedSmoothImage );
      fixedResampler->SetSize( virtualDomainImage->GetRequestedRegion().GetSize() );
      fixedResampler->SetOutputOrigin( virtualDomainImage->GetOrigin() );
      fixedResampler->SetOutputSpacing( virtualDomainImage->GetSpacing() );
      fixedResampler->SetOutputDirection( virtualDomainImage->GetDirection() );
      fixedResampler->SetDefaultPixelValue( 0 );
      fixedResampler->Update();

      typename DisplacementFieldType::Pointer identityField = DisplacementFieldType::New();
      identityField->CopyInformation( virtualDomainImage );
      identityField->SetRegions( virtualDomainImage->GetRequestedRegion() );
      identityField->Allocate();
      identityField->FillBuffer( zeroVector );

      typename DisplacementFieldTransformType::Pointer identityDisplacementFieldTransform = DisplacementFieldTransformType::New();
      identityDisplacementFieldTransform->SetDisplacementField( identityField );

      fixedToMiddleSmoothUpdateField = this->ComputeUpdateField( fixedResampler->GetOutput(), identityTransform,
        movingResampler->GetOutput(), identityDisplacementFieldTransform, movingMetricValue );
      movingToMiddleSmoothUpdateField = this->ComputeUpdateField( movingResampler->GetOutput(), identityTransform,
        fixedResampler->GetOutput(), identityDisplacementFieldTransform, fixedMetricValue );
      }
    else
      {
      fixedToMiddleSmoothUpdateField = this->ComputeUpdateField( this->m_FixedSmoothImage, fixedComposite,
        this->m_MovingSmoothImage, movingComposite, movingMetricValue );
      movingToMiddleSmoothUpdateField = this->ComputeUpdateField( this->m_MovingSmoothImage, movingComposite,
        this->m_FixedSmoothImage, fixedComposite, fixedMetricValue );
      }
    if ( this->m_AverageMidPointGradients )
      {
      ImageRegionIteratorWithIndex<DisplacementFieldType> ItF( fixedToMiddleSmoothUpdateField, fixedToMiddleSmoothUpdateField->GetLargestPossibleRegion() );
      for( ItF.GoToBegin(); !ItF.IsAtEnd(); ++ItF )
        {
        ItF.Set( ItF.Get() - movingToMiddleSmoothUpdateField->GetPixel( ItF.GetIndex() ) );
        movingToMiddleSmoothUpdateField->SetPixel( ItF.GetIndex(), -ItF.Get() );
        }
      }

    // Add the update field to both displacement fields (from fixed/moving to middle image) and then smooth

    typedef ComposeDisplacementFieldsImageFilter<DisplacementFieldType> ComposerType;

    typename ComposerType::Pointer fixedComposer = ComposerType::New();
    fixedComposer->SetDisplacementField( fixedToMiddleSmoothUpdateField );
    fixedComposer->SetWarpingField( this->m_FixedToMiddleTransform->GetDisplacementField() );
    fixedComposer->Update();

    DisplacementFieldPointer fixedToMiddleSmoothTotalFieldTmp = this->BSplineSmoothDisplacementField( fixedComposer->GetOutput(),
      this->m_FixedToMiddleTransform->GetNumberOfControlPointsForTheTotalField() );

    typename ComposerType::Pointer movingComposer = ComposerType::New();
    movingComposer->SetDisplacementField( movingToMiddleSmoothUpdateField );
    movingComposer->SetWarpingField( this->m_MovingToMiddleTransform->GetDisplacementField() );
    movingComposer->Update();

    DisplacementFieldPointer movingToMiddleSmoothTotalFieldTmp = this->BSplineSmoothDisplacementField( movingComposer->GetOutput(),
      this->m_MovingToMiddleTransform->GetNumberOfControlPointsForTheTotalField() );

    // Iteratively estimate the inverse fields.

    DisplacementFieldPointer fixedToMiddleSmoothTotalFieldInverse = this->InvertDisplacementField( fixedToMiddleSmoothTotalFieldTmp, this->m_FixedToMiddleTransform->GetInverseDisplacementField() );
    DisplacementFieldPointer fixedToMiddleSmoothTotalField = this->InvertDisplacementField( fixedToMiddleSmoothTotalFieldInverse, fixedToMiddleSmoothTotalFieldTmp );

    DisplacementFieldPointer movingToMiddleSmoothTotalFieldInverse = this->InvertDisplacementField( movingToMiddleSmoothTotalFieldTmp, this->m_MovingToMiddleTransform->GetInverseDisplacementField() );
    DisplacementFieldPointer movingToMiddleSmoothTotalField = this->InvertDisplacementField( movingToMiddleSmoothTotalFieldInverse, movingToMiddleSmoothTotalFieldTmp );

    // Assign the displacement fields and their inverses to the proper transforms.
    this->m_FixedToMiddleTransform->SetDisplacementField( fixedToMiddleSmoothTotalField );
    this->m_FixedToMiddleTransform->SetInverseDisplacementField( fixedToMiddleSmoothTotalFieldInverse );

    this->m_MovingToMiddleTransform->SetDisplacementField( movingToMiddleSmoothTotalField );
    this->m_MovingToMiddleTransform->SetInverseDisplacementField( movingToMiddleSmoothTotalFieldInverse );

    this->m_CurrentMetricValue = 0.5 * ( movingMetricValue + fixedMetricValue );

    convergenceMonitoring->AddEnergyValue( this->m_CurrentMetricValue );
    this->m_CurrentConvergenceValue = convergenceMonitoring->GetConvergenceValue();

    if( this->m_CurrentConvergenceValue < this->m_ConvergenceThreshold )
      {
      this->m_IsConverged = true;
      }
    reporter.CompletedStep();
    }
}

template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
typename BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>::DisplacementFieldPointer
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::ComputeUpdateField( const FixedImageType * fixedImage, const TransformBaseType * fixedTransform, const MovingImageType * movingImage, const TransformBaseType * movingTransform, MeasureType & value )
{
  typename VirtualImageType::ConstPointer virtualDomainImage = this->m_Metric->GetVirtualDomainImage();

  // pre calculate the voxel distance to be used in properly scaling the gradient.

  this->m_Metric->SetFixedImage( fixedImage );
  this->m_Metric->SetFixedTransform( const_cast<TransformBaseType *>( fixedTransform ) );
  this->m_Metric->SetMovingImage( movingImage );
  this->m_Metric->SetMovingTransform( const_cast<TransformBaseType *>( movingTransform ) );
  this->m_Metric->Initialize();

  typedef typename MetricType::DerivativeType MetricDerivativeType;
  const typename MetricDerivativeType::SizeValueType metricDerivativeSize = virtualDomainImage->GetLargestPossibleRegion().GetNumberOfPixels() * ImageDimension;
  MetricDerivativeType metricDerivative( metricDerivativeSize );

  metricDerivative.Fill( NumericTraits<typename MetricDerivativeType::ValueType>::Zero );
  this->m_Metric->GetValueAndDerivative( value, metricDerivative );

  // we rescale the update velocity field at each time point.
  // we first need to convert to a displacement field to look
  // at the max norm of the field.

  const SizeValueType numberOfPixels = static_cast<SizeValueType>( metricDerivative.Size() / ImageDimension );
  const bool importFilterWillReleaseMemory = false;

  // Brad L. says I should feel bad about using a reinterpret_cast.  I do feel bad.

  DisplacementVectorType *metricDerivativeFieldPointer = reinterpret_cast<DisplacementVectorType *>( metricDerivative.data_block() );

  typedef ImportImageFilter<DisplacementVectorType, ImageDimension> ImporterType;
  typename ImporterType::Pointer importer = ImporterType::New();
  importer->SetImportPointer( metricDerivativeFieldPointer, numberOfPixels, importFilterWillReleaseMemory );
  importer->SetRegion( virtualDomainImage->GetBufferedRegion() );
  importer->SetOrigin( virtualDomainImage->GetOrigin() );
  importer->SetSpacing( virtualDomainImage->GetSpacing() );
  importer->SetDirection( virtualDomainImage->GetDirection() );
  importer->Update();

  DisplacementFieldPointer updateField = this->BSplineSmoothDisplacementField( importer->GetOutput(), this->m_FixedToMiddleTransform->GetNumberOfControlPointsForTheUpdateField() );

  typename DisplacementFieldType::SpacingType spacing = updateField->GetSpacing();
  ImageRegionConstIterator<DisplacementFieldType> ItF( updateField, updateField->GetLargestPossibleRegion() );

  RealType maxNorm = NumericTraits<RealType>::NonpositiveMin();
  for( ItF.GoToBegin(); !ItF.IsAtEnd(); ++ItF )
    {
    DisplacementVectorType vector = ItF.Get();

    RealType localNorm = 0;
    for( unsigned int d = 0; d < ImageDimension; d++ )
      {
      localNorm += vnl_math_sqr( vector[d] / spacing[d] );
      }
    localNorm = vcl_sqrt( localNorm );

    if( localNorm > maxNorm )
      {
      maxNorm = localNorm;
      }
    }

  RealType scale = this->m_LearningRate / maxNorm;

  typedef Image<RealType, ImageDimension> RealImageType;

  typedef MultiplyImageFilter<DisplacementFieldType, RealImageType, DisplacementFieldType> MultiplierType;
  typename MultiplierType::Pointer multiplier = MultiplierType::New();
  multiplier->SetInput( updateField );
  multiplier->SetConstant( scale );

  typename DisplacementFieldType::Pointer scaledUpdateField = multiplier->GetOutput();
  scaledUpdateField->Update();
  scaledUpdateField->DisconnectPipeline();

  return scaledUpdateField;
}

template<typename TFixedImage, typename TMovingImage, typename TOutputTransform>
typename BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>::DisplacementFieldPointer
BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform>
::BSplineSmoothDisplacementField( const DisplacementFieldType * field, const ArrayType & numberOfControlPoints )
{
  typedef ImageDuplicator<DisplacementFieldType> DuplicatorType;
  typename DuplicatorType::Pointer duplicator = DuplicatorType::New();
  duplicator->SetInputImage( field );
  duplicator->Update();

  DisplacementFieldPointer smoothField = duplicator->GetOutput();

  for( unsigned int d = 0; d < numberOfControlPoints.Size(); d++ )
    {
    if( numberOfControlPoints[d] <= 0 )
      {
      return smoothField;
      }
    }

  typename BSplineFilterType::Pointer bspliner = BSplineFilterType::New();
  bspliner->SetDisplacementField( field );
  bspliner->SetNumberOfControlPoints( numberOfControlPoints );
  bspliner->SetSplineOrder( this->m_FixedToMiddleTransform->GetSplineOrder() );
  bspliner->SetNumberOfFittingLevels( 1 );
  bspliner->SetEnforceStationaryBoundary( true );
  bspliner->SetEstimateInverse( false );
  bspliner->Update();

  smoothField = bspliner->GetOutput();

  return smoothField;
}

} // end namespace itk

#endif
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestOSConeCxx.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This test covers offscreen rendering.
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit

#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"

#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkConeSource.h"

int TestOSConeCxx(int argc, char* argv[])
{
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->OffScreenRenderingOn();

  vtkRenderer *renderer = vtkRenderer::New();
  renWin->AddRenderer(renderer);
  renderer->Delete();

  vtkConeSource *cone=vtkConeSource::New();
  vtkPolyDataMapper *mapper=vtkPolyDataMapper::New();
  mapper->SetInputConnection(cone->GetOutputPort());
  cone->Delete();

  vtkActor *actor=vtkActor::New();
  actor->SetMapper(mapper);
  mapper->Delete();

  renderer->AddActor(actor);
  actor->Delete();

  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);
  renWin->Delete();

  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  // Cleanup
  iren->Delete();

  return !retVal;
}
<commit_msg>BUG:Turn off interactor to stop segfaulting with OSMesa. Temporary fix. See bug #0006072<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestOSConeCxx.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This test covers offscreen rendering.
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit

#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"

#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"
#include "vtkPolyDataMapper.h"
#include "vtkConeSource.h"

int TestOSConeCxx(int argc, char* argv[])
{
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->OffScreenRenderingOn();

  vtkRenderer *renderer = vtkRenderer::New();
  renWin->AddRenderer(renderer);
  renderer->Delete();

  vtkConeSource *cone=vtkConeSource::New();
  vtkPolyDataMapper *mapper=vtkPolyDataMapper::New();
  mapper->SetInputConnection(cone->GetOutputPort());
  cone->Delete();

  vtkActor *actor=vtkActor::New();
  actor->SetMapper(mapper);
  mapper->Delete();

  renderer->AddActor(actor);
  actor->Delete();

#if 0
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);
  renWin->Delete();

  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  // Cleanup
  iren->Delete();
#else // the interactor version fails with OSMesa.
  renWin->Render();
  int retVal = vtkRegressionTestImage( renWin );
  renWin->Delete();
#endif
  return !retVal;
}
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------
// Dan Cristian, Rotaru
//---------------------------------------------------------------------------
#include "Sun.h"

	Sun::Sun() : Sphere() {
	}

	Sun::~Sun(){
		Sphere::~Sphere();
	}

	void Sun::draw(){
		glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, sunOn);
		Sphere::draw();
		glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, sunOff);
	}<commit_msg>Sun.cpp 파일 주석 추가 1. Sun 클래스 생성자, 소멸자 설명 주석 추가 2. draw 멤버 함수 정의 설명 추가 3. opengl 라이브러리 함수 glMaterialfv에 사용된 인자 설명 추가<commit_after>
#include "Sun.h"

        /* Sphere 클래스를 상속 받는 Sun 클래스 생성자 정의 */
	Sun::Sun() : Sphere()
        {
		//void
	}

        /* Sphere 클래스를 상속 받는 클래스 소멸자 정의 */
	Sun::~Sun(){
		Sphere::~Sphere();
	}

        /*
	draw 함수 정의

	기능 : 태양의 재질 속성을 정의하고 태양의 객체를 그리는 프러시저
	인자 : void
	반환 : void
	*/
	void Sun::draw(){
		glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, sunOn);
		Sphere::draw();
		glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, sunOff);

	 /*
	 glMaterialfv

         GL_FRONT_AND_BACK: 태양의 앞면, 뒷면 모두가 속성의 영향을 받음
         GL_EMISSION: 태양은 스스로 발광하는 행성이므로 재질의 속성은 EMISSION
         sunOn: EMISSION의 속성 값을 미리 지정한 상수 배열(노란색)의 포인터
         sunOff: 태양을 그린 후, EMISSION의 속성 값을 미리 설정한 상수 배열(검은색)의 포인터로 초기화
         */
	}
<|endoftext|>