<commit_before>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// *       Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// *       Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// *       Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////

#include <testQuat.h>
#include "ImathQuat.h"
#include "ImathMatrixAlgo.h"
#include "ImathFun.h"
#include "ImathLimits.h"
#include <iostream>
#include <cassert>
#include <cmath>

using namespace std;
using namespace Imath;

namespace {

template <class T>
void
testQuatT ()
{
    const T s = limits<T>::smallest();
    const T e = 4 * limits<T>::epsilon();

    //
    // constructors, r(), v()
    //

    {
	Quat<T> q = Quat<T>();
	assert (q.r == 1 && q.v == Vec3<T> (0, 0, 0));

	q = Quat<T> (2, 3, 4, 5);
	assert (q.r == 2 && q.v == Vec3<T> (3, 4, 5));

	q = Quat<T> (6, Vec3<T> (7, 8, 9));
	assert (q.r == 6 && q.v == Vec3<T> (7, 8, 9));

	Quat<T> q1 = Quat<T> (q);
	assert (q1.r == 6 && q1.v == Vec3<T> (7, 8, 9));
    }

    //
    // invert(), inverse()
    //

    {
	Quat<T> q = Quat<T> (1, 0, 0, 1);
	assert (q.inverse() == Quat<T> (0.5, 0, 0, -0.5));

	q.invert();
	assert (q == Quat<T> (0.5, 0, 0, -0.5));
    }

    //
    // normalize(), normalized()
    //

    {
	Quat<T> q = Quat<T> (2, Vec3<T> (0, 0, 0));
	assert (q.normalized() == Quat<T> (1, 0, 0, 0));

	q.normalize();
	assert (q == Quat<T> (1, 0, 0, 0));

	q = Quat<T> (0, Vec3<T> (0, 2, 0));
	assert (q.normalized() == Quat<T> (0, 0, 1, 0));

	q.normalize();
	assert (q == Quat<T> (0, 0, 1, 0));
    }

    //
    // length()
    //

    {
	Quat<T> q = Quat<T> (3, 0, 4, 0);
	assert (q.length() == 5);
    }

    //
    // setAxisAngle(), angle(), axis()
    //

    {
	Quat<T> q;
	q.setAxisAngle (Vec3<T> (0, 0, 1), M_PI_2);
	Vec3<T> v = q.axis();
	T a = q.angle();
	assert (v.equalWithAbsError (Vec3<T> (0, 0, 1), e));
	assert (Imath::equal (a, T (M_PI_2), e));
    }

    //
    // Accuracy of angle() for very small angles
    // and when real part is slightly greater than 1.
    //

    {
	T t = 10 * Math<T>::sqrt (s);

	Quat<T> q;
	q.setAxisAngle (Vec3<T> (0, 0, 1), t);
	Vec3<T> v = q.axis();
	T a = q.angle();
	assert (v.equalWithAbsError (Vec3<T> (0, 0, 1), e));
	assert (Imath::equal (a, t, t * e));

	q.r *= 1.1;
	q.v *= 1.1;
	v = q.axis();
	a = q.angle();
	assert (v.equalWithAbsError (Vec3<T> (0, 0, 1), e));
	assert (Imath::equal (a, t, t * e));
    }

    {
	T t = 0.001 * Math<T>::sqrt (s);

	Quat<T> q;
	q.setAxisAngle (Vec3<T> (0, 0, 1), t);
	Vec3<T> v = q.axis();
	T a = q.angle();
	assert (v.equalWithAbsError (Vec3<T> (0, 0, 1), e));
	assert (Imath::equal (a, t, t * e));

	q.r *= 1.1;
	q.v *= 1.1;
	v = q.axis();
	a = q.angle();
	assert (v.equalWithAbsError (Vec3<T> (0, 0, 1), e));
	assert (Imath::equal (a, t, t * e));
    }

    //
    // toMatrix33(), toMatrix44()
    //

    {
	Quat<T> q;
	q.setRotation (Vec3<T> (1, 0, 0), Vec3<T> (0, 1, 0));

	Matrix33<T> m1 = q.toMatrix33();

	assert (m1.equalWithAbsError (Matrix33<T> (0, 1, 0,
						  -1, 0, 0,
						   0, 0, 1),
				      e));

	Matrix44<T> m2 = q.toMatrix44();

	assert (m2.equalWithAbsError (Matrix44<T> (0, 1, 0, 0,
						  -1, 0, 0, 0,
						   0, 0, 1, 0,
						   0, 0, 0, 1),
				      e));
    }

    //
    // +, - (unary and binary), ~ *, /, ^
    //

    assert (Quat<T> (1, 2, 3, 4) + Quat<T> (5, 6, 7, 8) ==
	    Quat<T> (6, 8, 10, 12));

    assert (Quat<T> (-1, -2, -3, -4) - Quat<T> (5, 6, 7, 8) ==
	    Quat<T> (-6, -8, -10, -12));

    assert (-Quat<T> (1, 2, 3, 4) == Quat<T> (-1, -2, -3, -4));

    assert (~Quat<T> (1, 2, 3, 4) == Quat<T> (1, -2, -3, -4));

    assert (T (2) * Quat<T> (1, 2, 3, 4) == Quat<T> (2, 4, 6, 8));

    assert (Quat<T> (1, 2, 3, 4) * T (2 )== Quat<T> (2, 4, 6, 8));

    assert (Quat<T> (1, 0, 0, 1) * Quat<T> (1, 1, 0, 0) ==
	    Quat<T> (1, 1, 1, 1));

    assert (Quat<T> (1, 1, 0, 0) * Quat<T> (1, 0, 0, 1) ==
	    Quat<T> (1, 1, -1, 1));

    assert (Quat<T> (1, 0, 0, 1) / Quat<T> (0.5, -0.5, 0, 0) ==
	    Quat<T> (1, 1, 1, 1));

    assert (Quat<T> (2, 4, 6, 8) / T (2) == Quat<T> (1, 2, 3, 4));

    assert ((Quat<T> (1, 2, 3, 4) ^ Quat<T> (2, 2, 2, 2)) == 20);

    //
    // extract()
    //

    {
	Vec3<T> vFrom (1, 0, 0);
	Vec3<T> vTo (0, 1, 1);
	Matrix44<T> m1 = rotationMatrix (vFrom, vTo);

	Quat<T> q = extractQuat (m1);;

	Matrix44<T> m2 = q.toMatrix44();

	assert (m2.equalWithAbsError (m1, 2 * e));
    }
}

void
testQuatConversions ()
{
    {
	Quatf q (1, V3f (2, 3, 4));
	Quatd q1 = Quatd (q);
	assert (q1.r == 1 && q1.v == V3d (2, 3, 4));
    }

    {
	Quatd q (1, V3d (2, 3, 4));
	Quatf q1 = Quatf (q);
	assert (q1.r == 1 && q1.v == V3f (2, 3, 4));
    }
}

} // namespace

void
testQuat ()
{
    cout << "Testing basic quaternion operations" << endl;

    testQuatT<float>();
    testQuatT<double>();
    testQuatConversions();

    cout << "ok\n" << endl;
}
<commit_msg>adding #include "ImathPlatform.h" /* [i_a] M_PI_2 */ to define M_PI_2 for those platforms that haven't got it in the standard run-time lib<commit_after>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// *       Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// *       Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// *       Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////

#include <testQuat.h>
#include "ImathQuat.h"
#include "ImathMatrixAlgo.h"
#include "ImathFun.h"
#include "ImathLimits.h"
#include "ImathPlatform.h" /* [i_a] M_PI_2 */
#include <iostream>
#include <cassert>
#include <cmath>

using namespace std;
using namespace Imath;

namespace {

template <class T>
void
testQuatT ()
{
    const T s = limits<T>::smallest();
    const T e = 4 * limits<T>::epsilon();

    //
    // constructors, r(), v()
    //

    {
	Quat<T> q = Quat<T>();
	assert (q.r == 1 && q.v == Vec3<T> (0, 0, 0));

	q = Quat<T> (2, 3, 4, 5);
	assert (q.r == 2 && q.v == Vec3<T> (3, 4, 5));

	q = Quat<T> (6, Vec3<T> (7, 8, 9));
	assert (q.r == 6 && q.v == Vec3<T> (7, 8, 9));

	Quat<T> q1 = Quat<T> (q);
	assert (q1.r == 6 && q1.v == Vec3<T> (7, 8, 9));
    }

    //
    // invert(), inverse()
    //

    {
	Quat<T> q = Quat<T> (1, 0, 0, 1);
	assert (q.inverse() == Quat<T> (0.5, 0, 0, -0.5));

	q.invert();
	assert (q == Quat<T> (0.5, 0, 0, -0.5));
    }

    //
    // normalize(), normalized()
    //

    {
	Quat<T> q = Quat<T> (2, Vec3<T> (0, 0, 0));
	assert (q.normalized() == Quat<T> (1, 0, 0, 0));

	q.normalize();
	assert (q == Quat<T> (1, 0, 0, 0));

	q = Quat<T> (0, Vec3<T> (0, 2, 0));
	assert (q.normalized() == Quat<T> (0, 0, 1, 0));

	q.normalize();
	assert (q == Quat<T> (0, 0, 1, 0));
    }

    //
    // length()
    //

    {
	Quat<T> q = Quat<T> (3, 0, 4, 0);
	assert (q.length() == 5);
    }

    //
    // setAxisAngle(), angle(), axis()
    //

    {
	Quat<T> q;
	q.setAxisAngle (Vec3<T> (0, 0, 1), M_PI_2);
	Vec3<T> v = q.axis();
	T a = q.angle();
	assert (v.equalWithAbsError (Vec3<T> (0, 0, 1), e));
	assert (Imath::equal (a, T (M_PI_2), e));
    }

    //
    // Accuracy of angle() for very small angles
    // and when real part is slightly greater than 1.
    //

    {
	T t = 10 * Math<T>::sqrt (s);

	Quat<T> q;
	q.setAxisAngle (Vec3<T> (0, 0, 1), t);
	Vec3<T> v = q.axis();
	T a = q.angle();
	assert (v.equalWithAbsError (Vec3<T> (0, 0, 1), e));
	assert (Imath::equal (a, t, t * e));

	q.r *= 1.1;
	q.v *= 1.1;
	v = q.axis();
	a = q.angle();
	assert (v.equalWithAbsError (Vec3<T> (0, 0, 1), e));
	assert (Imath::equal (a, t, t * e));
    }

    {
	T t = 0.001 * Math<T>::sqrt (s);

	Quat<T> q;
	q.setAxisAngle (Vec3<T> (0, 0, 1), t);
	Vec3<T> v = q.axis();
	T a = q.angle();
	assert (v.equalWithAbsError (Vec3<T> (0, 0, 1), e));
	assert (Imath::equal (a, t, t * e));

	q.r *= 1.1;
	q.v *= 1.1;
	v = q.axis();
	a = q.angle();
	assert (v.equalWithAbsError (Vec3<T> (0, 0, 1), e));
	assert (Imath::equal (a, t, t * e));
    }

    //
    // toMatrix33(), toMatrix44()
    //

    {
	Quat<T> q;
	q.setRotation (Vec3<T> (1, 0, 0), Vec3<T> (0, 1, 0));

	Matrix33<T> m1 = q.toMatrix33();

	assert (m1.equalWithAbsError (Matrix33<T> (0, 1, 0,
						  -1, 0, 0,
						   0, 0, 1),
				      e));

	Matrix44<T> m2 = q.toMatrix44();

	assert (m2.equalWithAbsError (Matrix44<T> (0, 1, 0, 0,
						  -1, 0, 0, 0,
						   0, 0, 1, 0,
						   0, 0, 0, 1),
				      e));
    }

    //
    // +, - (unary and binary), ~ *, /, ^
    //

    assert (Quat<T> (1, 2, 3, 4) + Quat<T> (5, 6, 7, 8) ==
	    Quat<T> (6, 8, 10, 12));

    assert (Quat<T> (-1, -2, -3, -4) - Quat<T> (5, 6, 7, 8) ==
	    Quat<T> (-6, -8, -10, -12));

    assert (-Quat<T> (1, 2, 3, 4) == Quat<T> (-1, -2, -3, -4));

    assert (~Quat<T> (1, 2, 3, 4) == Quat<T> (1, -2, -3, -4));

    assert (T (2) * Quat<T> (1, 2, 3, 4) == Quat<T> (2, 4, 6, 8));

    assert (Quat<T> (1, 2, 3, 4) * T (2 )== Quat<T> (2, 4, 6, 8));

    assert (Quat<T> (1, 0, 0, 1) * Quat<T> (1, 1, 0, 0) ==
	    Quat<T> (1, 1, 1, 1));

    assert (Quat<T> (1, 1, 0, 0) * Quat<T> (1, 0, 0, 1) ==
	    Quat<T> (1, 1, -1, 1));

    assert (Quat<T> (1, 0, 0, 1) / Quat<T> (0.5, -0.5, 0, 0) ==
	    Quat<T> (1, 1, 1, 1));

    assert (Quat<T> (2, 4, 6, 8) / T (2) == Quat<T> (1, 2, 3, 4));

    assert ((Quat<T> (1, 2, 3, 4) ^ Quat<T> (2, 2, 2, 2)) == 20);

    //
    // extract()
    //

    {
	Vec3<T> vFrom (1, 0, 0);
	Vec3<T> vTo (0, 1, 1);
	Matrix44<T> m1 = rotationMatrix (vFrom, vTo);

	Quat<T> q = extractQuat (m1);;

	Matrix44<T> m2 = q.toMatrix44();

	assert (m2.equalWithAbsError (m1, 2 * e));
    }
}

void
testQuatConversions ()
{
    {
	Quatf q (1, V3f (2, 3, 4));
	Quatd q1 = Quatd (q);
	assert (q1.r == 1 && q1.v == V3d (2, 3, 4));
    }

    {
	Quatd q (1, V3d (2, 3, 4));
	Quatf q1 = Quatf (q);
	assert (q1.r == 1 && q1.v == V3f (2, 3, 4));
    }
}

} // namespace

void
testQuat ()
{
    cout << "Testing basic quaternion operations" << endl;

    testQuatT<float>();
    testQuatT<double>();
    testQuatConversions();

    cout << "ok\n" << endl;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkImageAccumulate.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to C. Charles Law who developed this class.

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/

#include "vtkImageAccumulate.h"
#include <math.h>
#include <stdlib.h>
#include "vtkObjectFactory.h"

//----------------------------------------------------------------------------
vtkImageAccumulate* vtkImageAccumulate::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageAccumulate");
  if(ret)
    {
    return (vtkImageAccumulate*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkImageAccumulate;
}

//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageAccumulate::vtkImageAccumulate()
{
  int idx;

  for (idx = 0; idx < 3; ++idx)
    {
    this->ComponentSpacing[idx] = 1.0;
    this->ComponentOrigin[idx] = 0.0;
    this->ComponentExtent[idx*2] = 0;
    this->ComponentExtent[idx*2+1] = 0;
    }
  this->ComponentExtent[1] = 255;
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int extent[6])
{
  int idx, modified = 0;

  for (idx = 0; idx < 6; ++idx)
    {
    if (this->ComponentExtent[idx] != extent[idx])
      {
      this->ComponentExtent[idx] = extent[idx];
      this->Modified();
      }
    }
  if (modified)
    {
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int minX, int maxX,
                                            int minY, int maxY,
                                            int minZ, int maxZ)
{
  int extent[6];

  extent[0] = minX;  extent[1] = maxX;
  extent[2] = minY;  extent[3] = maxY;
  extent[4] = minZ;  extent[5] = maxZ;
  this->SetComponentExtent(extent);
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::GetComponentExtent(int extent[6])
{
  int idx;

  for (idx = 0; idx < 6; ++idx)
    {
    extent[idx] = this->ComponentExtent[idx];
    }
}

//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class T>
static void vtkImageAccumulateExecute(vtkImageAccumulate *self,
                               vtkImageData *inData, T *inPtr,
                               vtkImageData *outData, int *outPtr)
{
  int min0, max0, min1, max1, min2, max2;
  int idx0, idx1, idx2, idxC;
  int inInc0, inInc1, inInc2;
  T *inPtr0, *inPtr1, *inPtr2, *inPtrC;
  int *outPtrC;
  int numC, outIdx, *outExtent, *outIncs;
  float *origin, *spacing;
  unsigned long count = 0;
  unsigned long target;

  self = self;

  // Zero count in every bin
  outData->GetExtent(min0, max0, min1, max1, min2, max2);
  memset((void *)outPtr, 0,
         (max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int));

  // Get information to march through data
  numC = inData->GetNumberOfScalarComponents();
  inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2);
  inData->GetIncrements(inInc0, inInc1, inInc2);
  outExtent = outData->GetExtent();
  outIncs = outData->GetIncrements();
  origin = outData->GetOrigin();
  spacing = outData->GetSpacing();

  vtkGenericWarningMacro(<<"Executing with: " << min0 << "," << max0 << " "
  << min1 << "," << max1 << " " << min2 << "," << max2);

  target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)/50.0);
  target++;

  inPtr2 = inPtr;
  for (idx2 = min2; idx2 <= max2; ++idx2)
    {
    inPtr1 = inPtr2;
    for (idx1 = min1; !self->AbortExecute && idx1 <= max1; ++idx1)
      {
      if (!(count%target))
        {
        self->UpdateProgress(count/(50.0*target));
        }
      count++;
      inPtr0  = inPtr1;
      for (idx0 = min0; idx0 <= max0; ++idx0)
        {
        inPtrC = inPtr0;
        // find the bin for this pixel.
        outPtrC = outPtr;
        for (idxC = 0; idxC < numC; ++idxC)
          {
          // compute the index
          outIdx = (int)(((float)*inPtrC - origin[idxC]) / spacing[idxC]);
          if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
            {
            // Out of bin range
            outPtrC = NULL;
            break;
            }
          outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
          ++inPtrC;
          }
        if (outPtrC)
          {
          ++(*outPtrC);
          }

        inPtr0 += inInc0;
        }
      inPtr1 += inInc1;
      }
    inPtr2 += inInc2;
    }
}

//----------------------------------------------------------------------------
// This method is passed a input and output Data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the Datas data types.
void vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out))
{
  void *inPtr;
  void *outPtr;
  vtkImageData *inData = this->GetInput();
  vtkImageData *outData = this->GetOutput();

  vtkDebugMacro(<<"Executing image accumulate");

  // We need to allocate our own scalars since we are overriding
  // the superclasses "Execute()" method.
  outData->SetExtent(outData->GetWholeExtent());
  outData->AllocateScalars();

  inPtr = inData->GetScalarPointer();
  outPtr = outData->GetScalarPointer();

  // Components turned into x, y and z
  if (this->GetInput()->GetNumberOfScalarComponents() > 3)
    {
    vtkErrorMacro("This filter can handle upto 3 components");
    return;
    }

  // this filter expects that output is type int.
  if (outData->GetScalarType() != VTK_INT)
    {
    vtkErrorMacro(<< "Execute: out ScalarType " << outData->GetScalarType()
                  << " must be int\n");
    return;
    }

  switch (inData->GetScalarType())
    {
    vtkTemplateMacro5(vtkImageAccumulateExecute, this,
                      inData, (VTK_TT *)(inPtr),
                      outData, (int *)(outPtr));
    default:
      vtkErrorMacro(<< "Execute: Unknown ScalarType");
      return;
    }
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::ExecuteInformation(vtkImageData *vtkNotUsed(input),
                                            vtkImageData *output)
{
  output->SetWholeExtent(this->ComponentExtent);
  output->SetOrigin(this->ComponentOrigin);
  output->SetSpacing(this->ComponentSpacing);
  output->SetNumberOfScalarComponents(1);
  output->SetScalarType(VTK_INT);
}

//----------------------------------------------------------------------------
// Get ALL of the input.
void vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6],
                                                  int outExt[6])
{
  int *wholeExtent;

  outExt = outExt;
  wholeExtent = this->GetInput()->GetWholeExtent();
  memcpy(inExt, wholeExtent, 6*sizeof(int));
}

void vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkImageToImageFilter::PrintSelf(os,indent);

  os << indent << "ComponentOrigin: ( "
     << this->ComponentOrigin[0] << ", "
     << this->ComponentOrigin[1] << ", "
     << this->ComponentOrigin[2] << " )\n";

  os << indent << "ComponentSpacing: ( "
     << this->ComponentSpacing[0] << ", "
     << this->ComponentSpacing[1] << ", "
     << this->ComponentSpacing[2] << " )\n";

  os << indent << "ComponentExtent: ( "
     << this->ComponentExtent[0] << "," << this->ComponentExtent[1] << " "
     << this->ComponentExtent[2] << "," << this->ComponentExtent[3] << " "
     << this->ComponentExtent[4] << "," << this->ComponentExtent[5] << " }\n";
}

<commit_msg>ERR:Not grabbing right extent<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImageAccumulate.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to C. Charles Law who developed this class.

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/

#include "vtkImageAccumulate.h"
#include <math.h>
#include <stdlib.h>
#include "vtkObjectFactory.h"

//----------------------------------------------------------------------------
vtkImageAccumulate* vtkImageAccumulate::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageAccumulate");
  if(ret)
    {
    return (vtkImageAccumulate*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkImageAccumulate;
}

//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageAccumulate::vtkImageAccumulate()
{
  int idx;

  for (idx = 0; idx < 3; ++idx)
    {
    this->ComponentSpacing[idx] = 1.0;
    this->ComponentOrigin[idx] = 0.0;
    this->ComponentExtent[idx*2] = 0;
    this->ComponentExtent[idx*2+1] = 0;
    }
  this->ComponentExtent[1] = 255;
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int extent[6])
{
  int idx, modified = 0;

  for (idx = 0; idx < 6; ++idx)
    {
    if (this->ComponentExtent[idx] != extent[idx])
      {
      this->ComponentExtent[idx] = extent[idx];
      this->Modified();
      }
    }
  if (modified)
    {
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int minX, int maxX,
                                            int minY, int maxY,
                                            int minZ, int maxZ)
{
  int extent[6];

  extent[0] = minX;  extent[1] = maxX;
  extent[2] = minY;  extent[3] = maxY;
  extent[4] = minZ;  extent[5] = maxZ;
  this->SetComponentExtent(extent);
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::GetComponentExtent(int extent[6])
{
  int idx;

  for (idx = 0; idx < 6; ++idx)
    {
    extent[idx] = this->ComponentExtent[idx];
    }
}

//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class T>
static void vtkImageAccumulateExecute(vtkImageAccumulate *self,
                               vtkImageData *inData, T *inPtr,
                               vtkImageData *outData, int *outPtr)
{
  int min0, max0, min1, max1, min2, max2;
  int idx0, idx1, idx2, idxC;
  int inInc0, inInc1, inInc2;
  T *inPtr0, *inPtr1, *inPtr2, *inPtrC;
  int *outPtrC;
  int numC, outIdx, *outExtent, *outIncs;
  float *origin, *spacing;
  unsigned long count = 0;
  unsigned long target;

  self = self;

  // Zero count in every bin
  outData->GetExtent(min0, max0, min1, max1, min2, max2);
  memset((void *)outPtr, 0,
         (max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int));

  // Get information to march through data
  numC = inData->GetNumberOfScalarComponents();
  inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2);
  inData->GetIncrements(inInc0, inInc1, inInc2);
  outExtent = outData->GetExtent();
  outIncs = outData->GetIncrements();
  origin = outData->GetOrigin();
  spacing = outData->GetSpacing();

  vtkGenericWarningMacro(<<"Executing with: " << min0 << "," << max0 << " "
  << min1 << "," << max1 << " " << min2 << "," << max2);

  target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)/50.0);
  target++;

  inPtr2 = inPtr;
  for (idx2 = min2; idx2 <= max2; ++idx2)
    {
    inPtr1 = inPtr2;
    for (idx1 = min1; !self->AbortExecute && idx1 <= max1; ++idx1)
      {
      if (!(count%target))
        {
        self->UpdateProgress(count/(50.0*target));
        }
      count++;
      inPtr0  = inPtr1;
      for (idx0 = min0; idx0 <= max0; ++idx0)
        {
        inPtrC = inPtr0;
        // find the bin for this pixel.
        outPtrC = outPtr;
        for (idxC = 0; idxC < numC; ++idxC)
          {
          // compute the index
          outIdx = (int)(((float)*inPtrC - origin[idxC]) / spacing[idxC]);
          if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
            {
            // Out of bin range
            outPtrC = NULL;
            break;
            }
          outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
          ++inPtrC;
          }
        if (outPtrC)
          {
          ++(*outPtrC);
          }

        inPtr0 += inInc0;
        }
      inPtr1 += inInc1;
      }
    inPtr2 += inInc2;
    }
}

//----------------------------------------------------------------------------
// This method is passed a input and output Data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the Datas data types.
void vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out))
{
  void *inPtr;
  void *outPtr;
  vtkImageData *inData = this->GetInput();
  vtkImageData *outData = this->GetOutput();

  vtkDebugMacro(<<"Executing image accumulate");

  // We need to allocate our own scalars since we are overriding
  // the superclasses "Execute()" method.
  outData->SetExtent(outData->GetWholeExtent());
  outData->AllocateScalars();

  inPtr = inData->GetScalarPointerForExtent(inData->GetUpdateExtent());
  outPtr = outData->GetScalarPointer();

  // Components turned into x, y and z
  if (this->GetInput()->GetNumberOfScalarComponents() > 3)
    {
    vtkErrorMacro("This filter can handle upto 3 components");
    return;
    }

  // this filter expects that output is type int.
  if (outData->GetScalarType() != VTK_INT)
    {
    vtkErrorMacro(<< "Execute: out ScalarType " << outData->GetScalarType()
                  << " must be int\n");
    return;
    }

  switch (inData->GetScalarType())
    {
    vtkTemplateMacro5(vtkImageAccumulateExecute, this,
                      inData, (VTK_TT *)(inPtr),
                      outData, (int *)(outPtr));
    default:
      vtkErrorMacro(<< "Execute: Unknown ScalarType");
      return;
    }
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::ExecuteInformation(vtkImageData *vtkNotUsed(input),
                                            vtkImageData *output)
{
  output->SetWholeExtent(this->ComponentExtent);
  output->SetOrigin(this->ComponentOrigin);
  output->SetSpacing(this->ComponentSpacing);
  output->SetNumberOfScalarComponents(1);
  output->SetScalarType(VTK_INT);
}

//----------------------------------------------------------------------------
// Get ALL of the input.
void vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6],
                                                  int outExt[6])
{
  int *wholeExtent;

  outExt = outExt;
  wholeExtent = this->GetInput()->GetWholeExtent();
  memcpy(inExt, wholeExtent, 6*sizeof(int));
}

void vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkImageToImageFilter::PrintSelf(os,indent);

  os << indent << "ComponentOrigin: ( "
     << this->ComponentOrigin[0] << ", "
     << this->ComponentOrigin[1] << ", "
     << this->ComponentOrigin[2] << " )\n";

  os << indent << "ComponentSpacing: ( "
     << this->ComponentSpacing[0] << ", "
     << this->ComponentSpacing[1] << ", "
     << this->ComponentSpacing[2] << " )\n";

  os << indent << "ComponentExtent: ( "
     << this->ComponentExtent[0] << "," << this->ComponentExtent[1] << " "
     << this->ComponentExtent[2] << "," << this->ComponentExtent[3] << " "
     << this->ComponentExtent[4] << "," << this->ComponentExtent[5] << " }\n";
}

<|endoftext|>


<commit_before><commit_msg>Remove extra string "///" before the image in method headers.<commit_after><|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkDiffusionIOMimeTypes.h"
#include "mitkIOMimeTypes.h"
#include <itksys/SystemTools.hxx>
#include <itkNrrdImageIO.h>
#include <itkMetaDataDictionary.h>
#include <itkMetaDataObject.h>

namespace mitk
{

std::vector<CustomMimeType*> DiffusionIOMimeTypes::Get()
{
  std::vector<CustomMimeType*> mimeTypes;

  // order matters here (descending rank for mime types)

  mimeTypes.push_back(DWI_MIMETYPE().Clone());
  mimeTypes.push_back(DTI_MIMETYPE().Clone());
  mimeTypes.push_back(QBI_MIMETYPE().Clone());

  mimeTypes.push_back(FIBERBUNDLE_MIMETYPE().Clone());

  mimeTypes.push_back(CONNECTOMICS_MIMETYPE().Clone());

  return mimeTypes;
}

// Mime Types

CustomMimeType DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE()
{
  CustomMimeType mimeType(FIBERBUNDLE_MIMETYPE_NAME());
  std::string category = "Fiber Bundle File";
  mimeType.SetComment("Fiber Bundles");
  mimeType.SetCategory(category);
  mimeType.AddExtension("fib");
  mimeType.AddExtension("trk");
  //mimeType.AddExtension("vtk");
  return mimeType;
}

DiffusionIOMimeTypes::DwiMimeType::DwiMimeType()
  : CustomMimeType(DWI_MIMETYPE_NAME())
{
  std::string category = "Diffusion Weighted Image";
  this->SetCategory(category);
  this->SetComment("Diffusion Weighted Images");

  this->AddExtension("dwi");
  this->AddExtension("hdwi");
  this->AddExtension("fsl");
  this->AddExtension("fslgz");
  this->AddExtension("nrrd");
}

bool DiffusionIOMimeTypes::DwiMimeType::AppliesTo(const std::string &path) const
{
  bool canRead( CustomMimeType::AppliesTo(path) );

  // fix for bug 18572
  // Currently this function is called for writing as well as reading, in that case
  // the image information can of course not be read
  // This is a bug, this function should only be called for reading.
  if( ! itksys::SystemTools::FileExists( path.c_str() ) )
  {
    return canRead;
  }
  //end fix for bug 18572

  std::string ext = itksys::SystemTools::GetFilenameLastExtension( path );
  ext = itksys::SystemTools::LowerCase( ext );

  // Simple NRRD files should only be considered for this mime type if they contain
  // corresponding tags
  if( ext == ".nrrd" )
  {
    itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
    io->SetFileName(path);
    io->ReadImageInformation();

    itk::MetaDataDictionary imgMetaDictionary = io->GetMetaDataDictionary();
    std::vector<std::string> imgMetaKeys = imgMetaDictionary.GetKeys();
    std::vector<std::string>::const_iterator itKey = imgMetaKeys.begin();
    std::string metaString;

    for (; itKey != imgMetaKeys.end(); itKey ++)
    {
      itk::ExposeMetaData<std::string> (imgMetaDictionary, *itKey, metaString);
      if (itKey->find("modality") != std::string::npos)
      {
        if (metaString.find("DWMRI") != std::string::npos)
        {
          return canRead;
        }
      }
    }

    canRead = false;
  }

  return canRead;
}

DiffusionIOMimeTypes::DwiMimeType* DiffusionIOMimeTypes::DwiMimeType::Clone() const
{
  return new DwiMimeType(*this);
}

DiffusionIOMimeTypes::DwiMimeType DiffusionIOMimeTypes::DWI_MIMETYPE()
{
  return DwiMimeType();
}

CustomMimeType DiffusionIOMimeTypes::DTI_MIMETYPE()
{
  CustomMimeType mimeType(DTI_MIMETYPE_NAME());
  std::string category = "Tensor Images";
  mimeType.SetComment("Diffusion Tensor Images");
  mimeType.SetCategory(category);
  mimeType.AddExtension("dti");
  mimeType.AddExtension("hdti");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::QBI_MIMETYPE()
{
  CustomMimeType mimeType(QBI_MIMETYPE_NAME());
  std::string category = "Q-Ball Images";
  mimeType.SetComment("Diffusion Q-Ball Images");
  mimeType.SetCategory(category);
  mimeType.AddExtension("qbi");
  mimeType.AddExtension("hqbi");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE()
{
  CustomMimeType mimeType(CONNECTOMICS_MIMETYPE_NAME());
  std::string category = "Connectomics Networks";
  mimeType.SetComment("Connectomics Networks");
  mimeType.SetCategory(category);
  mimeType.AddExtension("cnf");
  return mimeType;
}

// Names
std::string DiffusionIOMimeTypes::DWI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".dwi";
  return name;
}

std::string DiffusionIOMimeTypes::DTI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".dti";
  return name;
}

std::string DiffusionIOMimeTypes::QBI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".qbi";
  return name;
}

std::string DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".fib";
  return name;
}

std::string DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".cnf";
  return name;
}

// Descriptions
std::string DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_DESCRIPTION()
{
  static std::string description = "Fiberbundles";
  return description;
}

std::string DiffusionIOMimeTypes::DWI_MIMETYPE_DESCRIPTION()
{
  static std::string description = "Diffusion Weighted Images";
  return description;
}

std::string DiffusionIOMimeTypes::DTI_MIMETYPE_DESCRIPTION()
{
  static std::string description = "Diffusion Tensor Images";
  return description;
}

std::string DiffusionIOMimeTypes::QBI_MIMETYPE_DESCRIPTION()
{
  static std::string description = "Q-Ball Images";
  return description;
}

std::string DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_DESCRIPTION()
{
  static std::string description = "Connectomics Networks";
  return description;
}

}
<commit_msg>COMP: Catch exceptions if the file can not be opened for reading image information<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkDiffusionIOMimeTypes.h"
#include "mitkIOMimeTypes.h"
#include <itksys/SystemTools.hxx>
#include <itkNrrdImageIO.h>
#include <itkMetaDataDictionary.h>
#include <itkMetaDataObject.h>
#include <mitkLogMacros.h>

namespace mitk
{

std::vector<CustomMimeType*> DiffusionIOMimeTypes::Get()
{
  std::vector<CustomMimeType*> mimeTypes;

  // order matters here (descending rank for mime types)

  mimeTypes.push_back(DWI_MIMETYPE().Clone());
  mimeTypes.push_back(DTI_MIMETYPE().Clone());
  mimeTypes.push_back(QBI_MIMETYPE().Clone());

  mimeTypes.push_back(FIBERBUNDLE_MIMETYPE().Clone());

  mimeTypes.push_back(CONNECTOMICS_MIMETYPE().Clone());

  return mimeTypes;
}

// Mime Types

CustomMimeType DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE()
{
  CustomMimeType mimeType(FIBERBUNDLE_MIMETYPE_NAME());
  std::string category = "Fiber Bundle File";
  mimeType.SetComment("Fiber Bundles");
  mimeType.SetCategory(category);
  mimeType.AddExtension("fib");
  mimeType.AddExtension("trk");
  //mimeType.AddExtension("vtk");
  return mimeType;
}

DiffusionIOMimeTypes::DwiMimeType::DwiMimeType()
  : CustomMimeType(DWI_MIMETYPE_NAME())
{
  std::string category = "Diffusion Weighted Image";
  this->SetCategory(category);
  this->SetComment("Diffusion Weighted Images");

  this->AddExtension("dwi");
  this->AddExtension("hdwi");
  this->AddExtension("fsl");
  this->AddExtension("fslgz");
  this->AddExtension("nrrd");
}

bool DiffusionIOMimeTypes::DwiMimeType::AppliesTo(const std::string &path) const
{
  bool canRead( CustomMimeType::AppliesTo(path) );

  // fix for bug 18572
  // Currently this function is called for writing as well as reading, in that case
  // the image information can of course not be read
  // This is a bug, this function should only be called for reading.
  if( ! itksys::SystemTools::FileExists( path.c_str() ) )
  {
    return canRead;
  }
  //end fix for bug 18572

  std::string ext = itksys::SystemTools::GetFilenameLastExtension( path );
  ext = itksys::SystemTools::LowerCase( ext );

  // Simple NRRD files should only be considered for this mime type if they contain
  // corresponding tags
  if( ext == ".nrrd" )
  {
    itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
    io->SetFileName(path);
    try
    {
      io->ReadImageInformation();

      itk::MetaDataDictionary imgMetaDictionary = io->GetMetaDataDictionary();
      std::vector<std::string> imgMetaKeys = imgMetaDictionary.GetKeys();
      std::vector<std::string>::const_iterator itKey = imgMetaKeys.begin();
      std::string metaString;

      for (; itKey != imgMetaKeys.end(); itKey ++)
      {
        itk::ExposeMetaData<std::string> (imgMetaDictionary, *itKey, metaString);
        if (itKey->find("modality") != std::string::npos)
        {
          if (metaString.find("DWMRI") != std::string::npos)
          {
            return canRead;
          }
        }
      }

    }
    catch( const itk::ExceptionObject &e )
    {
      MITK_ERROR << "ITK Exception: " << e.what();
    }
    canRead = false;
  }

  return canRead;
}

DiffusionIOMimeTypes::DwiMimeType* DiffusionIOMimeTypes::DwiMimeType::Clone() const
{
  return new DwiMimeType(*this);
}

DiffusionIOMimeTypes::DwiMimeType DiffusionIOMimeTypes::DWI_MIMETYPE()
{
  return DwiMimeType();
}

CustomMimeType DiffusionIOMimeTypes::DTI_MIMETYPE()
{
  CustomMimeType mimeType(DTI_MIMETYPE_NAME());
  std::string category = "Tensor Images";
  mimeType.SetComment("Diffusion Tensor Images");
  mimeType.SetCategory(category);
  mimeType.AddExtension("dti");
  mimeType.AddExtension("hdti");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::QBI_MIMETYPE()
{
  CustomMimeType mimeType(QBI_MIMETYPE_NAME());
  std::string category = "Q-Ball Images";
  mimeType.SetComment("Diffusion Q-Ball Images");
  mimeType.SetCategory(category);
  mimeType.AddExtension("qbi");
  mimeType.AddExtension("hqbi");
  return mimeType;
}

CustomMimeType DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE()
{
  CustomMimeType mimeType(CONNECTOMICS_MIMETYPE_NAME());
  std::string category = "Connectomics Networks";
  mimeType.SetComment("Connectomics Networks");
  mimeType.SetCategory(category);
  mimeType.AddExtension("cnf");
  return mimeType;
}

// Names
std::string DiffusionIOMimeTypes::DWI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".dwi";
  return name;
}

std::string DiffusionIOMimeTypes::DTI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".dti";
  return name;
}

std::string DiffusionIOMimeTypes::QBI_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".qbi";
  return name;
}

std::string DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".fib";
  return name;
}

std::string DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_NAME()
{
  static std::string name = IOMimeTypes::DEFAULT_BASE_NAME() + ".cnf";
  return name;
}

// Descriptions
std::string DiffusionIOMimeTypes::FIBERBUNDLE_MIMETYPE_DESCRIPTION()
{
  static std::string description = "Fiberbundles";
  return description;
}

std::string DiffusionIOMimeTypes::DWI_MIMETYPE_DESCRIPTION()
{
  static std::string description = "Diffusion Weighted Images";
  return description;
}

std::string DiffusionIOMimeTypes::DTI_MIMETYPE_DESCRIPTION()
{
  static std::string description = "Diffusion Tensor Images";
  return description;
}

std::string DiffusionIOMimeTypes::QBI_MIMETYPE_DESCRIPTION()
{
  static std::string description = "Q-Ball Images";
  return description;
}

std::string DiffusionIOMimeTypes::CONNECTOMICS_MIMETYPE_DESCRIPTION()
{
  static std::string description = "Connectomics Networks";
  return description;
}

}
<|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.
 *
 *=========================================================================*/

#include "itkCastImageFilter.h"
#include "itkRandomImageSource.h"
#include "itkVectorImage.h"
#include <iostream>
#include "itkFloatingPointExceptions.h"

// Better name demanging for gcc
#if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ > 0 )
#ifndef __EMSCRIPTEN__
#define GCC_USEDEMANGLE
#endif
#endif

#ifdef GCC_USEDEMANGLE
#include <cstdlib>
#include <cxxabi.h>
#include "itkMath.h"
#endif

template< typename T >
std::string GetCastTypeName()
{
  std::string name;
#ifdef GCC_USEDEMANGLE
  char const *mangledName = typeid( T ).name();
  int         status;
  char *      unmangled = abi::__cxa_demangle(mangledName, nullptr, nullptr, &status);
  name = unmangled;
  free(unmangled);
#else
  name = typeid( T ).name();
#endif

  return name;
}

template < typename TInputPixelType, typename TOutputPixelType >
bool TestCastFromTo()
{
  using InputImageType = itk::Image< TInputPixelType, 3 >;
  using OutputImageType = itk::Image< TOutputPixelType, 3 >;
  using FilterType = itk::CastImageFilter< InputImageType, OutputImageType >;

  using SourceType = itk::RandomImageSource< InputImageType >;
  typename SourceType::Pointer source = SourceType::New();

  typename InputImageType::SizeValueType randomSize[3] = {18, 17, 23};
  source->SetSize( randomSize );

  typename FilterType::Pointer filter = FilterType::New();
  filter->SetInput( source->GetOutput() );
  filter->UpdateLargestPossibleRegion();

  using InputIteratorType = itk::ImageRegionConstIterator< InputImageType >;
  using OutputIteratorType = itk::ImageRegionConstIterator< OutputImageType >;

  InputIteratorType  it( source->GetOutput(),
                         source->GetOutput()->GetLargestPossibleRegion() );
  OutputIteratorType ot( filter->GetOutput(),
                         filter->GetOutput()->GetLargestPossibleRegion() );

  bool success = true;

  std::cout << "Casting from " << GetCastTypeName< TInputPixelType >()
            << " to " << GetCastTypeName< TOutputPixelType >() << " ... ";

  it.GoToBegin();
  ot.GoToBegin();
  while ( !it.IsAtEnd() )
    {
    TInputPixelType  inValue  = it.Value();
    TOutputPixelType outValue = ot.Value();
    auto expectedValue = static_cast< TOutputPixelType >( inValue );

    /** Warning:
     * expectedValue == static_cast< TOutputPixelType( inValue ) is
     * false on some systems and compilers with some values of inValue. */
#if defined(__MINGW32__)
    if ( itk::Math::NotAlmostEquals(outValue, expectedValue) )
#else
    if ( itk::Math::NotExactlyEquals(outValue, expectedValue) )
#endif
      {
      std::cerr << "ERROR: " << outValue << " != " << expectedValue << std::endl;
      success = false;
      break;
      }

    ++it;
    ++ot;
    }

  if ( success )
    {
    std::cout << "[PASSED]" << std::endl;
    }
  else
    {
    std::cout << "[FAILED]" << std::endl;
    }

  return success;
}

template < typename TInputPixelType >
bool TestCastFrom()
{
  bool success = true;
  success &= TestCastFromTo< TInputPixelType, char >();
  success &= TestCastFromTo< TInputPixelType, signed char >();
  success &= TestCastFromTo< TInputPixelType, unsigned char >();
  success &= TestCastFromTo< TInputPixelType, short >();
  success &= TestCastFromTo< TInputPixelType, unsigned short >();
  success &= TestCastFromTo< TInputPixelType, int >();
  success &= TestCastFromTo< TInputPixelType, unsigned int >();
  success &= TestCastFromTo< TInputPixelType, long >();
  success &= TestCastFromTo< TInputPixelType, unsigned long >();
  success &= TestCastFromTo< TInputPixelType, long long >();
  success &= TestCastFromTo< TInputPixelType, unsigned long long >();
  success &= TestCastFromTo< TInputPixelType, float >();
  success &= TestCastFromTo< TInputPixelType, double >();

  return success;
}

bool TestVectorImageCast()
{
  // This function casts a VectorImage<float, 2>
  // to a VectorImage<unsigned char, 2>
  std::cout << "Casting from a VectorImage<float, 2> \
                to VectorImage<unsigned char, 2> ..." << std::endl;

  using UnsignedCharVectorImageType = itk::VectorImage<unsigned char, 2>;
  using FloatVectorImageType = itk::VectorImage<float, 2>;

  // Create a 1x3 image of 2D vectors
  FloatVectorImageType::Pointer image = FloatVectorImageType::New();

  itk::Size<2> size;
  size[0] = 1;
  size[1] = 3;

  itk::Index<2> start;
  start.Fill(0);

  itk::ImageRegion<2> region(start,size);
  image->SetNumberOfComponentsPerPixel(2);
  image->SetRegions(region);
  image->Allocate();
  itk::VariableLengthVector<float> vec;
  vec.SetSize(2);
  // All pixels will be the vector (1.3, 5.3)
  vec[0] = 1.3;
  vec[1] = 5.3;
  image->FillBuffer(vec);

  using CastImageFilterType = itk::CastImageFilter< FloatVectorImageType,
               UnsignedCharVectorImageType >;
  CastImageFilterType::Pointer castImageFilter = CastImageFilterType::New();
  castImageFilter->SetInput(image);
  castImageFilter->Update();

  // Setup iterators for the original and casted images
  itk::ImageRegionConstIterator<UnsignedCharVectorImageType>
       castedImageIterator(castImageFilter->GetOutput(),
       castImageFilter->GetOutput()->GetLargestPossibleRegion());

  itk::ImageRegionConstIterator<FloatVectorImageType>
    originalImageIterator(image, image->GetLargestPossibleRegion());

  // Compare both dimensions of all of the pixels from the manually
  // casted original image to the corresponding pixels in the filter-casted
  // image
  bool success = true;
  while(!originalImageIterator.IsAtEnd())
    {
    if(static_cast<unsigned char>(originalImageIterator.Get()[0]) !=
                                  castedImageIterator.Get()[0] ||
       static_cast<unsigned char>(originalImageIterator.Get()[1]) !=
                                  castedImageIterator.Get()[1])
      {
      std::cerr << "Error in TestVectorImageCast!" << std::endl;
      success = false;
      }
    ++originalImageIterator;
    ++castedImageIterator;
    }

  if ( success )
    {
    std::cout << "[PASSED]" << std::endl;
    }
  else
    {
    std::cout << "[FAILED]" << std::endl;
    }

  return success;
}

int itkCastImageFilterTest( int, char* [] )
{
  std::cout << "itkCastImageFilterTest Start" << std::endl;

  // This test casts floats to char, generating float point exceptions.
  // We disable float point exceptions only for this tests
  bool fpeSupport = itk::FloatingPointExceptions::HasFloatingPointExceptionsSupport();
  bool fpeStatus = itk::FloatingPointExceptions::GetEnabled();
  if (fpeSupport && fpeStatus)
    {
    std::cout << "FloatingPointExceptions are disabled only for this test." << std::endl;
    itk::FloatingPointExceptions::Disable();
    }

  bool success = true;
  success &= TestCastFrom< char >();
  success &= TestCastFrom< signed char >();
  success &= TestCastFrom< unsigned char >();
  success &= TestCastFrom< short >();
  success &= TestCastFrom< unsigned short >();
  success &= TestCastFrom< int >();
  success &= TestCastFrom< unsigned int >();
  success &= TestCastFrom< long >();
  success &= TestCastFrom< unsigned long >();
  success &= TestCastFrom< long long >();
  success &= TestCastFrom< unsigned long long >();
  success &= TestCastFrom< float >();
  success &= TestCastFrom< double >();
  success &= TestVectorImageCast();

  std::cout << std::endl;
  if ( !success )
    {
    std::cout << "An itkCastImageFilter test FAILED." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "All itkCastImageFilter tests PASSED." << std::endl;

  return EXIT_SUCCESS;
}
<commit_msg>ENH: Fix deficient itkCastImageFilter test<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.
 *
 *=========================================================================*/

#include "itkCastImageFilter.h"
#include "itkRandomImageSource.h"
#include "itkVectorImage.h"
#include <iostream>
#include "itkFloatingPointExceptions.h"

// Better name demanging for gcc
#if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ > 0 )
#ifndef __EMSCRIPTEN__
#define GCC_USEDEMANGLE
#endif
#endif

#ifdef GCC_USEDEMANGLE
#include <cstdlib>
#include <cxxabi.h>
#include "itkMath.h"
#endif

template< typename T >
std::string GetCastTypeName()
{
  std::string name;
#ifdef GCC_USEDEMANGLE
  char const *mangledName = typeid( T ).name();
  int         status;
  char *      unmangled = abi::__cxa_demangle(mangledName, nullptr, nullptr, &status);
  name = unmangled;
  free(unmangled);
#else
  name = typeid( T ).name();
#endif

  return name;
}

template < typename TInputPixelType, typename TOutputPixelType >
bool TestCastFromTo()
{
  using InputImageType = itk::Image< TInputPixelType, 3 >;
  using OutputImageType = itk::Image< TOutputPixelType, 3 >;
  using FilterType = itk::CastImageFilter< InputImageType, OutputImageType >;

  using SourceType = itk::RandomImageSource< InputImageType >;
  typename SourceType::Pointer source = SourceType::New();
  typename InputImageType::SizeValueType randomSize[3] = {18, 17, 23};
  source->SetSize( randomSize );

  source->UpdateLargestPossibleRegion();
  typename InputImageType::Pointer randomSourceImagePtr = source->GetOutput();
  {
    typename InputImageType::IndexType Index000 {0,0,0};
    typename InputImageType::IndexType Index100 {1,0,0};
    typename InputImageType::IndexType Index200 {2,0,0};
    typename InputImageType::IndexType Index300 {3,0,0};
    typename InputImageType::IndexType Index400 {4,0,0};

    /* Exercise input image type domain values (important for float -> integer conversions)
     *
     * Casting a float/double to an integer when integer isn't big enough to hold the value yields undefined behaviour.
     *
     * [n3290: 4.9/1]: A prvalue of a floating point type can be converted to a prvalue of an integer type.
     *  The conversion truncates; that is, the fractional part is discarded.
     *
     *  The behavior is undefined if the truncated value cannot be represented in the destination type.
     *                  ^^^^^^^^^
     * With scanline based optimization, SSE instructions can be used for converting blocks of
     * floats to integer, which results in different 'undefined' behavior for values
     * than an isolated static_cast<short>(outOfRangeFloat).
    */
    randomSourceImagePtr->SetPixel(Index000, std::numeric_limits<TInputPixelType>::max());
    randomSourceImagePtr->SetPixel(Index100, std::numeric_limits<TInputPixelType>::min());
    randomSourceImagePtr->SetPixel(Index200, std::numeric_limits<TInputPixelType>::epsilon() );
    randomSourceImagePtr->SetPixel(Index300, std::numeric_limits<TInputPixelType>::denorm_min() );
    randomSourceImagePtr->SetPixel(Index400, std::numeric_limits<TInputPixelType>::round_error() );
  }

  typename FilterType::Pointer filter = FilterType::New();
  filter->SetInput( randomSourceImagePtr );
  filter->UpdateLargestPossibleRegion();

  using InputIteratorType = itk::ImageRegionConstIterator< InputImageType >;
  using OutputIteratorType = itk::ImageRegionConstIterator< OutputImageType >;

  InputIteratorType  it( source->GetOutput(),
                         source->GetOutput()->GetLargestPossibleRegion() );
  OutputIteratorType ot( filter->GetOutput(),
                         filter->GetOutput()->GetLargestPossibleRegion() );

  bool success = true;

  std::cout << "Casting from " << GetCastTypeName< TInputPixelType >()
            << " to " << GetCastTypeName< TOutputPixelType >() << " ... ";

  it.GoToBegin();
  ot.GoToBegin();
  while ( !it.IsAtEnd() )
    {
    TInputPixelType  inValue  = it.Value();
    TOutputPixelType outValue = ot.Value();
    auto expectedValue = static_cast< TOutputPixelType >( inValue );

    if (std::is_floating_point<TInputPixelType>() && std::is_integral<TOutputPixelType>()
      && ( inValue > std::numeric_limits<TOutputPixelType>::max()
        || inValue < std::numeric_limits<TOutputPixelType>::min() )
      )
    {
      ++it;
      ++ot;
      std::cout << std::flush;
      //Debugging code left here for testing __MINGW32__ behavior below that may be redundant with this code
      //std::cout << "NOTICE: static_cast<" << GetCastTypeName< TOutputPixelType >() << ">(" << inValue << ") => "
      //         << outValue << " may not equal " << expectedValue
      //         << "  Casting out of range floating point values to integers is 'undefined' behavior."
      //         << std::flush << std::endl;
      continue;  // Simply skip the case where where the conversion is undefined.
    }

    /** Warning:
     * expectedValue == static_cast< TOutputPixelType( inValue ) is
     * false on some systems and compilers with some values of inValue. */
#if defined(__MINGW32__)  // NOTE:  This may be thee same problem identified above related to 'undefined' behavior
    if ( itk::Math::NotAlmostEquals(outValue, expectedValue) )
#else
    if ( itk::Math::NotExactlyEquals(outValue, expectedValue) )
#endif
      {
      std::cout << std::flush;
      std::cerr << "ERROR: staic_cast<" << GetCastTypeName< TOutputPixelType >() << ">(" << inValue << ") => "
                << outValue << " != " << expectedValue << std::flush << std::endl;
      success = false;
      break;
      }

    ++it;
    ++ot;
    }

  if ( success )
    {
    std::cout << "[PASSED]" << std::endl;
    }
  else
    {
    std::cout << "[FAILED]" << std::endl;
    }

  return success;
}

template < typename TInputPixelType >
bool TestCastFrom()
{
  bool success = true;
  success &= TestCastFromTo< TInputPixelType, char >();
  success &= TestCastFromTo< TInputPixelType, signed char >();
  success &= TestCastFromTo< TInputPixelType, unsigned char >();
  success &= TestCastFromTo< TInputPixelType, short >();
  success &= TestCastFromTo< TInputPixelType, unsigned short >();
  success &= TestCastFromTo< TInputPixelType, int >();
  success &= TestCastFromTo< TInputPixelType, unsigned int >();
  success &= TestCastFromTo< TInputPixelType, long >();
  success &= TestCastFromTo< TInputPixelType, unsigned long >();
  success &= TestCastFromTo< TInputPixelType, long long >();
  success &= TestCastFromTo< TInputPixelType, unsigned long long >();
  success &= TestCastFromTo< TInputPixelType, float >();
  success &= TestCastFromTo< TInputPixelType, double >();

  return success;
}

bool TestVectorImageCast()
{
  // This function casts a VectorImage<float, 2>
  // to a VectorImage<unsigned char, 2>
  std::cout << "Casting from a VectorImage<float, 2> \
                to VectorImage<unsigned char, 2> ..." << std::endl;

  using UnsignedCharVectorImageType = itk::VectorImage<unsigned char, 2>;
  using FloatVectorImageType = itk::VectorImage<float, 2>;

  // Create a 1x3 image of 2D vectors
  FloatVectorImageType::Pointer image = FloatVectorImageType::New();

  itk::Size<2> size;
  size[0] = 1;
  size[1] = 3;

  itk::Index<2> start;
  start.Fill(0);

  itk::ImageRegion<2> region(start,size);
  image->SetNumberOfComponentsPerPixel(2);
  image->SetRegions(region);
  image->Allocate();
  itk::VariableLengthVector<float> vec;
  vec.SetSize(2);
  // All pixels will be the vector (1.3, 5.3)
  vec[0] = 1.3;
  vec[1] = 5.3;
  image->FillBuffer(vec);

  using CastImageFilterType = itk::CastImageFilter< FloatVectorImageType,
               UnsignedCharVectorImageType >;
  CastImageFilterType::Pointer castImageFilter = CastImageFilterType::New();
  castImageFilter->SetInput(image);
  castImageFilter->Update();

  // Setup iterators for the original and casted images
  itk::ImageRegionConstIterator<UnsignedCharVectorImageType>
       castedImageIterator(castImageFilter->GetOutput(),
       castImageFilter->GetOutput()->GetLargestPossibleRegion());

  itk::ImageRegionConstIterator<FloatVectorImageType>
    originalImageIterator(image, image->GetLargestPossibleRegion());

  // Compare both dimensions of all of the pixels from the manually
  // casted original image to the corresponding pixels in the filter-casted
  // image
  bool success = true;
  while(!originalImageIterator.IsAtEnd())
    {
    if(static_cast<unsigned char>(originalImageIterator.Get()[0]) !=
                                  castedImageIterator.Get()[0] ||
       static_cast<unsigned char>(originalImageIterator.Get()[1]) !=
                                  castedImageIterator.Get()[1])
      {
      std::cerr << "Error in TestVectorImageCast!" << std::endl;
      success = false;
      }
    ++originalImageIterator;
    ++castedImageIterator;
    }

  if ( success )
    {
    std::cout << "[PASSED]" << std::endl;
    }
  else
    {
    std::cout << "[FAILED]" << std::endl;
    }

  return success;
}

int itkCastImageFilterTest( int, char* [] )
{
  std::cout << "itkCastImageFilterTest Start" << std::endl;

  // This test casts floats to char, generating float point exceptions.
  // We disable float point exceptions only for this tests
  bool fpeSupport = itk::FloatingPointExceptions::HasFloatingPointExceptionsSupport();
  bool fpeStatus = itk::FloatingPointExceptions::GetEnabled();
  if (fpeSupport && fpeStatus)
    {
    std::cout << "FloatingPointExceptions are disabled only for this test." << std::endl;
    itk::FloatingPointExceptions::Disable();
    }

  bool success = true;
  success &= TestCastFrom< char >();
  success &= TestCastFrom< signed char >();
  success &= TestCastFrom< unsigned char >();
  success &= TestCastFrom< short >();
  success &= TestCastFrom< unsigned short >();
  success &= TestCastFrom< int >();
  success &= TestCastFrom< unsigned int >();
  success &= TestCastFrom< long >();
  success &= TestCastFrom< unsigned long >();
  success &= TestCastFrom< long long >();
  success &= TestCastFrom< unsigned long long >();
  success &= TestCastFrom< float >();
  success &= TestCastFrom< double >();
  success &= TestVectorImageCast();

  std::cout << std::endl;
  if ( !success )
    {
    std::cout << "An itkCastImageFilter test FAILED." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "All itkCastImageFilter tests PASSED." << std::endl;

  return EXIT_SUCCESS;
}
<|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.
 *
 *=========================================================================*/

#include <iostream>

#include "itkClampImageFilter.h"
#include "itkRandomImageSource.h"

// Better name demanging for gcc
#if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ > 0 )
#define GCC_USEDEMANGLE
#endif

#ifdef GCC_USEDEMANGLE
#include <cstdlib>
#include <cxxabi.h>
#endif

template< class T >
std::string GetClampTypeName()
{
  std::string name;
#ifdef GCC_USEDEMANGLE
  char const *mangledName = typeid( T ).name();
  int         status;
  char *      unmangled = abi::__cxa_demangle(mangledName, 0, 0, &status);
  name = unmangled;
  free(unmangled);
#else
  name = typeid( T ).name();
#endif

  return name;
}

template < class TInputPixelType, class TOutputPixelType >
bool TestClampFromTo()
{
  typedef itk::Image< TInputPixelType, 3 >                        InputImageType;
  typedef itk::Image< TOutputPixelType, 3 >                       OutputImageType;
  typedef itk::ClampImageFilter< InputImageType, OutputImageType > FilterType;

  typedef itk::RandomImageSource< InputImageType > SourceType;
  typename SourceType::Pointer source = SourceType::New();

  typename InputImageType::SizeValueType randomSize[3] = {18, 17, 23};
  source->SetSize( randomSize );

  typename FilterType::Pointer filter = FilterType::New();
  filter->SetInput( source->GetOutput() );
  filter->UpdateLargestPossibleRegion();

  typedef itk::ImageRegionConstIterator< InputImageType >  InputIteratorType;
  typedef itk::ImageRegionConstIterator< OutputImageType > OutputIteratorType;

  InputIteratorType  it( source->GetOutput(),
                         source->GetOutput()->GetLargestPossibleRegion() );
  OutputIteratorType ot( filter->GetOutput(),
                         filter->GetOutput()->GetLargestPossibleRegion() );

  bool success = true;

  std::cout << "Casting from " << GetClampTypeName< TInputPixelType >()
            << " to " << GetClampTypeName< TOutputPixelType >() << " ... ";

  it.GoToBegin();
  ot.GoToBegin();
  while ( !it.IsAtEnd() )
    {
    TInputPixelType  inValue       = it.Value();
    TOutputPixelType outValue      = ot.Value();
    TOutputPixelType expectedValue;

    double dInValue = static_cast< double >( inValue );
    double expectedMin = itk::NumericTraits< TOutputPixelType >::NonpositiveMin();
    double expectedMax = itk::NumericTraits< TOutputPixelType >::max();

    if ( dInValue < expectedMin )
      {
      expectedValue = itk::NumericTraits< TOutputPixelType >::NonpositiveMin();
      }
    else if ( dInValue > expectedMax )
      {
      expectedValue = itk::NumericTraits< TOutputPixelType >::max();
      }
    else
      {
      expectedValue = static_cast< TOutputPixelType >( inValue );
      }

    if ( outValue != expectedValue )
      {
      success = false;
      break;
      }

    ++it;
    ++ot;
    }

  if ( success )
    {
    std::cout << "[PASSED]" << std::endl;
    }
  else
    {
    std::cout << "[FAILED]" << std::endl;
    }

  return success;
}

template < class TInputPixelType >
bool TestClampFrom()
{
  bool success =
    TestClampFromTo< TInputPixelType, char >() &&
    TestClampFromTo< TInputPixelType, unsigned char >() &&
    TestClampFromTo< TInputPixelType, short >() &&
    TestClampFromTo< TInputPixelType, unsigned short >() &&
    TestClampFromTo< TInputPixelType, int >() &&
    TestClampFromTo< TInputPixelType, unsigned int >() &&
    TestClampFromTo< TInputPixelType, long >() &&
    TestClampFromTo< TInputPixelType, unsigned long >() &&
    TestClampFromTo< TInputPixelType, long long >() &&
    TestClampFromTo< TInputPixelType, unsigned long long >() &&
    TestClampFromTo< TInputPixelType, float >() &&
    TestClampFromTo< TInputPixelType, double >();

  return success;
}

template < class TInputPixelType, class TOutputPixelType >
bool TestClampFromToWithCustomBounds()
{
  typedef itk::Image< TInputPixelType, 3 >                        InputImageType;
  typedef itk::Image< TOutputPixelType, 3 >                       OutputImageType;
  typedef itk::ClampImageFilter< InputImageType, OutputImageType > FilterType;

  typedef itk::RandomImageSource< InputImageType > SourceType;
  typename SourceType::Pointer source = SourceType::New();
  source->SetMin(static_cast< TInputPixelType >(0));
  source->SetMax(static_cast< TInputPixelType >(20));

  typename InputImageType::SizeValueType randomSize[3] = {18, 17, 23};
  source->SetSize( randomSize );

  typename FilterType::Pointer filter = FilterType::New();
  filter->SetBounds(static_cast< TOutputPixelType>(5), static_cast< TOutputPixelType>(15));
  filter->SetInput( source->GetOutput() );
  filter->UpdateLargestPossibleRegion();

  typedef itk::ImageRegionConstIterator< InputImageType >  InputIteratorType;
  typedef itk::ImageRegionConstIterator< OutputImageType > OutputIteratorType;

  InputIteratorType  it( source->GetOutput(),
                         source->GetOutput()->GetLargestPossibleRegion() );
  OutputIteratorType ot( filter->GetOutput(),
                         filter->GetOutput()->GetLargestPossibleRegion() );

  bool success = true;

  std::cout << "Casting from " << GetClampTypeName< TInputPixelType >()
            << " to " << GetClampTypeName< TOutputPixelType >() << " using custom bounds ... ";

  it.GoToBegin();
  ot.GoToBegin();
  while ( !it.IsAtEnd() )
    {
    TInputPixelType  inValue       = it.Value();
    TOutputPixelType outValue      = ot.Value();
    TOutputPixelType expectedValue;

    double dInValue = static_cast< double >( inValue );
    double expectedMin = filter->GetLowerBound();
    double expectedMax = filter->GetUpperBound();

    if ( dInValue < expectedMin )
      {
      expectedValue = filter->GetLowerBound();
      }
    else if ( dInValue > expectedMax )
      {
      expectedValue = filter->GetUpperBound();
      }
    else
      {
      expectedValue = static_cast< TOutputPixelType >( inValue );
      }

    if ( outValue != expectedValue )
      {
      success = false;
      break;
      }

    ++it;
    ++ot;
    }

  if ( success )
    {
    std::cout << "[PASSED]" << std::endl;
    }
  else
    {
    std::cout << "[FAILED]" << std::endl;
    }

  return success;
}

template < class TInputPixelType >
bool TestClampFromWithCustomBounds()
{
  bool success =
    TestClampFromToWithCustomBounds< TInputPixelType, char >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, unsigned char >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, short >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, unsigned short >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, int >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, unsigned int >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, long >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, unsigned long >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, long long >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, unsigned long long >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, float >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, double >();

  return success;
}

int itkClampImageFilterTest( int, char* [] )
{
  std::cout << "itkClampImageFilterTest Start" << std::endl;

  bool success =
    TestClampFrom< char >() &&
    TestClampFrom< unsigned char >() &&
    TestClampFrom< short >() &&
    TestClampFrom< unsigned short >() &&
    TestClampFrom< int >() &&
    TestClampFrom< unsigned int >() &&
    TestClampFrom< long >() &&
    TestClampFrom< unsigned long >() &&
    TestClampFrom< long long >() &&
    TestClampFrom< unsigned long long >() &&
    TestClampFrom< float >() &&
    TestClampFrom< double >() &&

    TestClampFromWithCustomBounds< char >() &&
    TestClampFromWithCustomBounds< unsigned char >() &&
    TestClampFromWithCustomBounds< short >() &&
    TestClampFromWithCustomBounds< unsigned short >() &&
    TestClampFromWithCustomBounds< int >() &&
    TestClampFromWithCustomBounds< unsigned int >() &&
    TestClampFromWithCustomBounds< long >() &&
    TestClampFromWithCustomBounds< unsigned long >() &&
    TestClampFromWithCustomBounds< long long >() &&
    TestClampFromWithCustomBounds< unsigned long long >() &&
    TestClampFromWithCustomBounds< float >() &&
    TestClampFromWithCustomBounds< double >();

  std::cout << std::endl;
  if ( !success )
    {
    std::cout << "An itkClampImageFilter test FAILED." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "All itkClampImageFilter tests PASSED." << std::endl;

  return EXIT_SUCCESS;
}
<commit_msg>BUG: Visual Studio itkClampImageFilterTest failures.<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.
 *
 *=========================================================================*/

#include <iostream>

#include "itkClampImageFilter.h"
#include "itkRandomImageSource.h"

// Better name demanging for gcc
#if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ > 0 )
#define GCC_USEDEMANGLE
#endif

#ifdef GCC_USEDEMANGLE
#include <cstdlib>
#include <cxxabi.h>
#endif

template< class T >
std::string GetClampTypeName()
{
  std::string name;
#ifdef GCC_USEDEMANGLE
  char const *mangledName = typeid( T ).name();
  int         status;
  char *      unmangled = abi::__cxa_demangle(mangledName, 0, 0, &status);
  name = unmangled;
  free(unmangled);
#else
  name = typeid( T ).name();
#endif

  return name;
}

template < class TInputPixelType, class TOutputPixelType >
bool TestClampFromTo()
{
  typedef itk::Image< TInputPixelType, 3 >                        InputImageType;
  typedef itk::Image< TOutputPixelType, 3 >                       OutputImageType;
  typedef itk::ClampImageFilter< InputImageType, OutputImageType > FilterType;

  typedef itk::RandomImageSource< InputImageType > SourceType;
  typename SourceType::Pointer source = SourceType::New();

  typename InputImageType::SizeValueType randomSize[3] = {18, 17, 23};
  source->SetSize( randomSize );

  typename FilterType::Pointer filter = FilterType::New();
  filter->SetInput( source->GetOutput() );
  filter->UpdateLargestPossibleRegion();

  typedef itk::ImageRegionConstIterator< InputImageType >  InputIteratorType;
  typedef itk::ImageRegionConstIterator< OutputImageType > OutputIteratorType;

  InputIteratorType  it( source->GetOutput(),
                         source->GetOutput()->GetLargestPossibleRegion() );
  OutputIteratorType ot( filter->GetOutput(),
                         filter->GetOutput()->GetLargestPossibleRegion() );

  bool success = true;

  std::cout << "Casting from " << GetClampTypeName< TInputPixelType >()
            << " to " << GetClampTypeName< TOutputPixelType >() << " ... ";

  it.GoToBegin();
  ot.GoToBegin();
  while ( !it.IsAtEnd() )
    {
    TInputPixelType  inValue       = it.Value();
    TOutputPixelType outValue      = ot.Value();
    TOutputPixelType expectedValue;

    double dInValue = static_cast< double >( inValue );
    double expectedMin = itk::NumericTraits< TOutputPixelType >::NonpositiveMin();
    double expectedMax = itk::NumericTraits< TOutputPixelType >::max();

    if ( dInValue < expectedMin )
      {
      expectedValue = itk::NumericTraits< TOutputPixelType >::NonpositiveMin();
      }
    else if ( dInValue > expectedMax )
      {
      expectedValue = itk::NumericTraits< TOutputPixelType >::max();
      }
    else
      {
      expectedValue = static_cast< TOutputPixelType >( inValue );
      }

    if ( outValue != expectedValue )
      {
      success = false;
      break;
      }

    ++it;
    ++ot;
    }

  if ( success )
    {
    std::cout << "[PASSED]" << std::endl;
    }
  else
    {
    std::cout << "[FAILED]" << std::endl;
    }

  return success;
}

template < class TInputPixelType >
bool TestClampFrom()
{
  bool success =
    TestClampFromTo< TInputPixelType, char >() &&
    TestClampFromTo< TInputPixelType, unsigned char >() &&
    TestClampFromTo< TInputPixelType, short >() &&
    TestClampFromTo< TInputPixelType, unsigned short >() &&
    TestClampFromTo< TInputPixelType, int >() &&
    TestClampFromTo< TInputPixelType, unsigned int >() &&
    TestClampFromTo< TInputPixelType, long >() &&
    TestClampFromTo< TInputPixelType, unsigned long >() &&
// Visual Studio has a false failure in due to
// imprecise integer to double conversion. It causes the comparison
// dInValue > expectedMax to pass when it should fail.
#ifndef _MSC_VER
    TestClampFromTo< TInputPixelType, long long >() &&
    TestClampFromTo< TInputPixelType, unsigned long long >() &&
#endif
    TestClampFromTo< TInputPixelType, float >() &&
    TestClampFromTo< TInputPixelType, double >();

  return success;
}

template < class TInputPixelType, class TOutputPixelType >
bool TestClampFromToWithCustomBounds()
{
  typedef itk::Image< TInputPixelType, 3 >                        InputImageType;
  typedef itk::Image< TOutputPixelType, 3 >                       OutputImageType;
  typedef itk::ClampImageFilter< InputImageType, OutputImageType > FilterType;

  typedef itk::RandomImageSource< InputImageType > SourceType;
  typename SourceType::Pointer source = SourceType::New();
  source->SetMin(static_cast< TInputPixelType >(0));
  source->SetMax(static_cast< TInputPixelType >(20));

  typename InputImageType::SizeValueType randomSize[3] = {18, 17, 23};
  source->SetSize( randomSize );

  typename FilterType::Pointer filter = FilterType::New();
  filter->SetBounds(static_cast< TOutputPixelType>(5), static_cast< TOutputPixelType>(15));
  filter->SetInput( source->GetOutput() );
  filter->UpdateLargestPossibleRegion();

  typedef itk::ImageRegionConstIterator< InputImageType >  InputIteratorType;
  typedef itk::ImageRegionConstIterator< OutputImageType > OutputIteratorType;

  InputIteratorType  it( source->GetOutput(),
                         source->GetOutput()->GetLargestPossibleRegion() );
  OutputIteratorType ot( filter->GetOutput(),
                         filter->GetOutput()->GetLargestPossibleRegion() );

  bool success = true;

  std::cout << "Casting from " << GetClampTypeName< TInputPixelType >()
            << " to " << GetClampTypeName< TOutputPixelType >() << " using custom bounds ... ";

  it.GoToBegin();
  ot.GoToBegin();
  while ( !it.IsAtEnd() )
    {
    TInputPixelType  inValue       = it.Value();
    TOutputPixelType outValue      = ot.Value();
    TOutputPixelType expectedValue;

    double dInValue = static_cast< double >( inValue );
    double expectedMin = filter->GetLowerBound();
    double expectedMax = filter->GetUpperBound();

    if ( dInValue < expectedMin )
      {
      expectedValue = filter->GetLowerBound();
      }
    else if ( dInValue > expectedMax )
      {
      expectedValue = filter->GetUpperBound();
      }
    else
      {
      expectedValue = static_cast< TOutputPixelType >( inValue );
      }

    if ( outValue != expectedValue )
      {
      success = false;
      break;
      }

    ++it;
    ++ot;
    }

  if ( success )
    {
    std::cout << "[PASSED]" << std::endl;
    }
  else
    {
    std::cout << "[FAILED]" << std::endl;
    }

  return success;
}

template < class TInputPixelType >
bool TestClampFromWithCustomBounds()
{
  bool success =
    TestClampFromToWithCustomBounds< TInputPixelType, char >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, unsigned char >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, short >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, unsigned short >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, int >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, unsigned int >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, long >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, unsigned long >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, long long >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, unsigned long long >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, float >() &&
    TestClampFromToWithCustomBounds< TInputPixelType, double >();

  return success;
}

int itkClampImageFilterTest( int, char* [] )
{
  std::cout << "itkClampImageFilterTest Start" << std::endl;

  bool success =
    TestClampFrom< char >() &&
    TestClampFrom< unsigned char >() &&
    TestClampFrom< short >() &&
    TestClampFrom< unsigned short >() &&
    TestClampFrom< int >() &&
    TestClampFrom< unsigned int >() &&
    TestClampFrom< long >() &&
    TestClampFrom< unsigned long >() &&
    TestClampFrom< long long >() &&
    TestClampFrom< unsigned long long >() &&
    TestClampFrom< float >() &&
    TestClampFrom< double >() &&

    TestClampFromWithCustomBounds< char >() &&
    TestClampFromWithCustomBounds< unsigned char >() &&
    TestClampFromWithCustomBounds< short >() &&
    TestClampFromWithCustomBounds< unsigned short >() &&
    TestClampFromWithCustomBounds< int >() &&
    TestClampFromWithCustomBounds< unsigned int >() &&
    TestClampFromWithCustomBounds< long >() &&
    TestClampFromWithCustomBounds< unsigned long >() &&
    TestClampFromWithCustomBounds< long long >() &&
    TestClampFromWithCustomBounds< unsigned long long >() &&
    TestClampFromWithCustomBounds< float >() &&
    TestClampFromWithCustomBounds< double >();

  std::cout << std::endl;
  if ( !success )
    {
    std::cout << "An itkClampImageFilter test FAILED." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "All itkClampImageFilter tests PASSED." << std::endl;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>fixing warning<commit_after><|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <algorithm>
#include <iterator>
#include <iv/ustring.h>
#include <iv/stringpiece.h>
#include <iv/conversions.h>
#include "test_aero.h"
namespace {

template<typename T>
bool ExpectEqual(T reg,
                 const iv::core::StringPiece& expected) {
  const iv::core::UString r = iv::core::ToUString(reg);
  iv::core::UString res;
  iv::core::RegExpEscape(r.begin(), r.end(), std::back_inserter(res));
  return res == iv::core::ToUString(expected);
}

}  // namespace anonymous

TEST(AeroSourceEscapeCase, SlashInBrackTest) {
  EXPECT_TRUE(ExpectEqual("[/]", "[/]")) << "[/] => [/]";
  EXPECT_TRUE(ExpectEqual("[\\]/]", "[\\]/]")) << "[\\]/] => [\\]/]";
}

TEST(AeroSourceEscapeCase, SlashTest) {
  EXPECT_TRUE(ExpectEqual("/", "\\/")) << "/ => \\/";
  EXPECT_TRUE(ExpectEqual("\\/", "\\/")) << "\\/ => \\/";
}

TEST(AeroSourceEscapeCase, LineTerminatorTest) {
  EXPECT_TRUE(ExpectEqual("\n", "\\n")) << "\\n => \\n";
  EXPECT_TRUE(ExpectEqual("\\\n", "\\\\n")) << "\\\\n => \\\\n";
  EXPECT_TRUE(ExpectEqual(0x2028, "\\u2028")) << "2028 code => \\u2028";
  EXPECT_TRUE(ExpectEqual(0x2029, "\\u2029")) << "2029 code => \\u2029";
}
<commit_msg>add one char test for aero escape #38<commit_after>#include <gtest/gtest.h>
#include <algorithm>
#include <iterator>
#include <iv/alloc.h>
#include <iv/ustring.h>
#include <iv/stringpiece.h>
#include <iv/conversions.h>
#include <iv/aero/aero.h>
#include "test_aero.h"
namespace {

template<typename T>
bool ExpectEqual(T reg,
                 const iv::core::StringPiece& expected) {
  const iv::core::UString r = iv::core::ToUString(reg);
  iv::core::UString res;
  iv::core::RegExpEscape(r.begin(), r.end(), std::back_inserter(res));
  return res == iv::core::ToUString(expected);
}

}  // namespace anonymous

TEST(AeroSourceEscapeCase, SlashInBrackTest) {
  EXPECT_TRUE(ExpectEqual("[/]", "[/]")) << "[/] => [/]";
  EXPECT_TRUE(ExpectEqual("[\\]/]", "[\\]/]")) << "[\\]/] => [\\]/]";
}

TEST(AeroSourceEscapeCase, SlashTest) {
  EXPECT_TRUE(ExpectEqual("/", "\\/")) << "/ => \\/";
  EXPECT_TRUE(ExpectEqual("\\/", "\\/")) << "\\/ => \\/";
}

TEST(AeroSourceEscapeCase, LineTerminatorTest) {
  EXPECT_TRUE(ExpectEqual("\n", "\\n")) << "\\n => \\n";
  EXPECT_TRUE(ExpectEqual("\\\n", "\\\\n")) << "\\\\n => \\\\n";
  EXPECT_TRUE(ExpectEqual(0x2028, "\\u2028")) << "2028 code => \\u2028";
  EXPECT_TRUE(ExpectEqual(0x2029, "\\u2029")) << "2029 code => \\u2029";
}

TEST(AeroSourceEscapeCase, OneCharTest) {
  iv::core::Space space;
  for (uint32_t ch = 0; ch <= 0xFFFF; ++ch) {
    iv::core::UString str = iv::core::ToUString(ch);
    {
      space.Clear();
      iv::aero::Parser parser(&space, str, iv::aero::NONE);
      int error = 0;
      parser.ParsePattern(&error);
      if (error) {  // invalid, like '['
        continue;
      }
    }
    iv::core::UString res;
    iv::core::RegExpEscape(str.begin(), str.end(), std::back_inserter(res));
    {
      space.Clear();
      iv::aero::Parser parser(&space, str, iv::aero::NONE);
      int error = 0;
      iv::aero::ParsedData data = parser.ParsePattern(&error);
      EXPECT_FALSE(error);
    }
  }
}
<|endoftext|>


<commit_before>AliAnalysisTaskWeakDecayVertexer *AddTaskWeakDecayVertexer( TString lExtraOptions = "", const TString lMasterJobSessionFlag = "")
{
    // Creates, configures and attaches to the train a cascades check task.
    // Get the pointer to the existing analysis manager via the static access method.
    //==============================================================================
    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        ::Error("AddTaskWeakDecayVertexer", "No analysis manager to connect to.");
        return NULL;
    }

    // Check the analysis type using the event handlers connected to the analysis manager.
    //==============================================================================
    if (!mgr->GetInputEventHandler()) {
        ::Error("AddTaskWeakDecayVertexer", "This task requires an input event handler");
        return NULL;
    }
    TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

    // Create and configure the task
    AliAnalysisTaskWeakDecayVertexer *taskWDvertexer = new AliAnalysisTaskWeakDecayVertexer("taskWDvertexer", lExtraOptions);
    mgr->AddTask(taskWDvertexer);
    TString outputFileName = AliAnalysisManager::GetCommonFileName();

    outputFileName += ":PWGLF_WDVertexer";
    //if (mgr->GetMCtruthEventHandler()) outputFileName += "_MC";

    Printf("Set OutputFileName : \n %s\n", outputFileName.Data() );

    AliAnalysisDataContainer *coutputList = mgr->CreateContainer("cListVertexer",
                                                                 TList::Class(),
                                                                 AliAnalysisManager::kOutputContainer,
                                                                 outputFileName );

    //Recommendation: Tree as a single output slot
    mgr->ConnectInput (taskWDvertexer, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(taskWDvertexer, 1, coutputList);

    return taskAuxiliary;
}
<commit_msg>Bugfix in AddTask for supervertexing task<commit_after>AliAnalysisTaskWeakDecayVertexer *AddTaskWeakDecayVertexer( TString lExtraOptions = "", const TString lMasterJobSessionFlag = "")
{
    // Creates, configures and attaches to the train a cascades check task.
    // Get the pointer to the existing analysis manager via the static access method.
    //==============================================================================
    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        ::Error("AddTaskWeakDecayVertexer", "No analysis manager to connect to.");
        return NULL;
    }

    // Check the analysis type using the event handlers connected to the analysis manager.
    //==============================================================================
    if (!mgr->GetInputEventHandler()) {
        ::Error("AddTaskWeakDecayVertexer", "This task requires an input event handler");
        return NULL;
    }
    TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

    // Create and configure the task
    AliAnalysisTaskWeakDecayVertexer *taskWDvertexer = new AliAnalysisTaskWeakDecayVertexer("taskWDvertexer", lExtraOptions);
    mgr->AddTask(taskWDvertexer);
    TString outputFileName = AliAnalysisManager::GetCommonFileName();

    outputFileName += ":PWGLF_WDVertexer";
    //if (mgr->GetMCtruthEventHandler()) outputFileName += "_MC";

    Printf("Set OutputFileName : \n %s\n", outputFileName.Data() );

    AliAnalysisDataContainer *coutputList = mgr->CreateContainer("cListVertexer",
                                                                 TList::Class(),
                                                                 AliAnalysisManager::kOutputContainer,
                                                                 outputFileName );

    //Recommendation: Tree as a single output slot
    mgr->ConnectInput (taskWDvertexer, 0, mgr->GetCommonInputContainer());
    mgr->ConnectOutput(taskWDvertexer, 1, coutputList);

    return taskWDvertexer;
}
<|endoftext|>