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

  Program:   Visualization Toolkit
  Module:    vtkImageThreshold.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 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.

=========================================================================*/
#include "vtkImageThreshold.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkImageThreshold, "1.34");
vtkStandardNewMacro(vtkImageThreshold);

//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageThreshold::vtkImageThreshold()
{
  this->UpperThreshold = VTK_LARGE_FLOAT;
  this->LowerThreshold = -VTK_LARGE_FLOAT;
  this->ReplaceIn = 0;
  this->InValue = 0.0;
  this->ReplaceOut = 0;
  this->OutValue = 0.0;

  this->OutputScalarType = -1; // invalid; output same as input
}

//----------------------------------------------------------------------------
void vtkImageThreshold::SetInValue(float val)
{
  if (val != this->InValue || this->ReplaceIn != 1)
    {
    this->InValue = val;
    this->ReplaceIn = 1;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkImageThreshold::SetOutValue(float val)
{
  if (val != this->OutValue || this->ReplaceOut != 1)
    {
    this->OutValue = val;
    this->ReplaceOut = 1;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
// The values greater than or equal to the value match.
void vtkImageThreshold::ThresholdByUpper(float thresh)
{
  if (this->LowerThreshold != thresh || this->UpperThreshold < VTK_LARGE_FLOAT)
    {
    this->LowerThreshold = thresh;
    this->UpperThreshold = VTK_LARGE_FLOAT;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
// The values less than or equal to the value match.
void vtkImageThreshold::ThresholdByLower(float thresh)
{
  if (this->UpperThreshold != thresh || this->LowerThreshold > -VTK_LARGE_FLOAT)
    {
    this->UpperThreshold = thresh;
    this->LowerThreshold = -VTK_LARGE_FLOAT;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
// The values in a range (inclusive) match
void vtkImageThreshold::ThresholdBetween(float lower, float upper)
{
  if (this->LowerThreshold != lower || this->UpperThreshold != upper)
    {
    this->LowerThreshold = lower;
    this->UpperThreshold = upper;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkImageThreshold::ExecuteInformation(vtkImageData *inData,
                                           vtkImageData *outData)
{
  if (this->OutputScalarType != -1)
    {
    outData->SetScalarType(this->OutputScalarType);
    }
  else
    {
    outData->SetScalarType(inData->GetScalarType());
    }
}

//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class IT, class OT>
static void vtkImageThresholdExecute(vtkImageThreshold *self,
                                     vtkImageData *inData, IT *inPtr,
                                     vtkImageData *outData, OT *outPtr,
                                     int outExt[6], int id)
{
  int idxR, idxY, idxZ;
  int maxY, maxZ;
  int inIncX, inIncY, inIncZ;
  int outIncX, outIncY, outIncZ;
  int rowLength;
  float  lowerThreshold = self->GetLowerThreshold();
  float  upperThreshold = self->GetUpperThreshold();
  int replaceIn = self->GetReplaceIn();
  OT  inValue = (OT)(self->GetInValue());
  int replaceOut = self->GetReplaceOut();
  OT  outValue = (OT)(self->GetOutValue());
  float temp;
  unsigned long count = 0;
  unsigned long target;

  // find the region to loop over
  rowLength = (outExt[1] - outExt[0]+1)*inData->GetNumberOfScalarComponents();
  maxY = outExt[3] - outExt[2];
  maxZ = outExt[5] - outExt[4];
  target = (unsigned long)((maxZ+1)*(maxY+1)/50.0);
  target++;

  // Get increments to march through data
  inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
  outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);

  // Loop through ouput pixels
  for (idxZ = 0; idxZ <= maxZ; idxZ++)
    {
    for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++)
      {
      if (!id)
        {
        if (!(count%target))
          {
          self->UpdateProgress(count/(50.0*target));
          }
        count++;
        }
      for (idxR = 0; idxR < rowLength; idxR++)
        {
        // Pixel operation
        temp = (float)(*inPtr);
        if (lowerThreshold <= temp && temp <= upperThreshold)
          {
          // match
          if (replaceIn)
            {
            *outPtr = inValue;
            }
          else
            {
            *outPtr = (OT)(temp);
            }
          }
        else
          {
          // not match
          if (replaceOut)
            {
            *outPtr = outValue;
            }
          else
            {
            *outPtr = (OT)(temp);
            }
          }
        outPtr++;
        inPtr++;
        }
      outPtr += outIncY;
      inPtr += inIncY;
      }
    outPtr += outIncZ;
    inPtr += inIncZ;
    }
}

//----------------------------------------------------------------------------
template <class T>
static void vtkImageThresholdExecute1(vtkImageThreshold *self,
                                      vtkImageData *inData, T *inPtr,
                                      vtkImageData *outData,
                                      int outExt[6], int id)
{
  void *outPtr = outData->GetScalarPointerForExtent(outExt);

  switch (outData->GetScalarType())
    {
    vtkTemplateMacro7(vtkImageThresholdExecute, self, inData, inPtr,
                      outData, (VTK_TT *)(outPtr),outExt, id);
    default:
      vtkGenericWarningMacro("Execute: Unknown input ScalarType");
      return;
    }
}

//----------------------------------------------------------------------------
// 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 vtkImageThreshold::ThreadedExecute(vtkImageData *inData,
                                        vtkImageData *outData,
                                        int outExt[6], int id)
{
  void *inPtr = inData->GetScalarPointerForExtent(outExt);

  switch (inData->GetScalarType())
    {
    vtkTemplateMacro6(vtkImageThresholdExecute1, this, inData,
                      (VTK_TT *)(inPtr), outData, outExt, id);
    default:
      vtkErrorMacro(<< "Execute: Unknown input ScalarType");
      return;
    }
}

void vtkImageThreshold::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "OutputScalarType: " << this->OutputScalarType << "\n";
  os << indent << "InValue: " << this->InValue << "\n";
  os << indent << "OutValue: " << this->OutValue << "\n";
  os << indent << "LowerThreshold: " << this->LowerThreshold << "\n";
  os << indent << "UpperThreshold: " << this->UpperThreshold << "\n";
  os << indent << "ReplaceIn: " << this->ReplaceIn << "\n";
  os << indent << "ReplaceOut: " << this->ReplaceOut << "\n";
}

<commit_msg>ENH: performance improvement by removing cast to float at every pixel.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImageThreshold.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 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.

=========================================================================*/
#include "vtkImageThreshold.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkImageThreshold, "1.35");
vtkStandardNewMacro(vtkImageThreshold);

//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageThreshold::vtkImageThreshold()
{
  this->UpperThreshold = VTK_LARGE_FLOAT;
  this->LowerThreshold = -VTK_LARGE_FLOAT;
  this->ReplaceIn = 0;
  this->InValue = 0.0;
  this->ReplaceOut = 0;
  this->OutValue = 0.0;

  this->OutputScalarType = -1; // invalid; output same as input
}

//----------------------------------------------------------------------------
void vtkImageThreshold::SetInValue(float val)
{
  if (val != this->InValue || this->ReplaceIn != 1)
    {
    this->InValue = val;
    this->ReplaceIn = 1;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkImageThreshold::SetOutValue(float val)
{
  if (val != this->OutValue || this->ReplaceOut != 1)
    {
    this->OutValue = val;
    this->ReplaceOut = 1;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
// The values greater than or equal to the value match.
void vtkImageThreshold::ThresholdByUpper(float thresh)
{
  if (this->LowerThreshold != thresh || this->UpperThreshold < VTK_LARGE_FLOAT)
    {
    this->LowerThreshold = thresh;
    this->UpperThreshold = VTK_LARGE_FLOAT;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
// The values less than or equal to the value match.
void vtkImageThreshold::ThresholdByLower(float thresh)
{
  if (this->UpperThreshold != thresh || this->LowerThreshold > -VTK_LARGE_FLOAT)
    {
    this->UpperThreshold = thresh;
    this->LowerThreshold = -VTK_LARGE_FLOAT;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
// The values in a range (inclusive) match
void vtkImageThreshold::ThresholdBetween(float lower, float upper)
{
  if (this->LowerThreshold != lower || this->UpperThreshold != upper)
    {
    this->LowerThreshold = lower;
    this->UpperThreshold = upper;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkImageThreshold::ExecuteInformation(vtkImageData *inData,
                                           vtkImageData *outData)
{
  if (this->OutputScalarType != -1)
    {
    outData->SetScalarType(this->OutputScalarType);
    }
  else
    {
    outData->SetScalarType(inData->GetScalarType());
    }
}

//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class IT, class OT>
static void vtkImageThresholdExecute(vtkImageThreshold *self,
                                     vtkImageData *inData, IT *inPtr,
                                     vtkImageData *outData, OT *outPtr,
                                     int outExt[6], int id)
{
  int idxR, idxY, idxZ;
  int maxY, maxZ;
  int inIncX, inIncY, inIncZ;
  int outIncX, outIncY, outIncZ;
  int rowLength;
  IT  lowerThreshold;
  IT  upperThreshold;
  int replaceIn = self->GetReplaceIn();
  OT  inValue = (OT)(self->GetInValue());
  int replaceOut = self->GetReplaceOut();
  OT  outValue = (OT)(self->GetOutValue());
  IT temp;
  unsigned long count = 0;
  unsigned long target;

  // Make sure the thresholds are valid for the scalar
  if (self->GetLowerThreshold() < (float) inData->GetScalarTypeMin())
    {
    lowerThreshold = inData->GetScalarTypeMin();
    }
  else
    {
    lowerThreshold = (IT) self->GetLowerThreshold();
    }

  if (self->GetUpperThreshold() > (float) inData->GetScalarTypeMax())
    {
    upperThreshold = inData->GetScalarTypeMax();
    }
  else
    {
    upperThreshold = (IT) self->GetUpperThreshold();
    }

  // find the region to loop over
  rowLength = (outExt[1] - outExt[0]+1)*inData->GetNumberOfScalarComponents();
  maxY = outExt[3] - outExt[2];
  maxZ = outExt[5] - outExt[4];
  target = (unsigned long)((maxZ+1)*(maxY+1)/50.0);
  target++;

  // Get increments to march through data
  inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ);
  outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);

  // Loop through output pixels
  for (idxZ = 0; idxZ <= maxZ; idxZ++)
    {
    for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++)
      {
      if (!id)
        {
        if (!(count%target))
          {
          self->UpdateProgress(count/(50.0*target));
          }
        count++;
        }
      for (idxR = 0; idxR < rowLength; idxR++)
        {
        // Pixel operation
        temp = (*inPtr);
        if (lowerThreshold <= temp && temp <= upperThreshold)
          {
          // match
          if (replaceIn)
            {
            *outPtr = inValue;
            }
          else
            {
            *outPtr = (OT)(temp);
            }
          }
        else
          {
          // not match
          if (replaceOut)
            {
            *outPtr = outValue;
            }
          else
            {
            *outPtr = (OT)(temp);
            }
          }
        outPtr++;
        inPtr++;
        }
      outPtr += outIncY;
      inPtr += inIncY;
      }
    outPtr += outIncZ;
    inPtr += inIncZ;
    }
}

//----------------------------------------------------------------------------
template <class T>
static void vtkImageThresholdExecute1(vtkImageThreshold *self,
                                      vtkImageData *inData, T *inPtr,
                                      vtkImageData *outData,
                                      int outExt[6], int id)
{
  void *outPtr = outData->GetScalarPointerForExtent(outExt);

  switch (outData->GetScalarType())
    {
    vtkTemplateMacro7(vtkImageThresholdExecute, self, inData, inPtr,
                      outData, (VTK_TT *)(outPtr),outExt, id);
    default:
      vtkGenericWarningMacro("Execute: Unknown input ScalarType");
      return;
    }
}

//----------------------------------------------------------------------------
// 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 vtkImageThreshold::ThreadedExecute(vtkImageData *inData,
                                        vtkImageData *outData,
                                        int outExt[6], int id)
{
  void *inPtr = inData->GetScalarPointerForExtent(outExt);

  switch (inData->GetScalarType())
    {
    vtkTemplateMacro6(vtkImageThresholdExecute1, this, inData,
                      (VTK_TT *)(inPtr), outData, outExt, id);
    default:
      vtkErrorMacro(<< "Execute: Unknown input ScalarType");
      return;
    }
}

void vtkImageThreshold::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "OutputScalarType: " << this->OutputScalarType << "\n";
  os << indent << "InValue: " << this->InValue << "\n";
  os << indent << "OutValue: " << this->OutValue << "\n";
  os << indent << "LowerThreshold: " << this->LowerThreshold << "\n";
  os << indent << "UpperThreshold: " << this->UpperThreshold << "\n";
  os << indent << "ReplaceIn: " << this->ReplaceIn << "\n";
  os << indent << "ReplaceOut: " << this->ReplaceOut << "\n";
}

<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.6  2001/05/11 13:26:16  tng
 * Copyright update.
 *
 * Revision 1.5  2001/03/21 21:56:04  tng
 * Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar.
 *
 * Revision 1.4  2001/02/26 19:44:14  tng
 * Schema: add utility class QName, by Pei Yong Zhang.
 *
 * Revision 1.3  2000/11/02 01:14:07  andyh
 * SAX bug fix:  Attribute lists were throwing exceptions rather than returning
 * null when an attribute could not be found by name.  Fixed by Tinny Ng.
 *
 * Revision 1.2  2000/08/09 22:11:16  jpolast
 * changes to allow const instances of the sax2
 * Attributes class.
 *
 * Revision 1.1  2000/08/02 18:09:14  jpolast
 * initial checkin: attributes vector needed for
 * Attributes class as defined by sax2 spec
 *
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <util/Janitor.hpp>
#include <internal/VecAttributesImpl.hpp>

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
VecAttributesImpl::VecAttributesImpl() :

    fAdopt(false)
    , fCount(0)
    , fVector(0)
    , fScanner(0)
{
}

VecAttributesImpl::~VecAttributesImpl()
{
    //
    //  Note that some compilers can't deal with the fact that the pointer
    //  is to a const object, so we have to cast off the const'ness here!
    //
    if (fAdopt)
        delete (RefVectorOf<XMLAttr>*)fVector;
}

// ---------------------------------------------------------------------------
//  Implementation of the attribute list interface
// ---------------------------------------------------------------------------
unsigned int VecAttributesImpl::getLength() const
{
    return fCount;
}

const XMLCh* VecAttributesImpl::getURI(const unsigned int index) const
{
    // since this func really needs to be const, like the rest, not sure how we
    // make it const and re-use the fURIBuffer member variable.  we're currently
    // creating a buffer each time you need a URI.  there has to be a better
    // way to do this...

    //XMLBuffer tempBuf;
    if (index >= fCount) {

        return 0;
     }
    //fValidator->getURIText(fVector->elementAt(index)->getURIId(), tempBuf) ;
    //return tempBuf.getRawBuffer() ;
    return fScanner->getURIText(fVector->elementAt(index)->getURIId());
}

const XMLCh* VecAttributesImpl::getLocalName(const unsigned int index) const
{
    if (index >= fCount) {
        return 0;
     }
    return fVector->elementAt(index)->getName();
}

const XMLCh* VecAttributesImpl::getQName(const unsigned int index) const
{
    if (index >= fCount) {
        return 0;
     }
    return fVector->elementAt(index)->getQName();
}

const XMLCh* VecAttributesImpl::getType(const unsigned int index) const
{
    if (index >= fCount) {
        return 0;
     }
    return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType());
}

const XMLCh* VecAttributesImpl::getValue(const unsigned int index) const
{
    if (index >= fCount) {
        return 0;
     }
    return fVector->elementAt(index)->getValue();
}

int VecAttributesImpl::getIndex(const XMLCh* const uri, const XMLCh* const localPart ) const
{
    //
    //  Search the vector for the attribute with the given name and return
    //  its type.
    //
    XMLBuffer uriBuffer ;
    for (unsigned int index = 0; index < fCount; index++)
    {
        const XMLAttr* curElem = fVector->elementAt(index);

        fScanner->getURIText(curElem->getURIId(), uriBuffer) ;

        if ( (!XMLString::compareString(curElem->getName(), localPart)) &&
             (!XMLString::compareString(uriBuffer.getRawBuffer(), uri)) )
            return index ;
    }
    return -1;
}

int VecAttributesImpl::getIndex(const XMLCh* const qName ) const
{
    //
    //  Search the vector for the attribute with the given name and return
    //  its type.
    //
    for (unsigned int index = 0; index < fCount; index++)
    {
        const XMLAttr* curElem = fVector->elementAt(index);

        if (!XMLString::compareString(curElem->getQName(), qName))
            return index ;
    }
    return -1;
}

const XMLCh* VecAttributesImpl::getType(const XMLCh* const uri, const XMLCh* const localPart ) const
{
    return getType(getIndex(uri, localPart)) ;
}

const XMLCh* VecAttributesImpl::getType(const XMLCh* const qName) const
{
    return getType(getIndex(qName)) ;
}

const XMLCh* VecAttributesImpl::getValue(const XMLCh* const uri, const XMLCh* const localPart ) const
{
    return getValue(getIndex(uri, localPart)) ;
}

const XMLCh* VecAttributesImpl::getValue(const XMLCh* const qName) const
{
    return getValue(getIndex(qName)) ;
}

// ---------------------------------------------------------------------------
//  Setter methods
// ---------------------------------------------------------------------------
void VecAttributesImpl::setVector(const   RefVectorOf<XMLAttr>* const srcVec
                                , const unsigned int                count
                                , const XMLScanner * const        scanner
                                , const bool                        adopt)
{
    //
    //  Delete the previous vector (if any) if we are adopting. Note that some
    //  compilers can't deal with the fact that the pointer is to a const
    //  object, so we have to cast off the const'ness here!
    //
    if (fAdopt)
        delete (RefVectorOf<XMLAttr>*)fVector;

    fAdopt = adopt;
    fCount = count;
    fVector = srcVec;
    fScanner = scanner ;
}

<commit_msg>[BUG# 3831]: -1 returned from getIndex() needs to be checked<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.7  2001/10/05 17:57:39  peiyongz
 * [BUG# 3831]: -1 returned from getIndex() needs to be checked
 *
 * Revision 1.6  2001/05/11 13:26:16  tng
 * Copyright update.
 *
 * Revision 1.5  2001/03/21 21:56:04  tng
 * Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar.
 *
 * Revision 1.4  2001/02/26 19:44:14  tng
 * Schema: add utility class QName, by Pei Yong Zhang.
 *
 * Revision 1.3  2000/11/02 01:14:07  andyh
 * SAX bug fix:  Attribute lists were throwing exceptions rather than returning
 * null when an attribute could not be found by name.  Fixed by Tinny Ng.
 *
 * Revision 1.2  2000/08/09 22:11:16  jpolast
 * changes to allow const instances of the sax2
 * Attributes class.
 *
 * Revision 1.1  2000/08/02 18:09:14  jpolast
 * initial checkin: attributes vector needed for
 * Attributes class as defined by sax2 spec
 *
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <util/Janitor.hpp>
#include <internal/VecAttributesImpl.hpp>

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
VecAttributesImpl::VecAttributesImpl() :

    fAdopt(false)
    , fCount(0)
    , fVector(0)
    , fScanner(0)
{
}

VecAttributesImpl::~VecAttributesImpl()
{
    //
    //  Note that some compilers can't deal with the fact that the pointer
    //  is to a const object, so we have to cast off the const'ness here!
    //
    if (fAdopt)
        delete (RefVectorOf<XMLAttr>*)fVector;
}

// ---------------------------------------------------------------------------
//  Implementation of the attribute list interface
// ---------------------------------------------------------------------------
unsigned int VecAttributesImpl::getLength() const
{
    return fCount;
}

const XMLCh* VecAttributesImpl::getURI(const unsigned int index) const
{
    // since this func really needs to be const, like the rest, not sure how we
    // make it const and re-use the fURIBuffer member variable.  we're currently
    // creating a buffer each time you need a URI.  there has to be a better
    // way to do this...

    //XMLBuffer tempBuf;
    if (index >= fCount) {

        return 0;
     }
    //fValidator->getURIText(fVector->elementAt(index)->getURIId(), tempBuf) ;
    //return tempBuf.getRawBuffer() ;
    return fScanner->getURIText(fVector->elementAt(index)->getURIId());
}

const XMLCh* VecAttributesImpl::getLocalName(const unsigned int index) const
{
    if (index >= fCount) {
        return 0;
     }
    return fVector->elementAt(index)->getName();
}

const XMLCh* VecAttributesImpl::getQName(const unsigned int index) const
{
    if (index >= fCount) {
        return 0;
     }
    return fVector->elementAt(index)->getQName();
}

const XMLCh* VecAttributesImpl::getType(const unsigned int index) const
{
    if (index >= fCount) {
        return 0;
     }
    return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType());
}

const XMLCh* VecAttributesImpl::getValue(const unsigned int index) const
{
    if (index >= fCount) {
        return 0;
     }
    return fVector->elementAt(index)->getValue();
}

int VecAttributesImpl::getIndex(const XMLCh* const uri, const XMLCh* const localPart ) const
{
    //
    //  Search the vector for the attribute with the given name and return
    //  its type.
    //
    XMLBuffer uriBuffer ;
    for (unsigned int index = 0; index < fCount; index++)
    {
        const XMLAttr* curElem = fVector->elementAt(index);

        fScanner->getURIText(curElem->getURIId(), uriBuffer) ;

        if ( (!XMLString::compareString(curElem->getName(), localPart)) &&
             (!XMLString::compareString(uriBuffer.getRawBuffer(), uri)) )
            return index ;
    }
    return -1;
}

int VecAttributesImpl::getIndex(const XMLCh* const qName ) const
{
    //
    //  Search the vector for the attribute with the given name and return
    //  its type.
    //
    for (unsigned int index = 0; index < fCount; index++)
    {
        const XMLAttr* curElem = fVector->elementAt(index);

        if (!XMLString::compareString(curElem->getQName(), qName))
            return index ;
    }
    return -1;
}

const XMLCh* VecAttributesImpl::getType(const XMLCh* const uri, const XMLCh* const localPart ) const
{
    int retVal = getIndex(uri, localPart);
    return ((retVal < 0) ? 0 : getType(retVal));
}

const XMLCh* VecAttributesImpl::getType(const XMLCh* const qName) const
{
    int retVal = getIndex(qName);
    return ((retVal < 0) ? 0 : getType(retVal));
}

const XMLCh* VecAttributesImpl::getValue(const XMLCh* const uri, const XMLCh* const localPart ) const
{
    int retVal = getIndex(uri, localPart);
    return ((retVal < 0) ? 0 : getValue(retVal));
}

const XMLCh* VecAttributesImpl::getValue(const XMLCh* const qName) const
{
    int retVal = getIndex(qName);
    return ((retVal < 0) ? 0 : getValue(retVal));
}

// ---------------------------------------------------------------------------
//  Setter methods
// ---------------------------------------------------------------------------
void VecAttributesImpl::setVector(const   RefVectorOf<XMLAttr>* const srcVec
                                , const unsigned int                count
                                , const XMLScanner * const        scanner
                                , const bool                        adopt)
{
    //
    //  Delete the previous vector (if any) if we are adopting. Note that some
    //  compilers can't deal with the fact that the pointer is to a const
    //  object, so we have to cast off the const'ness here!
    //
    if (fAdopt)
        delete (RefVectorOf<XMLAttr>*)fVector;

    fAdopt = adopt;
    fCount = count;
    fVector = srcVec;
    fScanner = scanner ;
}

<|endoftext|>


<commit_before>#pragma once

#include <EasyDx/Common.hpp>
#include <EasyDx/Vertex.hpp>
#include <vector>
#include <gsl/span>
#include <d3d11.h>

template<typename VertexT,
    typename InstancedT>
    struct InstancingObject
{
    static_assert(dx::is_vertex_v<VertexT>);

    InstancingObject(std::uint32_t count)
    {

    }

    VertexT Vertex;

    void Draw(ID3D11DeviceContext& context)
    {

    }

    ID3D11Buffer* InstancedBuffer() const { return gpuInstancedData_.Get(); }

    gsl::span<InstancedT> InstancedData() { return gsl::make_span(cpuInstancedData_); }
    gsl::span<const InstancedT> InstancedData() const { return gsl::make_span(cpuInstancedData_); }

private:
    wrl::ComPtr<ID3D11Buffer> gpuInstancedData_;
    std::vector<InstancedT> cpuInstancedData_;

};<commit_msg>删除没用的文件。<commit_after><|endoftext|>


<commit_before>// ConsoleRPG.cpp : Defines the entry point for the console application.
// Created by Nick Mullally a.k.a. thakyZ / Nire Inicana
//

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include "time.h"
using namespace std;

// Roll the dice.
int diceRoll(int qty, int sides)
{
	int subTotal = 0; // Dice addition subtotal.
	// Roll the dice.

	// Loop to roll the dice
	for (int i = 0; i < qty; i++)
	{
		int currentRoll = rand() % sides + 1;
		subTotal += currentRoll;
	}

	return subTotal;
}

// Race Choices
enum RACE { HUMAN, ELF, DARKELF, ANGEL, MONGREL, SHAMANI, NIBELUNG, UNDEAD };

// Class Choices
enum OCC { FIGHTER, CLERIC, THEIF, BARD, ROUGE, TINKER, MAGE };

// Stats Tree
struct ATTRIBUTES
{
	unsigned int strength;
	unsigned int faith;
	unsigned int dexterity;
	unsigned int insperation;
	unsigned int cleverness;
	unsigned int focus;
	unsigned int hp, hpMax;
	unsigned int mp, mpMax;
};

void displayStats(ATTRIBUTES atts)
{
	cout << " +---------------------+ \n";
	cout << " |  Attributes:        | \n";
	cout << " +---------------------+ \n";
	cout << "\n";
	cout << "   Strength:      " << atts.strength << "\n";
	cout << "   Faith:         " << atts.faith << "\n";
	cout << "   Dexterity:     " << atts.dexterity << "\n";
	cout << "   Insperation:   " << atts.insperation << "\n";
	cout << "   Cleverness:    " << atts.cleverness << "\n";
	cout << "   Focus:         " << atts.focus << "\n";
	cout << "\n\n";
}

// Startup
int _tmain(int argc, _TCHAR* argv[])
{
	srand(time(NULL));

	RACE inputRace; // The race that is chosen.
	char inputs; // The inputs.
	ATTRIBUTES tempStats; // The stats the player gets by random.
	bool reroll = true; // The bool for rerolling.
	OCC inputClass; // The class that is chosen.

	system("cls");

	cout << "Welcome to Zoro\n";

	while (reroll == true)
	{
		cout << "Please Select a Race:\n";
		cout << "[H]uman [E]lf [D]ark elf [A]ngel [M]ongrel [S]hamani [N]ibelung [U]ndead\n";

		// The input for the chosen race.
		cin >> inputs;

		switch (inputs)
		{
			case 'h':
			case 'H':
				cout << "Human\n";
				inputRace = HUMAN;
				tempStats.strength = diceRoll(3, 6);
				tempStats.faith = diceRoll(3, 6);
				tempStats.dexterity = diceRoll(3, 6);
				tempStats.insperation = diceRoll(3, 6);
				tempStats.cleverness = diceRoll(3, 6);
				tempStats.focus = diceRoll(3, 6);
				break;
			case 'e':
			case 'E':
				cout << "Elf\n";
				inputRace = ELF;
				tempStats.strength = diceRoll(3, 6);
				tempStats.faith = diceRoll(3, 6);
				tempStats.dexterity = diceRoll(3, 6);
				tempStats.insperation = diceRoll(3, 6);
				tempStats.cleverness = diceRoll(2, 6);
				tempStats.focus = diceRoll(4, 6);
				break;
			case 'd':
			case 'D':
				cout << "Dark Elf\n";
				inputRace = DARKELF;
				tempStats.strength = diceRoll(3, 6);
				tempStats.faith = diceRoll(3, 6);
				tempStats.dexterity = diceRoll(4, 6);
				tempStats.insperation = diceRoll(2, 6);
				tempStats.cleverness = diceRoll(3, 6);
				tempStats.focus = diceRoll(3, 6);
				break;
			case 'a':
			case 'A':
				cout << "Angel\n";
				inputRace = ANGEL;
				tempStats.strength = diceRoll(3, 6);
				tempStats.faith = diceRoll(4, 6);
				tempStats.dexterity = diceRoll(3, 6);
				tempStats.insperation = diceRoll(3, 6);
				tempStats.cleverness = diceRoll(3, 6);
				tempStats.focus = diceRoll(3, 6);
				break;
			case 'm':
			case 'M':
				cout << "Mongrel\n";
				inputRace = MONGREL;
				tempStats.strength = diceRoll(4, 6);
				tempStats.faith = diceRoll(3, 6);
				tempStats.dexterity = diceRoll(3, 6);
				tempStats.insperation = diceRoll(3, 6);
				tempStats.cleverness = diceRoll(3, 6);
				tempStats.focus = diceRoll(2, 6);
				break;
			case 's':
			case 'S':
				cout << "Shamani\n";
				inputRace = SHAMANI;
				tempStats.strength = diceRoll(2, 6);
				tempStats.faith = diceRoll(4, 6);
				tempStats.dexterity = diceRoll(3, 6);
				tempStats.insperation = diceRoll(3, 6);
				tempStats.cleverness = diceRoll(3, 6);
				tempStats.focus = diceRoll(3, 6);
				break;
			case 'n':
			case 'N':
				cout << "Nibelung\n";
				inputRace = NIBELUNG;
				tempStats.strength = diceRoll(3, 6);
				tempStats.faith = diceRoll(3, 6);
				tempStats.dexterity = diceRoll(2, 6);
				tempStats.insperation = diceRoll(3, 6);
				tempStats.cleverness = diceRoll(4, 6);
				tempStats.focus = diceRoll(3, 6);
				break;
			case 'u':
			case 'U':
				cout << "Undead\n";
				inputRace = UNDEAD;
				tempStats.strength = diceRoll(3, 6);
				tempStats.faith = diceRoll(3, 6);
				tempStats.dexterity = diceRoll(3, 6);
				tempStats.insperation = diceRoll(3, 6);
				tempStats.cleverness = diceRoll(2, 6);
				tempStats.focus = diceRoll(3, 6);
				break;
			default:
				cout << "Please input a vaild race.\n";
				reroll = true;
				break;
		}

		displayStats(tempStats);

		cout << "Reroll? [Y]es [N]o\n";

		cin >> inputs;

		reroll = false;

		if (inputs == 'y' || inputs == 'Y')
		{
			reroll = true;
		}
	}

	reroll = true;

	while (reroll) // While reroll == true
	{
		reroll = false;

		cout << "Please select a class\n";
		cout << "[F]ighter [C]leric [T]heif [B]ard [R]ouge [M]age\n";

		cin >> inputs;

		switch (inputs)
		{
			case 'f':
			case 'F':
				inputClass = FIGHTER;
				cout << "Fighter\n";
				break;
			case 'c':
			case 'C':
				inputClass = CLERIC;
				cout << "Cleric\n";
				break;
			case 't':
			case 'T':
				inputClass = THEIF;
				cout << "Theif\n";
				break;
			case 'b':
			case 'B':
				inputClass = BARD;
				cout << "Bard\n";
				break;
			case 'r':
			case 'R':
				inputClass = ROUGE;
				cout << "Rouge\n";
				break;
			case 'm':
			case 'M':
				inputClass = MAGE;
				cout << "Mage\n";
				break;
			default:
				cout << "Please input a valid class.\n";
				reroll = true;
				break;
		}
	}

	return 0;
}<commit_msg>Added check to retry the choose race switch<commit_after>// ConsoleRPG.cpp : Defines the entry point for the console application.
// Created by Nick Mullally a.k.a. thakyZ / Nire Inicana
//

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include "time.h"
using namespace std;

// Roll the dice.
int diceRoll(int qty, int sides)
{
	int subTotal = 0; // Dice addition subtotal.
	// Roll the dice.

	// Loop to roll the dice
	for (int i = 0; i < qty; i++)
	{
		int currentRoll = rand() % sides + 1;
		subTotal += currentRoll;
	}

	return subTotal;
}

// Race Choices
enum RACE { HUMAN, ELF, DARKELF, ANGEL, MONGREL, SHAMANI, NIBELUNG, UNDEAD };

// Class Choices
enum OCC { FIGHTER, CLERIC, THEIF, BARD, ROUGE, TINKER, MAGE };

// Stats Tree
struct ATTRIBUTES
{
	unsigned int strength;
	unsigned int faith;
	unsigned int dexterity;
	unsigned int insperation;
	unsigned int cleverness;
	unsigned int focus;
	unsigned int hp, hpMax;
	unsigned int mp, mpMax;
};

void displayStats(ATTRIBUTES atts)
{
	cout << " +---------------------+ \n";
	cout << " |  Attributes:        | \n";
	cout << " +---------------------+ \n";
	cout << "\n";
	cout << "   Strength:      " << atts.strength << "\n";
	cout << "   Faith:         " << atts.faith << "\n";
	cout << "   Dexterity:     " << atts.dexterity << "\n";
	cout << "   Insperation:   " << atts.insperation << "\n";
	cout << "   Cleverness:    " << atts.cleverness << "\n";
	cout << "   Focus:         " << atts.focus << "\n";
	cout << "\n\n";
}

// Startup
int _tmain(int argc, _TCHAR* argv[])
{
	srand(time(NULL));

	RACE inputRace; // The race that is chosen.
	char inputs; // The inputs.
	ATTRIBUTES tempStats; // The stats the player gets by random.
	bool reroll = true; // The bool for rerolling.
	OCC inputClass; // The class that is chosen.
	bool retry = true;

	system("cls");

	cout << "Welcome to Zoro\n";

	while (reroll == true)
	{
		cout << "Please Select a Race:\n";
		cout << "[H]uman [E]lf [D]ark elf [A]ngel [M]ongrel [S]hamani [N]ibelung [U]ndead\n";

		// The input for the chosen race.
		cin >> inputs;

		while (retry == true)
		{
			retry == false

			switch (inputs)
			{
				case 'h':
				case 'H':
					cout << "Human\n";
					inputRace = HUMAN;
					tempStats.strength = diceRoll(3, 6);
					tempStats.faith = diceRoll(3, 6);
					tempStats.dexterity = diceRoll(3, 6);
					tempStats.insperation = diceRoll(3, 6);
					tempStats.cleverness = diceRoll(3, 6);
					tempStats.focus = diceRoll(3, 6);
					break;
				case 'e':
				case 'E':
					cout << "Elf\n";
					inputRace = ELF;
					tempStats.strength = diceRoll(3, 6);
					tempStats.faith = diceRoll(3, 6);
					tempStats.dexterity = diceRoll(3, 6);
					tempStats.insperation = diceRoll(3, 6);
					tempStats.cleverness = diceRoll(2, 6);
					tempStats.focus = diceRoll(4, 6);
					break;
				case 'd':
				case 'D':
					cout << "Dark Elf\n";
					inputRace = DARKELF;
					tempStats.strength = diceRoll(3, 6);
					tempStats.faith = diceRoll(3, 6);
					tempStats.dexterity = diceRoll(4, 6);
					tempStats.insperation = diceRoll(2, 6);
					tempStats.cleverness = diceRoll(3, 6);
					tempStats.focus = diceRoll(3, 6);
					break;
				case 'a':
				case 'A':
					cout << "Angel\n";
					inputRace = ANGEL;
					tempStats.strength = diceRoll(3, 6);
					tempStats.faith = diceRoll(4, 6);
					tempStats.dexterity = diceRoll(3, 6);
					tempStats.insperation = diceRoll(3, 6);
					tempStats.cleverness = diceRoll(3, 6);
					tempStats.focus = diceRoll(3, 6);
					break;
				case 'm':
				case 'M':
					cout << "Mongrel\n";
					inputRace = MONGREL;
					tempStats.strength = diceRoll(4, 6);
					tempStats.faith = diceRoll(3, 6);
					tempStats.dexterity = diceRoll(3, 6);
					tempStats.insperation = diceRoll(3, 6);
					tempStats.cleverness = diceRoll(3, 6);
					tempStats.focus = diceRoll(2, 6);
					break;
				case 's':
				case 'S':
					cout << "Shamani\n";
					inputRace = SHAMANI;
					tempStats.strength = diceRoll(2, 6);
					tempStats.faith = diceRoll(4, 6);
					tempStats.dexterity = diceRoll(3, 6);
					tempStats.insperation = diceRoll(3, 6);
					tempStats.cleverness = diceRoll(3, 6);
					tempStats.focus = diceRoll(3, 6);
					break;
				case 'n':
				case 'N':
					cout << "Nibelung\n";
					inputRace = NIBELUNG;
					tempStats.strength = diceRoll(3, 6);
					tempStats.faith = diceRoll(3, 6);
					tempStats.dexterity = diceRoll(2, 6);
					tempStats.insperation = diceRoll(3, 6);
					tempStats.cleverness = diceRoll(4, 6);
					tempStats.focus = diceRoll(3, 6);
					break;
				case 'u':
				case 'U':
					cout << "Undead\n";
					inputRace = UNDEAD;
					tempStats.strength = diceRoll(3, 6);
					tempStats.faith = diceRoll(3, 6);
					tempStats.dexterity = diceRoll(3, 6);
					tempStats.insperation = diceRoll(3, 6);
					tempStats.cleverness = diceRoll(2, 6);
					tempStats.focus = diceRoll(3, 6);
					break;
				default:
					cout << "Please input a vaild race.\n";
					retry = true;
					break;
			}
		}

		displayStats(tempStats);

		cout << "Reroll? [Y]es [N]o\n";

		cin >> inputs;

		reroll = false;

		if (inputs == 'y' || inputs == 'Y')
		{
			reroll = true;
		}
	}

	reroll = true;

	while (reroll) // While reroll == true
	{
		reroll = false;

		cout << "Please select a class\n";
		cout << "[F]ighter [C]leric [T]heif [B]ard [R]ouge [M]age\n";

		cin >> inputs;

		switch (inputs)
		{
			case 'f':
			case 'F':
				inputClass = FIGHTER;
				cout << "Fighter\n";
				break;
			case 'c':
			case 'C':
				inputClass = CLERIC;
				cout << "Cleric\n";
				break;
			case 't':
			case 'T':
				inputClass = THEIF;
				cout << "Theif\n";
				break;
			case 'b':
			case 'B':
				inputClass = BARD;
				cout << "Bard\n";
				break;
			case 'r':
			case 'R':
				inputClass = ROUGE;
				cout << "Rouge\n";
				break;
			case 'm':
			case 'M':
				inputClass = MAGE;
				cout << "Mage\n";
				break;
			default:
				cout << "Please input a valid class.\n";
				reroll = true;
				break;
		}
	}

	return 0;
}<|endoftext|>


<commit_before>//---------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2003, 2004, 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <base/quadrature_lib.h>
#include <base/table.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_accessor.h>
#include <fe/fe.h>
#include <fe/mapping.h>
#include <fe/fe_raviart_thomas.h>
#include <fe/fe_values.h>
#include <fe/fe_tools.h>

#ifdef HAVE_STD_STRINGSTREAM
#  include <sstream>
#else
#  include <strstream>
#endif

template <int dim>
FE_RaviartThomasNodal<dim>::FE_RaviartThomasNodal (const unsigned int deg)
		:
		FE_PolyTensor<PolynomialsRaviartThomas<dim>, dim> (
		  deg,
		  FiniteElementData<dim>(get_dpo_vector(deg),
					 dim, deg+1),
		  get_ria_vector (deg),
		  std::vector<std::vector<bool> >(
		    FiniteElementData<dim>(get_dpo_vector(deg),
					   dim,deg+1).dofs_per_cell,
		    std::vector<bool>(dim,true)))
{
  Assert (dim >= 2, ExcImpossibleInDim(dim));

  this->mapping_type = this->independent_on_cartesian;
				   // These must be done first, since
				   // they change the evaluation of
				   // basis functions
  initialize_unit_support_points (deg);
  initialize_node_matrix();

  for (unsigned int i=0; i<GeometryInfo<dim>::children_per_cell; ++i)
    this->prolongation[i].reinit (this->dofs_per_cell,
				  this->dofs_per_cell);
  FETools::compute_embedding_matrices (*this, &this->prolongation[0]);
}

template <int dim>
std::string
FE_RaviartThomasNodal<dim>::get_name () const
{
				   // note that the
				   // FETools::get_fe_from_name
				   // function depends on the
				   // particular format of the string
				   // this function returns, so they
				   // have to be kept in synch

#ifdef HAVE_STD_STRINGSTREAM
  std::ostringstream namebuf;
#else
  std::ostrstream namebuf;
#endif

  namebuf << "FE_RaviartThomasNodal<" << dim << ">(" << this->degree-1 << ")";

#ifndef HAVE_STD_STRINGSTREAM
  namebuf << std::ends;
#endif
  return namebuf.str();
}

template <int dim>
bool
FE_RaviartThomasNodal<dim>::has_support_on_face (unsigned int, unsigned int) const
{
  return true;
}

template <int dim>
FiniteElement<dim> *
FE_RaviartThomasNodal<dim>::clone() const
{
  return new FE_RaviartThomasNodal<dim>(this->degree-1);
}

#if deal_II_dimension == 1

template <>
std::vector<unsigned int>
FE_RaviartThomasNodal<1>::get_dpo_vector (const unsigned int deg)
{
  std::vector<unsigned int> dpo(2);
  dpo[0] = 1;
  dpo[1] = deg;
  return dpo;
}

#endif

template <int dim>
std::vector<unsigned int>
FE_RaviartThomasNodal<dim>::get_dpo_vector (const unsigned int deg)
{
                                   // the element is face-based and we have
                                   // (deg+1)^(dim-1) DoFs per face
  unsigned int dofs_per_face = 1;
  for (unsigned int d=0; d<dim-1; ++d)
    dofs_per_face *= deg+1;

                                   // and then there are interior dofs
  const unsigned int
    interior_dofs = dim*deg*dofs_per_face;

  std::vector<unsigned int> dpo(dim+1);
  dpo[dim-1] = dofs_per_face;
  dpo[dim]   = interior_dofs;

  return dpo;
}

#if deal_II_dimension == 1

template <>
std::vector<bool>
FE_RaviartThomasNodal<1>::get_ria_vector (const unsigned int)
{
  Assert (false, ExcImpossibleInDim(1));
  return std::vector<bool>();
}

#endif

template <int dim>
std::vector<bool>
FE_RaviartThomasNodal<dim>::get_ria_vector (const unsigned int deg)
{
  unsigned int dofs_per_cell, dofs_per_face;
  switch (dim)
    {
      case 2:
	    dofs_per_face = deg+1;
	    dofs_per_cell = 2*(deg+1)*(deg+2);
	    break;
      case 3:
	    dofs_per_face = (deg+1)*(deg+1);
	    dofs_per_cell = 3*(deg+1)*(deg+1)*(deg+2);
	    break;
      default:
	    Assert (false, ExcNotImplemented());
    }
  Assert (FiniteElementData<dim>(get_dpo_vector(deg),dim).dofs_per_cell ==
	  dofs_per_cell,
	  ExcInternalError());
  Assert (FiniteElementData<dim>(get_dpo_vector(deg),dim).dofs_per_face ==
	  dofs_per_face,
	  ExcInternalError());

				   // all face dofs need to be
				   // non-additive, since they have
				   // continuity requirements.
				   // however, the interior dofs are
				   // made additive
  std::vector<bool> ret_val(dofs_per_cell,false);
  for (unsigned int i=GeometryInfo<dim>::faces_per_cell*dofs_per_face;
       i < dofs_per_cell; ++i)
    ret_val[i] = true;

  return ret_val;
}

template <int dim>
void
FE_RaviartThomasNodal<dim>::initialize_unit_support_points (const unsigned int deg)
{
  this->unit_support_points.resize (this->dofs_per_cell);
  this->unit_face_support_points.resize (this->dofs_per_face);

  unsigned int current = 0;

				   // On the faces, we choose as many
				   // Gauss points as necessary to
				   // determine the normal component
				   // uniquely. This is the deg of
				   // the Raviart-Thomas element plus
				   // one.
  if (dim>1)
    {
      QGauss<dim-1> face_points (deg+1);
      Assert (face_points.n_quadrature_points == this->dofs_per_face,
	      ExcInternalError());
      for (unsigned int k=0;k<this->dofs_per_face;++k)
	this->unit_face_support_points[k] = face_points.point(k);
      Quadrature<dim> faces = QProjector<dim>::project_to_all_faces(face_points);
      for (unsigned int k=0;k<faces.n_quadrature_points;++k)
	this->unit_support_points[k] = faces.point(k);

      current = faces.n_quadrature_points;
    }
				   // In the interior, we need
				   // anisotropic Gauss quadratures,
				   // different for each direction.
  QGauss<1> high(deg+1);
  QGauss<1> low(deg);

  for (unsigned int d=0;d<dim;++d)
    {
      QAnisotropic<dim>* quadrature;
      if (dim == 1) quadrature = new QAnisotropic<dim>(high);
      if (dim == 2) quadrature = new QAnisotropic<dim>(((d==0) ? low : high),
						       ((d==1) ? low : high));
      if (dim == 3) quadrature = new QAnisotropic<dim>(((d==0) ? low : high),
						       ((d==1) ? low : high),
						       ((d==2) ? low : high));
      for (unsigned int k=0;k<quadrature->n_quadrature_points;++k)
	this->unit_support_points[current++] = quadrature->point(k);
      delete quadrature;
    }
  Assert (current == this->dofs_per_cell, ExcInternalError());
}

template <int dim>
void
FE_RaviartThomasNodal<dim>::initialize_node_matrix ()
{
  const unsigned int n_dofs = this->dofs_per_cell;

				   // We use an auxiliary matrix in
				   // this function. Therefore,
				   // inverse_node_matrix is still
				   // empty and shape_value_component
				   // returns the 'raw' shape values.
  FullMatrix<double> N(n_dofs, n_dofs);

				   // The curent node functional index
  unsigned int current = 0;

				   // For each face and all quadrature
				   // points on it, the node value is
				   // the normal component of the
				   // shape function, possibly
				   // pointing in negative direction.
  for (unsigned int face = 0; face<GeometryInfo<dim>::faces_per_cell; ++face)
    for (unsigned int k=0;k<this->dofs_per_face;++k)
      {
	for (unsigned int i=0;i<n_dofs;++i)
	  N(current,i) = this->shape_value_component(
	    i, this->unit_support_points[current],
	    GeometryInfo< dim >::unit_normal_direction[face])
			 * GeometryInfo< dim >::unit_normal_orientation[face];
	++current;
      }
				   // Interior degrees of freedom in each direction
  const unsigned int n_cell = (n_dofs - current) / dim;

  for (unsigned int d=0;d<dim;++d)
    for (unsigned int k=0;k<n_cell;++k)
      {
	for (unsigned int i=0;i<n_dofs;++i)
	  N(current,i) = this->shape_value_component(i, this->unit_support_points[current], d);
	++current;
      }
  Assert (current == n_dofs, ExcInternalError());
  this->inverse_node_matrix.reinit(n_dofs, n_dofs);
  this->inverse_node_matrix.invert(N);
}

template class FE_RaviartThomasNodal<deal_II_dimension>;
<commit_msg>fix node values in 2d and accomodate for Wolfgangs project_to_all_faces in 3d<commit_after>//---------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2003, 2004, 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <base/quadrature_lib.h>
#include <base/table.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_accessor.h>
#include <fe/fe.h>
#include <fe/mapping.h>
#include <fe/fe_raviart_thomas.h>
#include <fe/fe_values.h>
#include <fe/fe_tools.h>

#ifdef HAVE_STD_STRINGSTREAM
#  include <sstream>
#else
#  include <strstream>
#endif

#include <iostream>

template <int dim>
FE_RaviartThomasNodal<dim>::FE_RaviartThomasNodal (const unsigned int deg)
		:
		FE_PolyTensor<PolynomialsRaviartThomas<dim>, dim> (
		  deg,
		  FiniteElementData<dim>(get_dpo_vector(deg),
					 dim, deg+1),
		  get_ria_vector (deg),
		  std::vector<std::vector<bool> >(
		    FiniteElementData<dim>(get_dpo_vector(deg),
					   dim,deg+1).dofs_per_cell,
		    std::vector<bool>(dim,true)))
{
  Assert (dim >= 2, ExcImpossibleInDim(dim));

  this->mapping_type = this->independent_on_cartesian;
				   // These must be done first, since
				   // they change the evaluation of
				   // basis functions
  initialize_unit_support_points (deg);
  initialize_node_matrix();

  for (unsigned int i=0; i<GeometryInfo<dim>::children_per_cell; ++i)
    this->prolongation[i].reinit (this->dofs_per_cell,
				  this->dofs_per_cell);
  FETools::compute_embedding_matrices (*this, &this->prolongation[0]);
}

template <int dim>
std::string
FE_RaviartThomasNodal<dim>::get_name () const
{
				   // note that the
				   // FETools::get_fe_from_name
				   // function depends on the
				   // particular format of the string
				   // this function returns, so they
				   // have to be kept in synch

#ifdef HAVE_STD_STRINGSTREAM
  std::ostringstream namebuf;
#else
  std::ostrstream namebuf;
#endif

  namebuf << "FE_RaviartThomasNodal<" << dim << ">(" << this->degree-1 << ")";

#ifndef HAVE_STD_STRINGSTREAM
  namebuf << std::ends;
#endif
  return namebuf.str();
}

template <int dim>
bool
FE_RaviartThomasNodal<dim>::has_support_on_face (unsigned int, unsigned int) const
{
  return true;
}

template <int dim>
FiniteElement<dim> *
FE_RaviartThomasNodal<dim>::clone() const
{
  return new FE_RaviartThomasNodal<dim>(this->degree-1);
}

#if deal_II_dimension == 1

template <>
std::vector<unsigned int>
FE_RaviartThomasNodal<1>::get_dpo_vector (const unsigned int deg)
{
  std::vector<unsigned int> dpo(2);
  dpo[0] = 1;
  dpo[1] = deg;
  return dpo;
}

#endif

template <int dim>
std::vector<unsigned int>
FE_RaviartThomasNodal<dim>::get_dpo_vector (const unsigned int deg)
{
                                   // the element is face-based and we have
                                   // (deg+1)^(dim-1) DoFs per face
  unsigned int dofs_per_face = 1;
  for (unsigned int d=1; d<dim; ++d)
    dofs_per_face *= deg+1;

                                   // and then there are interior dofs
  const unsigned int
    interior_dofs = dim*deg*dofs_per_face;

  std::vector<unsigned int> dpo(dim+1);
  dpo[dim-1] = dofs_per_face;
  dpo[dim]   = interior_dofs;

  return dpo;
}

#if deal_II_dimension == 1

template <>
std::vector<bool>
FE_RaviartThomasNodal<1>::get_ria_vector (const unsigned int)
{
  Assert (false, ExcImpossibleInDim(1));
  return std::vector<bool>();
}

#endif

template <int dim>
std::vector<bool>
FE_RaviartThomasNodal<dim>::get_ria_vector (const unsigned int deg)
{
  unsigned int dofs_per_cell, dofs_per_face;
  switch (dim)
    {
      case 2:
	    dofs_per_face = deg+1;
	    dofs_per_cell = 2*(deg+1)*(deg+2);
	    break;
      case 3:
	    dofs_per_face = (deg+1)*(deg+1);
	    dofs_per_cell = 3*(deg+1)*(deg+1)*(deg+2);
	    break;
      default:
	    Assert (false, ExcNotImplemented());
    }
  Assert (FiniteElementData<dim>(get_dpo_vector(deg),dim).dofs_per_cell ==
	  dofs_per_cell,
	  ExcInternalError());
  Assert (FiniteElementData<dim>(get_dpo_vector(deg),dim).dofs_per_face ==
	  dofs_per_face,
	  ExcInternalError());

				   // all face dofs need to be
				   // non-additive, since they have
				   // continuity requirements.
				   // however, the interior dofs are
				   // made additive
  std::vector<bool> ret_val(dofs_per_cell,false);
  for (unsigned int i=GeometryInfo<dim>::faces_per_cell*dofs_per_face;
       i < dofs_per_cell; ++i)
    ret_val[i] = true;

  return ret_val;
}

template <int dim>
void
FE_RaviartThomasNodal<dim>::initialize_unit_support_points (const unsigned int deg)
{
  this->unit_support_points.resize (this->dofs_per_cell);
  this->unit_face_support_points.resize (this->dofs_per_face);

  unsigned int current = 0;

				   // On the faces, we choose as many
				   // Gauss points as necessary to
				   // determine the normal component
				   // uniquely. This is the deg of
				   // the Raviart-Thomas element plus
				   // one.
  if (dim>1)
    {
      QGauss<dim-1> face_points (deg+1);
      Assert (face_points.n_quadrature_points == this->dofs_per_face,
	      ExcInternalError());
      for (unsigned int k=0;k<this->dofs_per_face;++k)
	this->unit_face_support_points[k] = face_points.point(k);
      Quadrature<dim> faces = QProjector<dim>::project_to_all_faces(face_points);
      for (unsigned int k=0;k<//faces.n_quadrature_points
			  this->dofs_per_face*GeometryInfo<dim>::faces_per_cell;++k)
	this->unit_support_points[k] = faces.point(k);

      current = this->dofs_per_face*GeometryInfo<dim>::faces_per_cell;
    }

  if (deg==0) return;
				   // In the interior, we need
				   // anisotropic Gauss quadratures,
				   // different for each direction.
  QGauss<1> high(deg+1);
  QGauss<1> low(deg);

  for (unsigned int d=0;d<dim;++d)
    {
      QAnisotropic<dim>* quadrature;
      if (dim == 1) quadrature = new QAnisotropic<dim>(high);
      if (dim == 2) quadrature = new QAnisotropic<dim>(((d==0) ? low : high),
						       ((d==1) ? low : high));
      if (dim == 3) quadrature = new QAnisotropic<dim>(((d==0) ? low : high),
						       ((d==1) ? low : high),
						       ((d==2) ? low : high));
      for (unsigned int k=0;k<quadrature->n_quadrature_points;++k)
	this->unit_support_points[current++] = quadrature->point(k);
      delete quadrature;
    }
  Assert (current == this->dofs_per_cell, ExcInternalError());
}

template <int dim>
void
FE_RaviartThomasNodal<dim>::initialize_node_matrix ()
{
  const unsigned int n_dofs = this->dofs_per_cell;

				   // We use an auxiliary matrix in
				   // this function. Therefore,
				   // inverse_node_matrix is still
				   // empty and shape_value_component
				   // returns the 'raw' shape values.
  FullMatrix<double> N(n_dofs, n_dofs);

				   // The curent node functional index
  unsigned int current = 0;

				   // For each face and all quadrature
				   // points on it, the node value is
				   // the normal component of the
				   // shape function, possibly
				   // pointing in negative direction.
  for (unsigned int face = 0; face<GeometryInfo<dim>::faces_per_cell; ++face)
    for (unsigned int k=0;k<this->dofs_per_face;++k)
      {
	for (unsigned int i=0;i<n_dofs;++i)
	  N(current,i) = this->shape_value_component(
	    i, this->unit_support_points[current],
	    GeometryInfo< dim >::unit_normal_direction[face]);
//			 * GeometryInfo< dim >::unit_normal_orientation[face];
	++current;
      }
				   // Interior degrees of freedom in each direction
  const unsigned int n_cell = (n_dofs - current) / dim;

  for (unsigned int d=0;d<dim;++d)
    for (unsigned int k=0;k<n_cell;++k)
      {
	for (unsigned int i=0;i<n_dofs;++i)
	  N(current,i) = this->shape_value_component(i, this->unit_support_points[current], d);
	++current;
      }
  Assert (current == n_dofs, ExcInternalError());
  this->inverse_node_matrix.reinit(n_dofs, n_dofs);
  this->inverse_node_matrix.invert(N);
}

template class FE_RaviartThomasNodal<deal_II_dimension>;
<|endoftext|>


<commit_before>// -*- mode: c++ -*-
/**************************************************************************
 * 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.                  *
 **************************************************************************/

// Extraction of Amplitude and peak
// position using special algorithm
// from Alexei Pavlinov
// ----------------
// ----------------

#include "AliCaloRawAnalyzerFastFit.h"
#include "AliCaloFastAltroFitv0.h"
#include "AliCaloFitResults.h"
#include "AliCaloBunchInfo.h"
#include "TMath.h"
#include <iostream>

using namespace std;
#include "AliCaloConstants.h"

ClassImp( AliCaloRawAnalyzerFastFit )

AliCaloRawAnalyzerFastFit::AliCaloRawAnalyzerFastFit() : AliCaloRawAnalyzerFitter("Fast Fit (Alexei)", "FF")
{
  // Constructor
  fAlgo= Algo::kFastFit;
}

AliCaloFitResults
AliCaloRawAnalyzerFastFit::Evaluate( const vector<AliCaloBunchInfo> &bunchvector,
                                     UInt_t altrocfg1, UInt_t altrocfg2 )
{
  // Execute algorithm

  short maxampindex; //index of maximum amplitude
  short maxamp; //Maximum amplitude
  int index = SelectBunch( bunchvector,  &maxampindex,  &maxamp );

  if( index >= 0)
  {
    Float_t ped = ReverseAndSubtractPed( &(bunchvector.at(index))  ,  altrocfg1, altrocfg2, fReversed  );
    Float_t maxf = TMath::MaxElement( bunchvector.at(index).GetLength(),  fReversed );
    short timebinOffset = maxampindex - (bunchvector.at(index).GetLength()-1);

    if(  maxf < fAmpCut  ||  ( maxamp - ped) > fOverflowCut  ) // (maxamp - ped) > fOverflowCut = Close to saturation (use low gain then)
    {
      return  AliCaloFitResults( maxamp, ped, Algo::kCrude, maxf, timebinOffset*TIMEBINWITH); //Time scale 19/08/2014 (Antônio)
    }
    else if ( maxf >= fAmpCut ) // no if statement needed really; keep for readability
    {
      int first = 0;
      int last = 0;
      int maxrev =  maxampindex -  bunchvector.at(index).GetStartBin();

      SelectSubarray( fReversed,  bunchvector.at(index).GetLength(), maxrev , &first, &last, fFitArrayCut);

      int nsamples =  last - first + 1;

      if( ( nsamples  )  >= fNsampleCut )
	    {
	      Double_t ordered[1008];

	      for(int i=0; i < nsamples ; i++ )
        {
          ordered[i] = fReversed[first + i];
        }

	      Double_t eSignal = 1; // nominal 1 ADC error
	      Double_t dAmp = maxf;
	      Double_t eAmp = 0;
	      Double_t dTime0 = 0;
	      Double_t eTime = 0;
	      Double_t chi2 = 0;
	      Double_t dTau = 2.35; // time-bin units

	      AliCaloFastAltroFitv0::FastFit(fXaxis, ordered , nsamples,
                                       eSignal, dTau, dAmp, eAmp, dTime0, eTime, chi2);
	      Double_t dTimeMax = dTime0 + timebinOffset - (maxrev - first) // abs. t0
        + dTau; // +tau, makes sum tmax

	      return AliCaloFitResults(maxamp,ped,Ret::kFitPar,dAmp,dTimeMax*TIMEBINWITH,timebinOffset,chi2,Ret::kDummy,Ret::kDummy,AliCaloFitSubarray(index,maxrev,first,last)); //Time scale 19/08/2014 (Antônio)
	    } // samplecut
      else
	    {

	      Float_t chi2 = CalculateChi2(maxf, maxrev, first, last);
	      Int_t ndf = last - first - 1; // nsamples - 2
	      return AliCaloFitResults( maxamp, ped, Ret::kCrude, maxf, timebinOffset*TIMEBINWITH, timebinOffset, chi2, ndf, Ret::kDummy, AliCaloFitSubarray(index, maxrev, first, last) ); //Time scale 19/08/2014 (Antônio)
	    }
    } // ampcut
  } // bunch index

  return AliCaloFitResults( Ret::kInvalid , Ret::kInvalid );
}
<commit_msg>L1 Phase for FastFit<commit_after>// -*- mode: c++ -*-
/**************************************************************************
 * 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.                  *
 **************************************************************************/

// Extraction of Amplitude and peak
// position using special algorithm
// from Alexei Pavlinov
// ----------------
// ----------------

#include "AliCaloRawAnalyzerFastFit.h"
#include "AliCaloFastAltroFitv0.h"
#include "AliCaloFitResults.h"
#include "AliCaloBunchInfo.h"
#include "TMath.h"
#include <iostream>

using namespace std;
#include "AliCaloConstants.h"

ClassImp( AliCaloRawAnalyzerFastFit )

AliCaloRawAnalyzerFastFit::AliCaloRawAnalyzerFastFit() : AliCaloRawAnalyzerFitter("Fast Fit (Alexei)", "FF")
{
  // Constructor
  fAlgo= Algo::kFastFit;
}

AliCaloFitResults
AliCaloRawAnalyzerFastFit::Evaluate( const vector<AliCaloBunchInfo> &bunchvector,
                                     UInt_t altrocfg1, UInt_t altrocfg2 )
{
  // Execute algorithm

  short maxampindex; //index of maximum amplitude
  short maxamp; //Maximum amplitude
  int index = SelectBunch( bunchvector,  &maxampindex,  &maxamp );

  if( index >= 0)
  {
    Float_t ped = ReverseAndSubtractPed( &(bunchvector.at(index))  ,  altrocfg1, altrocfg2, fReversed  );
    Float_t maxf = TMath::MaxElement( bunchvector.at(index).GetLength(),  fReversed );
    short timebinOffset = maxampindex - (bunchvector.at(index).GetLength()-1);

    if(  maxf < fAmpCut  ||  ( maxamp - ped) > fOverflowCut  ) // (maxamp - ped) > fOverflowCut = Close to saturation (use low gain then)
    {
      return  AliCaloFitResults( maxamp, ped, Algo::kCrude, maxf, (timebinOffset*TIMEBINWITH)-fL1Phase); //Time scale 19/08/2014 (Antônio)
    }
    else if ( maxf >= fAmpCut ) // no if statement needed really; keep for readability
    {
      int first = 0;
      int last = 0;
      int maxrev =  maxampindex -  bunchvector.at(index).GetStartBin();

      SelectSubarray( fReversed,  bunchvector.at(index).GetLength(), maxrev , &first, &last, fFitArrayCut);

      int nsamples =  last - first + 1;

      if( ( nsamples  )  >= fNsampleCut )
	    {
	      Double_t ordered[1008];

	      for(int i=0; i < nsamples ; i++ )
        {
          ordered[i] = fReversed[first + i];
        }

	      Double_t eSignal = 1; // nominal 1 ADC error
	      Double_t dAmp = maxf;
	      Double_t eAmp = 0;
	      Double_t dTime0 = 0;
	      Double_t eTime = 0;
	      Double_t chi2 = 0;
	      Double_t dTau = 2.35; // time-bin units

	      AliCaloFastAltroFitv0::FastFit(fXaxis, ordered , nsamples,
                                       eSignal, dTau, dAmp, eAmp, dTime0, eTime, chi2);
	      Double_t dTimeMax = dTime0 + timebinOffset - (maxrev - first) // abs. t0
        + dTau; // +tau, makes sum tmax

	      return AliCaloFitResults(maxamp,ped,Ret::kFitPar,dAmp,(dTimeMax*TIMEBINWITH)-fL1Phase,timebinOffset,chi2,Ret::kDummy,Ret::kDummy,AliCaloFitSubarray(index,maxrev,first,last)); //Time scale 19/08/2014 (Antônio)
	    } // samplecut
      else
	    {

	      Float_t chi2 = CalculateChi2(maxf, maxrev, first, last);
	      Int_t ndf = last - first - 1; // nsamples - 2
	      return AliCaloFitResults( maxamp, ped, Ret::kCrude, maxf, (timebinOffset*TIMEBINWITH)-fL1Phase, timebinOffset, chi2, ndf, Ret::kDummy, AliCaloFitSubarray(index, maxrev, first, last) ); //Time scale 19/08/2014 (Antônio)
	    }
    } // ampcut
  } // bunch index

  return AliCaloFitResults( Ret::kInvalid , Ret::kInvalid );
}
<|endoftext|>


<commit_before>#include "nodes/VideoProc/OpticalFlow.h"
#include "nodes/VideoProc/Tracking.hpp"
#include <opencv2/cudaoptflow.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/cudaimgproc.hpp>
using namespace EagleLib;

#include "../RuntimeObjectSystem/ObjectInterfacePerModule.h"
#if __linux
RUNTIME_COMPILER_LINKLIBRARY("-lopencv_core -lopencv_cudaoptflow")
#endif
NODE_DEFAULT_CONSTRUCTOR_IMPL(SparsePyrLKOpticalFlow)
NODE_DEFAULT_CONSTRUCTOR_IMPL(BroxOpticalFlow)

void SparsePyrLKOpticalFlow::Init(bool firstInit)
{
    if(firstInit)
    {
        addInputParameter<cv::cuda::GpuMat>("Input Points");
        updateParameter("Window size", int(21));
        updateParameter("Max Levels", int(3));
        updateParameter("Iterations", int(30));
        updateParameter("Use initial flow", true);
        updateParameter("Enabled", false);
        parameters[1]->changed = true;
        addInputParameter<boost::function<void(cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, std::string&, cv::cuda::Stream)>>("Display function");
    }
    /*updateParameter<boost::function<void(cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::Stream)>>(
        "Set Reference", boost::bind(&SparsePyrLKOpticalFlow::setReferenceImage, this, _1, _2, _3), Parameters::Parameter::Output);

    updateParameter<TrackSparseFunctor>("Sparse Track Functor", boost::bind(&SparsePyrLKOpticalFlow::trackSparse, this, _1, _2, _3, _4, _5, _6, _7), Parameters::Parameter::Output);*/
}
void SparsePyrLKOpticalFlow::Serialize(ISimpleSerializer *pSerializer)
{
    Node::Serialize(pSerializer);
    SERIALIZE(optFlow);
}

cv::cuda::GpuMat SparsePyrLKOpticalFlow::doProcess(cv::cuda::GpuMat &img, cv::cuda::Stream& stream)
{
    if(parameters[1]->changed ||
       parameters[2]->changed ||
       parameters[3]->changed ||
       parameters[4]->changed)
    {
		int winSize = *getParameter<int>(1)->Data();
		int levels = *getParameter<int>(2)->Data();
		int iters = *getParameter<int>(3)->Data();
		bool useInital = *getParameter<bool>(4)->Data();
        optFlow = cv::cuda::SparsePyrLKOpticalFlow::create(cv::Size(winSize,winSize),levels,iters,useInital);
        parameters[1]->changed = false;
        parameters[2]->changed = false;
        parameters[3]->changed = false;
        parameters[4]->changed = false;
    }

    if(img.channels() != 1)
        cv::cuda::cvtColor(img,greyImg, cv::COLOR_BGR2GRAY,0, stream);
    else
        greyImg = img;
    if(refImg.empty())
    {
        refImg = greyImg;
        return img;
    }else
    {
		cv::cuda::GpuMat* inputPts = getParameter<cv::cuda::GpuMat>(0)->Data();
        if(!inputPts)
            return img;
        if(!inputPts->empty())
        {
            if(prevKeyPoints.size() != inputPts->size())
                inputPts->copyTo(prevKeyPoints, stream);
            cv::cuda::GpuMat status, error;
            trackSparse(refImg, greyImg,*inputPts, prevKeyPoints,status, error, stream);
        }
    }
    return img;
}
void SparsePyrLKOpticalFlow::setReferenceImage(cv::cuda::GpuMat img, cv::cuda::GpuMat keyPoints, cv::cuda::Stream& stream)
{
    if(img.channels() != 1)
        cv::cuda::cvtColor(img, refImg, cv::COLOR_BGR2GRAY,0, stream);
    refPts  = keyPoints;
    keyPoints.copyTo(trackedKeyPoints,stream);

}
void SparsePyrLKOpticalFlow::trackSparse(
        cv::cuda::GpuMat refImg, cv::cuda::GpuMat curImg,
        cv::cuda::GpuMat refPts, cv::cuda::GpuMat &trackedPts,
        cv::cuda::GpuMat& status, cv::cuda::GpuMat& err,
        cv::cuda::Stream stream)
{
    if(optFlow == nullptr)
    {
        //log(Error, "Optical flow not initialized correctly");
		NODE_LOG(error) << "Optical flow not initialized correctly";
        return;
    }
    if(trackedPts.empty())
    {
        trackedPts = cv::cuda::GpuMat(refPts.size(), refPts.type());
        refPts.copyTo(trackedPts,stream);
    }
    boost::function<void(cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, std::string&, cv::cuda::Stream)>* display =
            getParameter<boost::function<void(cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, std::string&, cv::cuda::Stream)>>("Display function")->Data();

    optFlow->calc(refImg, curImg, refPts, trackedPts, status, err, stream);
    if(display)
    {
        (*display)(curImg, refPts, trackedPts, status, fullTreeName, stream);
    }
    updateParameter("Tracked points", trackedPts, Parameters::Parameter::Output);
	updateParameter("Status", status, Parameters::Parameter::Output);
	updateParameter("Error", err, Parameters::Parameter::Output);

}

void BroxOpticalFlow::Init(bool firstInit)
{

}

cv::cuda::GpuMat BroxOpticalFlow::doProcess(cv::cuda::GpuMat &img, cv::cuda::Stream& stream)
{
	return img;
}

<commit_msg>Optical flow doesn't require greyscale iamges anymore.<commit_after>#include "nodes/VideoProc/OpticalFlow.h"
#include "nodes/VideoProc/Tracking.hpp"
#include <opencv2/cudaoptflow.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/cudaimgproc.hpp>
using namespace EagleLib;

#include "../RuntimeObjectSystem/ObjectInterfacePerModule.h"
#if __linux
RUNTIME_COMPILER_LINKLIBRARY("-lopencv_core -lopencv_cudaoptflow")
#endif
NODE_DEFAULT_CONSTRUCTOR_IMPL(SparsePyrLKOpticalFlow)
NODE_DEFAULT_CONSTRUCTOR_IMPL(BroxOpticalFlow)

void SparsePyrLKOpticalFlow::Init(bool firstInit)
{
    if(firstInit)
    {
        addInputParameter<cv::cuda::GpuMat>("Input Points");
        updateParameter("Window size", int(21));
        updateParameter("Max Levels", int(3));
        updateParameter("Iterations", int(30));
        updateParameter("Use initial flow", true);
        updateParameter("Enabled", false);
        parameters[1]->changed = true;
        addInputParameter<boost::function<void(cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, std::string&, cv::cuda::Stream)>>("Display function");
    }
    /*updateParameter<boost::function<void(cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::Stream)>>(
        "Set Reference", boost::bind(&SparsePyrLKOpticalFlow::setReferenceImage, this, _1, _2, _3), Parameters::Parameter::Output);

    updateParameter<TrackSparseFunctor>("Sparse Track Functor", boost::bind(&SparsePyrLKOpticalFlow::trackSparse, this, _1, _2, _3, _4, _5, _6, _7), Parameters::Parameter::Output);*/
}
void SparsePyrLKOpticalFlow::Serialize(ISimpleSerializer *pSerializer)
{
    Node::Serialize(pSerializer);
    SERIALIZE(optFlow);
}

cv::cuda::GpuMat SparsePyrLKOpticalFlow::doProcess(cv::cuda::GpuMat &img, cv::cuda::Stream& stream)
{
    if(parameters[1]->changed ||
       parameters[2]->changed ||
       parameters[3]->changed ||
       parameters[4]->changed)
    {
		int winSize = *getParameter<int>(1)->Data();
		int levels = *getParameter<int>(2)->Data();
		int iters = *getParameter<int>(3)->Data();
		bool useInital = *getParameter<bool>(4)->Data();
        optFlow = cv::cuda::SparsePyrLKOpticalFlow::create(cv::Size(winSize,winSize),levels,iters,useInital);
        parameters[1]->changed = false;
        parameters[2]->changed = false;
        parameters[3]->changed = false;
        parameters[4]->changed = false;
    }

    if(img.channels() != 1)
        cv::cuda::cvtColor(img,greyImg, cv::COLOR_BGR2GRAY,0, stream);
    else
        greyImg = img;
    if(refImg.empty())
    {
        refImg = greyImg;
        return img;
    }else
    {
		cv::cuda::GpuMat* inputPts = getParameter<cv::cuda::GpuMat>(0)->Data();
        if(!inputPts)
            return img;
        if(!inputPts->empty())
        {
            if(prevKeyPoints.size() != inputPts->size())
                inputPts->copyTo(prevKeyPoints, stream);
            cv::cuda::GpuMat status, error;
            trackSparse(refImg, greyImg,*inputPts, prevKeyPoints,status, error, stream);
        }
    }
    return img;
}
void SparsePyrLKOpticalFlow::setReferenceImage(cv::cuda::GpuMat img, cv::cuda::GpuMat keyPoints, cv::cuda::Stream& stream)
{
	refImg = img;
    refPts  = keyPoints;
    keyPoints.copyTo(trackedKeyPoints,stream);

}
void SparsePyrLKOpticalFlow::trackSparse(
        cv::cuda::GpuMat refImg, cv::cuda::GpuMat curImg,
        cv::cuda::GpuMat refPts, cv::cuda::GpuMat &trackedPts,
        cv::cuda::GpuMat& status, cv::cuda::GpuMat& err,
        cv::cuda::Stream stream)
{
    if(optFlow == nullptr)
    {
        //log(Error, "Optical flow not initialized correctly");
		NODE_LOG(error) << "Optical flow not initialized correctly";
        return;
    }
    if(trackedPts.empty())
    {
        trackedPts = cv::cuda::GpuMat(refPts.size(), refPts.type());
        refPts.copyTo(trackedPts,stream);
    }
    boost::function<void(cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, std::string&, cv::cuda::Stream)>* display =
            getParameter<boost::function<void(cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, cv::cuda::GpuMat, std::string&, cv::cuda::Stream)>>("Display function")->Data();

    optFlow->calc(refImg, curImg, refPts, trackedPts, status, err, stream);
    if(display)
    {
        (*display)(curImg, refPts, trackedPts, status, fullTreeName, stream);
    }
    updateParameter("Tracked points", trackedPts, Parameters::Parameter::Output);
	updateParameter("Status", status, Parameters::Parameter::Output);
	updateParameter("Error", err, Parameters::Parameter::Output);

}

void BroxOpticalFlow::Init(bool firstInit)
{

}

cv::cuda::GpuMat BroxOpticalFlow::doProcess(cv::cuda::GpuMat &img, cv::cuda::Stream& stream)
{
	return img;
}

<|endoftext|>


<commit_before>#include "itkImage.h"
#include "itkPoint.h"

int main()
{

  typedef itk::Image< unsigned short, 3 > ImageType;

  ImageType::Pointer image = ImageType::New();

  ImageType::IndexType start;
  ImageType::SizeType  size;

  size[0]  = 200;  // size along X
  size[1]  = 200;  // size along Y
  size[2]  = 200;  // size along Z

  start[0] =   0;  // first index on X
  start[1] =   0;  // first index on Y
  start[2] =   0;  // first index on Z

  ImageType::RegionType region;

  image->SetRegions( region );
  image->Allocate();

  image->FillBuffer( 0 );

  double spacing[ 3 ];

  spacing[0] = 0.33; // spacing in millimeters
  spacing[1] = 0.33; // spacing in millimeters
  spacing[2] = 1.20; // spacing in millimeters

  image->SetSpacing( spacing );

  double origin[ 3 ];

  origin[0] = 0.0;  // coordinates of the
  origin[1] = 0.0;  // first pixel in N-D
  origin[2] = 0.0;

  image->SetOrigin( origin );

  typedef itk::Point<double,3> PointType;

  PointType point;

  point[0] = 1.45;
  point[1] = 7.21;
  point[2] = 9.28;

  ImageType::IndexType pixelIndex;

  image->TransformPhysicalPointToIndex( point, pixelIndex );

  ImageType::PixelType value = image->GetPixel( pixelIndex );

  return 0;

}

<commit_msg>ENH: Full documentation added. Verified to match with the SoftwareGuide.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    Image4.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

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

// Software Guide : BeginLatex
//
// Even though ITK can be used for performing general image processing tasks,
// the main target of the toolkit is the processing of medical image data.
// In that perspective, additional information about the images is considered
// mandatory. In particular the information associated with the physical
// spacing between pixels and the position of the image in space with
// respect to some world coordinates reference system are considered to
// be extremly important.
//
// The values assiged to origin and spacing are fundamental in many
// applications. Registration, for example, is entirely performed in
// physical coordinates. Poorly defined spacing and origins will result
// in inconsistent results in such processes. Medical images lacking
// spatial information should not be used for purposes like medical
// diagnosis, image analysis, feature extraction, assisted radiation
// therapy or image guided surgery. In other words, medical images
// lacking spacing are not only useless but rather hazardous.
//
// Software Guide : EndLatex

#include "itkImage.h"
#include "itkPoint.h"

int main()
{

  typedef itk::Image< unsigned short, 3 > ImageType;

  ImageType::Pointer image = ImageType::New();

  ImageType::IndexType start;
  ImageType::SizeType  size;

  size[0]  = 200;  // size along X
  size[1]  = 200;  // size along Y
  size[2]  = 200;  // size along Z

  start[0] =   0;  // first index on X
  start[1] =   0;  // first index on Y
  start[2] =   0;  // first index on Z

  ImageType::RegionType region;

  image->SetRegions( region );
  image->Allocate();

  image->FillBuffer( 0 );

  // Software Guide : BeginLatex
  //
  // Image spacing is represented in an C-like array of doubles
  // whose size matches the dimension of the image. In order
  // to manually set the spacing of the image, an array of
  // the corresponding type must be created. The elements of
  // the array should then be initialized with the spacing
  // between the centers of the adjacent pixels. The following
  // code illustrates the methods available in the image class
  // for dealing with spacing and origin.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  double spacing[ ImageType::ImageDimension ];

  spacing[0] = 0.33; // spacing in millimeters along X
  spacing[1] = 0.33; // spacing in millimeters along Y
  spacing[2] = 1.20; // spacing in millimeters along Z
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The array can be assigned to the image using
  // the \texttt{SetSpacing()} method.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  image->SetSpacing( spacing );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Image origin is managed in a similar way to the spacing.
  // A C-like array of doubles matching the dimension of the
  // image must be allocated first. The coordinates of the
  // origin can then be assigned to every component. These
  // coordinates correspond to the position of the first
  // pixel of the image with respect to an arbitrary reference
  // system in physical space. It is the user's responsibility
  // to make sure that multiple images used in the same application
  // are using a consisten reference system. This is extremly
  // important in image registration applications.
  //
  // The following code illustrates the creation and assignment
  // of a variable suitable for initializing the image origin.
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  double origin[ ImageType::ImageDimension ];

  origin[0] = 0.0;  // coordinates of the
  origin[1] = 0.0;  // first pixel in N-D
  origin[2] = 0.0;

  image->SetOrigin( origin );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Once the spacing and origin of the image have been initialized
  // the image is in condition to map pixel indices to physical
  // space coordinates and back. The following code illustrates
  // how a point in physical space can be mapped into an image index
  // for the purpose of reading the content of the closest pixel.
  //
  // First, a PointType must be declared. The point type is templated
  // over the type used to represent coordinates and over the dimension
  // of the space. In this particular case, the dimension of the
  // point must match the dimension of the image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::Point< double, ImageType::ImageDimension > PointType;
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // A point, like the index, is a relatively small and simple object.
  // for this reason it is not reference counted like the large data
  // objects in ITK and as a consequence it is not managed by SmartPointers.
  // Point objects are simply declared as instances of any other C++ class.
  // Once the point is declared, its components can be accessed using
  // traditional array notation. In particular the \texttt{[]} operator
  // is available. For efficiency reasons, no bound checking is performed
  // on the index used to access a particular point component. It is the
  // user's responsibility to make sure that the index is in the range
  // $\{0,Dimension-1\}$
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  PointType point;

  point[0] = 1.45;
  point[1] = 7.21;
  point[2] = 9.28;
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The image can map this point to an index using the values of the
  // current spacing and origin. An index object must be provided to
  // receive the results of the mapping. The index object can be
  // instantiated by using the \texttt{IndexType} defined in the Image
  // type.
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  ImageType::IndexType pixelIndex;
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The \texttt{TransformPhysicalPointToIndex()} method of the image class
  // will compute the pixel index closest to the point provided. The method
  // checks for this index to be contained inside the current buffered pixel
  // data. The method returns a boolean indicating whether the resulting
  // index falls inside the buffered region or not. The output index should
  // not be used when the returned value of the method is \texttt{false}.
  //
  // The following lines illustrate the point to index mapping and the subsequent
  // use of the pixel index for accessing pixel data from the image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  image->TransformPhysicalPointToIndex( point, pixelIndex );

  ImageType::PixelType pixelValue = image->GetPixel( pixelIndex );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Remember that \texttt{GetPixel()} and \texttt{SetPixel()} are very
  // inefficient methods for accessing pixel data. Image iterators should be
  // used for when massive access to pixel data is required.
  //
  // Software Guide : EndLatex

  return 0;

}

<|endoftext|>