<commit_before>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.

#ifndef POSEIDON_NETWORK_SOCKET_ADDRESS_HPP_
#define POSEIDON_NETWORK_SOCKET_ADDRESS_HPP_

#include "../fwd.hpp"
#include "enums.hpp"
#include <sys/socket.h>
#include <netinet/in.h>

namespace poseidon {

class Socket_Address
  {
  public:
    // For maximum compatibility, this union is recommended to be used
    // in place of the legacy `::sockaddr`.
    union storage_type
      {
        ::sockaddr_storage stor;
        ::sockaddr addr;
        ::sockaddr_in addr4;
        ::sockaddr_in6 addr6;

        constexpr operator
        const sockaddr*()
        const noexcept
          { return &(this->addr);  }

        operator
        sockaddr*()
        noexcept
          { return &(this->addr);  }

        constexpr operator
        const sockaddr_in*()
        const noexcept
          { return &(this->addr4);  }

        operator
        sockaddr_in*()
        noexcept
          { return &(this->addr4);  }

        constexpr operator
        const sockaddr_in6*()
        const noexcept
          { return &(this->addr6);  }

        operator
        sockaddr_in6*()
        noexcept
          { return &(this->addr6);  }
      };

    using size_type = ::socklen_t;

  private:
    storage_type m_stor;
    size_type m_size;

  public:
    // Note this is a trivially copyable and destructible class.
    constexpr
    Socket_Address()
    noexcept
      : m_stor(), m_size(0)
      { }

    Socket_Address(const storage_type& stor, size_type size)
    noexcept
      { this->assign(stor, size);  }

    Socket_Address(const char* host, uint16_t port)
      { this->parse(host, port);  }

  public:
    // Gets the `AF_` or `PF_` field.
    ::sa_family_t
    family()
    const noexcept
      { return this->m_stor.addr.sa_family;  }

    // Checks whether this is an IPv4 address.
    // An IPv4-mapped IPv6 address is not an IPv4 one.
    bool
    is_ipv4()
    const noexcept
      { return this->m_stor.addr.sa_family == AF_INET;  }

    // Checks whether this is an IPv6 address.
    // An IPv4-mapped IPv6 address is an IPv6 one.
    bool
    is_ipv6()
    const noexcept
      { return this->m_stor.addr.sa_family == AF_INET6;  }

    // Gets internal data.
    // The pointer and size can be passed to `bind()` or `connect()`
    const storage_type&
    data()
    const noexcept
      { return this->m_stor;  }

    ::socklen_t
    size()
    const noexcept
      { return this->m_size;  }

    // Resets to the default-constructed one (all zeroes).
    Socket_Address&
    clear()
    noexcept
      {
        this->m_stor.addr.sa_family = 0;
        this->m_size = 0;
        return *this;
      }

    Socket_Address&
    swap(Socket_Address& other)
    noexcept
      {
        ::std::swap(this->m_stor, other.m_stor);
        ::std::swap(this->m_size, other.m_size);
        return *this;
      }

    // Classifies this address.
    ROCKET_PURE_FUNCTION
    Address_Class
    classify()
    const noexcept;

    bool
    is_loopback()
    const noexcept
      { return this->classify() == address_class_loopback;  }

    bool
    is_private()
    const noexcept
      { return this->classify() == address_class_private;  }

    bool
    is_multicast()
    const noexcept
      { return this->classify() == address_class_multicast;  }

    bool
    is_public()
    const noexcept
      { return this->classify() == address_class_public;  }

    // Sets contents from the result of a call to `recvfrom()`.
    // Either an IPv4 or IPv6 address may be specified. The address family is
    // detected automatically.
    // This function throws an exception upon failure, and the contents of `*this`
    // is undefined.
    Socket_Address&
    assign(const storage_type& stor, size_type size)
    noexcept
      {
        this->m_stor = stor;
        this->m_size = size;
        return *this;
      }

    // Loads address from a string.
    // Either an IPv4 or IPv6 address may be specified. The address family is
    // detected automatically.
    // This function throws an exception upon failure, and the contents of `*this`
    // is undefined.
    Socket_Address&
    parse(const char* host, uint16_t port);

    // Converts this address to a human-readable string.
    // This is the inverse function of `assign()` except that the port is appended
    // to the host as a string, separated by a colon.
    tinyfmt&
    print(tinyfmt& fmt)
    const;
  };

inline
void
swap(Socket_Address& lhs, Socket_Address& rhs)
noexcept
  { lhs.swap(rhs);  }

inline
tinyfmt&
operator<<(tinyfmt& fmt, const Socket_Address& addr)
  { return addr.print(fmt);  }

}  // namespace poseidon

#endif
<commit_msg>network/socket_address: Add conversion to `void*`<commit_after>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.

#ifndef POSEIDON_NETWORK_SOCKET_ADDRESS_HPP_
#define POSEIDON_NETWORK_SOCKET_ADDRESS_HPP_

#include "../fwd.hpp"
#include "enums.hpp"
#include <sys/socket.h>
#include <netinet/in.h>

namespace poseidon {

class Socket_Address
  {
  public:
    // For maximum compatibility, this union is recommended to be used
    // in place of the legacy `::sockaddr`.
    union storage_type
      {
        ::sockaddr_storage stor;
        ::sockaddr addr;
        ::sockaddr_in addr4;
        ::sockaddr_in6 addr6;

        constexpr operator
        const void*()
        const noexcept
          { return &(this->addr);  }

        operator
        void*()
        noexcept
          { return &(this->addr);  }

        constexpr operator
        const sockaddr*()
        const noexcept
          { return &(this->addr);  }

        operator
        sockaddr*()
        noexcept
          { return &(this->addr);  }

        constexpr operator
        const sockaddr_in*()
        const noexcept
          { return &(this->addr4);  }

        operator
        sockaddr_in*()
        noexcept
          { return &(this->addr4);  }

        constexpr operator
        const sockaddr_in6*()
        const noexcept
          { return &(this->addr6);  }

        operator
        sockaddr_in6*()
        noexcept
          { return &(this->addr6);  }
      };

    using size_type = ::socklen_t;

  private:
    storage_type m_stor;
    size_type m_size;

  public:
    // Note this is a trivially copyable and destructible class.
    constexpr
    Socket_Address()
    noexcept
      : m_stor(), m_size(0)
      { }

    Socket_Address(const storage_type& stor, size_type size)
    noexcept
      { this->assign(stor, size);  }

    Socket_Address(const char* host, uint16_t port)
      { this->parse(host, port);  }

  public:
    // Gets the `AF_` or `PF_` field.
    ::sa_family_t
    family()
    const noexcept
      { return this->m_stor.addr.sa_family;  }

    // Checks whether this is an IPv4 address.
    // An IPv4-mapped IPv6 address is not an IPv4 one.
    bool
    is_ipv4()
    const noexcept
      { return this->m_stor.addr.sa_family == AF_INET;  }

    // Checks whether this is an IPv6 address.
    // An IPv4-mapped IPv6 address is an IPv6 one.
    bool
    is_ipv6()
    const noexcept
      { return this->m_stor.addr.sa_family == AF_INET6;  }

    // Gets internal data.
    // The pointer and size can be passed to `bind()` or `connect()`
    const storage_type&
    data()
    const noexcept
      { return this->m_stor;  }

    ::socklen_t
    size()
    const noexcept
      { return this->m_size;  }

    // Resets to the default-constructed one (all zeroes).
    Socket_Address&
    clear()
    noexcept
      {
        this->m_stor.addr.sa_family = 0;
        this->m_size = 0;
        return *this;
      }

    Socket_Address&
    swap(Socket_Address& other)
    noexcept
      {
        ::std::swap(this->m_stor, other.m_stor);
        ::std::swap(this->m_size, other.m_size);
        return *this;
      }

    // Classifies this address.
    ROCKET_PURE_FUNCTION
    Address_Class
    classify()
    const noexcept;

    bool
    is_loopback()
    const noexcept
      { return this->classify() == address_class_loopback;  }

    bool
    is_private()
    const noexcept
      { return this->classify() == address_class_private;  }

    bool
    is_multicast()
    const noexcept
      { return this->classify() == address_class_multicast;  }

    bool
    is_public()
    const noexcept
      { return this->classify() == address_class_public;  }

    // Sets contents from the result of a call to `recvfrom()`.
    // Either an IPv4 or IPv6 address may be specified. The address family is
    // detected automatically.
    // This function throws an exception upon failure, and the contents of `*this`
    // is undefined.
    Socket_Address&
    assign(const storage_type& stor, size_type size)
    noexcept
      {
        this->m_stor = stor;
        this->m_size = size;
        return *this;
      }

    // Loads address from a string.
    // Either an IPv4 or IPv6 address may be specified. The address family is
    // detected automatically.
    // This function throws an exception upon failure, and the contents of `*this`
    // is undefined.
    Socket_Address&
    parse(const char* host, uint16_t port);

    // Converts this address to a human-readable string.
    // This is the inverse function of `assign()` except that the port is appended
    // to the host as a string, separated by a colon.
    tinyfmt&
    print(tinyfmt& fmt)
    const;
  };

inline
void
swap(Socket_Address& lhs, Socket_Address& rhs)
noexcept
  { lhs.swap(rhs);  }

inline
tinyfmt&
operator<<(tinyfmt& fmt, const Socket_Address& addr)
  { return addr.print(fmt);  }

}  // namespace poseidon

#endif
<|endoftext|>


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

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

  Copyright (c) Insight Software 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.

=========================================================================*/
#ifndef _itkPowellOptimizer_cxx
#define _itkPowellOptimizer_cxx

#include "itkPowellOptimizer.h"

const double POWELL_BRACKET_GOLD = 1.618034;
const double POWELL_BRENT_GOLD = 0.3819660;
const double POWELL_GLIMIT = 100.0;
const double POWELL_TINY = 1.0e-20;

namespace itk
{

PowellOptimizer
::PowellOptimizer()
{
  m_Maximize = false;

  m_StepLength = 1.0;
  m_StepTolerance = 0.00001;
  m_ValueTolerance = 0.00001;

  m_Stop = false ;

  m_CurrentCost = 0;
  m_CurrentIteration = 0;
  m_CurrentLineIteration = 0;

  m_MaximumIteration = 100 ;

  m_MaximumLineIteration = 100 ;
}

PowellOptimizer
::~PowellOptimizer()
{
}

void
PowellOptimizer
::SetLine(const PowellOptimizer::ParametersType & origin,
          const vnl_vector<double> & direction)
{
  m_LineOrigin = origin;
  m_LineDirection = direction;
  for(int i=0; i<m_SpaceDimension; i++)
    {
    m_LineDirection[i] = m_LineDirection[i] / this->GetScales()[i];
    }
}

double
PowellOptimizer
::GetLineValue(double x) const
{
  PowellOptimizer::ParametersType xCoord( m_SpaceDimension );
  for(int i=0; i<m_SpaceDimension; i++)
    {
    xCoord[i] = this->m_LineOrigin[i] + x * this->m_LineDirection[i];
    }
  if(m_Maximize)
    {
    return -(this->m_CostFunction->GetValue(xCoord));
    }
  else
    {
    return this->m_CostFunction->GetValue(xCoord);
    }
}

void
PowellOptimizer
::SetCurrentLinePoint(double x, double fx)
{
  PowellOptimizer::ParametersType xCoord( m_SpaceDimension );
  for(int i=0; i<m_SpaceDimension; i++)
    {
    xCoord[i] = this->m_LineOrigin[i] + x * this->m_LineDirection[i];
    }
  this->SetCurrentPosition(xCoord);
  if(m_Maximize)
    {
    this->SetCurrentCost(-fx);
    }
  else
    {
    this->SetCurrentCost(fx);
    }
}

void
PowellOptimizer
::Swap(double * a, double  * b) const
{
  double tf;
  tf = *a;
  *a = *b;
  *b = tf;
}

void
PowellOptimizer
::Shift(double *a, double *b, double *c, double d) const
{
  *a = *b;
  *b = *c;
  *c = d;
}

void
PowellOptimizer
::LineBracket(double * ax, double * bx, double * cx,
              double * fa, double * fb, double * fc)
{
  double ulim,u,r,q,fu,dq;

  //*fa = this->GetLineValue(*ax);
  *fb = this->GetLineValue(*bx);
  if (*fb > *fa)
    {
    this->Swap(ax, bx);
    this->Swap(fa, fb);
    }

  *cx = (*bx) + POWELL_BRACKET_GOLD * (*bx - *ax);
  *fc = this->GetLineValue(*cx);
  while (*fb > *fc)
    {
    r = (*bx - *ax) * (*fb - *fc);
    q = (*bx - *cx) * (*fb - *fa);

    dq = q - r;
    if (vcl_abs(dq) < POWELL_TINY)
      {
      dq = vnl_math_sgn(dq) * POWELL_TINY;
      }
    u = (*bx) - ( (*bx - *cx) * q - (*bx - *ax) * r ) / (2.0 * dq);
    ulim = (*bx) + POWELL_GLIMIT * (*cx - *bx);

    if ( (*bx - u) * (u - *cx) > 0.0 )
      {
      fu = this->GetLineValue(u);
      if (fu < *fc)
        {
        *ax = (*bx);
        *bx = u;
        *fa = (*fb);
        *fb = fu;
        return;
        }
      else if (fu > *fb)
        {
        *cx=u;
        *fc=fu;
        return;
        }
      u = (*cx) + POWELL_BRACKET_GOLD * (*cx - *bx);
      fu = this->GetLineValue(u);
      }
    else if ( (*cx - u) * (u - ulim) > 0.0 )
      {
      fu = this->GetLineValue(u);
      if (fu < *fc)
        {
        //SHFT(bx,cx,&u,*cx+GOLD*(*cx-*bx)); awf dumped -- c is useless
        this->Shift(bx, cx, &u, u + POWELL_BRACKET_GOLD * (u - *cx));
        this->Shift(fb, fc, &fu, this->GetLineValue(u));
        }
      }
    else if ( (u - ulim) * (ulim - *cx) >= 0.0)
      {
      u = ulim;
      fu = this->GetLineValue(u);
      }
    else
      {
      u = (*cx) + POWELL_BRACKET_GOLD * (*cx - *bx);
      fu = this->GetLineValue(u);
      }

    this->Shift(ax, bx, cx, u);
    this->Shift(fa, fb, fc, fu);
    }

  this->SetCurrentLinePoint(*bx, *fb);

}

void
PowellOptimizer
::BracketedLineOptimize(double ax, double bx, double cx,
                        double itkNotUsed(fa), double fb, double itkNotUsed(fc),
                        double * extX, double * extVal)
{
  double a, b;
  double d=0.0;
  double etemp,fu,fv,fw,fx,p,q,r,tol1,tol2,u,v,w,x,xm;
  double e=0.0;

  a = (ax < cx ? ax : cx);
  b = (ax > cx ? ax : cx);
  x = w = v = bx;
  fw = fv = fx = fb;
  for (m_CurrentLineIteration = 0;
       m_CurrentLineIteration < m_MaximumLineIteration;
       m_CurrentLineIteration++)
    {
    xm = 0.5*(a+b);
    tol1 = m_StepTolerance * vcl_fabs(x) + POWELL_TINY;
    tol2 = 2.0 * tol1;
    if (vcl_fabs(x-xm) <= (tol2 - 0.5*(b-a))
        || 0.5*(b-a) < m_StepTolerance)
      {
      *extX = x;
      *extVal = fx;
      this->SetCurrentLinePoint(x, fx);
      return;
      }
    if (vcl_fabs(e) > tol1)
      {
      r = (x-w) * (fx-fv);
      q = (x-v) * (fx-fw);
      p = (x-v)*q - (x-w)*r;
      q = 2.0 * (q-r);
      if (q > 0.0)
        {
        p = -p;
        }
      q = vcl_fabs(q);
      etemp = e;
      e = d;
      if (vcl_fabs(p) >= vcl_fabs(0.5*q*etemp)
          || p <= q*(a-x)
          || p >= q*(b-x))
        {
        if(x >= xm)
          {
          e = a - x;
          }
        else
          {
          e = b - x;
          }
        d = POWELL_BRENT_GOLD * e;
        }
      else
        {
        d = p/q;
        u = x+d;
        if (u-a < tol2 || b-u < tol2)
          {
          d = tol1 * vnl_math_sgn(xm-x);
          }
        }
      }
    else
      {
      if(x >= xm)
        {
        e = a - x;
        }
      else
        {
        e = b - x;
        }
      d = POWELL_BRENT_GOLD * e;
      }
    if(vcl_fabs(d) >= tol1)
      {
      u = x + d;
      }
    else
      {
      u = x + tol1 * vnl_math_sgn(d);
      }
    fu = this->GetLineValue(u);
    if (fu <= fx)
      {
      if (u >= x)
        {
        a = x;
        }
      else
        {
        b = x;
        }
      this->Shift(&v, &w, &x, u);
      this->Shift(&fv, &fw, &fx, fu);
      }
    else
      {
      if (u < x)
        {
        a = u;
        }
      else
        {
        b = u;
        }
      if (fu <= fw || w == x)
        {
        v = w;
        w = u;
        fv = fw;
        fw = fu;
        }
      else if (fu <= fv || v == x || v == w)
        {
        v = u;
        fv = fu;
        }
      }
    }

  *extX = x;
  *extVal = fx;
  this->SetCurrentLinePoint(x, fx);
}

void
PowellOptimizer
::StartOptimization()
{
  if( m_CostFunction.IsNull() )
    {
    return ;
    }

  this->InvokeEvent( StartEvent() );
  m_Stop = false ;

  m_SpaceDimension = m_CostFunction->GetNumberOfParameters();
  m_LineOrigin.set_size(m_SpaceDimension);
  m_LineDirection.set_size(m_SpaceDimension);

  vnl_matrix<double> xi(m_SpaceDimension, m_SpaceDimension);
  vnl_vector<double> xit(m_SpaceDimension);
  xi.set_identity();
  xit.fill(0);
  xit[0] = 1;

  PowellOptimizer::ParametersType p(m_SpaceDimension);
  PowellOptimizer::ParametersType pt(m_SpaceDimension);
  PowellOptimizer::ParametersType ptt(m_SpaceDimension);
  p = this->GetInitialPosition();
  pt = p;

  int ibig;
  double fp, del, fptt;
  double ax, xx, bx;
  double fa, fx, fb;

  xx = 0;
  this->SetLine(p, xit);
  fx = this->GetLineValue(0);

  for (m_CurrentIteration = 0;
       m_CurrentIteration <= m_MaximumIteration;
       m_CurrentIteration++)
    {
    fp = fx;
    ibig = 0;
    del = 0.0;

    for (int i = 0; i < m_SpaceDimension; i++)
      {
      for (int j = 0; j < m_SpaceDimension; ++j)
        {
        xit[j] = xi[j][i];
        }
      fptt = fx;

      this->SetLine(p, xit);

      ax = 0.0;
      fa = fx;
      xx = m_StepLength;
      this->LineBracket(&ax, &xx, &bx, &fa, &fx, &fb);
      this->BracketedLineOptimize(ax, xx, bx, fa, fx, fb, &xx, &fx);
      this->SetCurrentLinePoint(xx, fx);
      p = this->GetCurrentPosition();

      if (vcl_fabs(fptt-fx) > del)
        {
        del = vcl_fabs(fptt-fx);
        ibig = i;
        }
      }

    if (2.0*vcl_fabs(fp-fx)
        <= m_ValueTolerance*(vcl_fabs(fp)+vcl_fabs(fx)))
      {
      this->InvokeEvent( EndEvent() );
      return;
      }

    for (int j = 0; j < m_SpaceDimension; ++j)
      {
      ptt[j] = 2.0*p[j] - pt[j];
      xit[j] = p[j] - pt[j];
      pt[j] = p[j];
      }

    this->SetLine(ptt, xit);
    fptt = this->GetLineValue(0);
    if (fptt < fp)
      {
      double t = 2.0 * (fp - 2.0*fx + fptt)
                     * vnl_math_sqr(fp-fx-del)
                     - del * vnl_math_sqr(fp-fptt);
      if (t < 0.0)
        {
        this->SetLine(p, xit);

        ax = 0.0;
        fa = fx;
        xx = 1;
        this->LineBracket(&ax, &xx, &bx, &fa, &fx, &fb);
        this->BracketedLineOptimize(ax, xx, bx, fa, fx, fb, &xx, &fx);
        this->SetCurrentLinePoint(xx, fx);
        p = this->GetCurrentPosition();

        for (int j = 0; j < m_SpaceDimension; j++)
          {
          xi[j][ibig] = xx * xit[j];
          }
        }
      }

    this->InvokeEvent( IterationEvent() );

    }

  this->InvokeEvent( EndEvent() );

}

/**
 *
 */
void
PowellOptimizer
::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os,indent);

  os << indent << "Space Dimension   " << m_SpaceDimension   << std::endl;
  os << indent << "Maximum Iteration " << m_MaximumIteration << std::endl;
  os << indent << "Current Iteration " << m_CurrentIteration << std::endl;
  os << indent << "Maximize On/Off   " << m_Maximize         << std::endl;
  os << indent << "StepLength        " << m_StepLength       << std::endl;
  os << indent << "StepTolerance     " << m_StepTolerance    << std::endl;
  os << indent << "ValueTolerance    " << m_ValueTolerance   << std::endl;
  os << indent << "LineOrigin        " << m_LineOrigin       << std::endl;
  os << indent << "LineDirection     " << m_LineDirection    << std::endl;
  os << indent << "Current Cost      " << m_CurrentCost      << std::endl;
  os << indent << "Stop              " << m_Stop             << std::endl;
}

} // end of namespace itk
#endif
<commit_msg>BUG: Fixed signed/unsigned comparison warnings<commit_after>/*=========================================================================

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

  Copyright (c) Insight Software 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.

=========================================================================*/
#ifndef _itkPowellOptimizer_cxx
#define _itkPowellOptimizer_cxx

#include "itkPowellOptimizer.h"

const double POWELL_BRACKET_GOLD = 1.618034;
const double POWELL_BRENT_GOLD = 0.3819660;
const double POWELL_GLIMIT = 100.0;
const double POWELL_TINY = 1.0e-20;

namespace itk
{

PowellOptimizer
::PowellOptimizer()
{
  m_Maximize = false;

  m_StepLength = 1.0;
  m_StepTolerance = 0.00001;
  m_ValueTolerance = 0.00001;

  m_Stop = false ;

  m_CurrentCost = 0;
  m_CurrentIteration = 0;
  m_CurrentLineIteration = 0;

  m_MaximumIteration = 100 ;

  m_MaximumLineIteration = 100 ;
}

PowellOptimizer
::~PowellOptimizer()
{
}

void
PowellOptimizer
::SetLine(const PowellOptimizer::ParametersType & origin,
          const vnl_vector<double> & direction)
{
  m_LineOrigin = origin;
  m_LineDirection = direction;
  for(unsigned int i=0; i<m_SpaceDimension; i++)
    {
    m_LineDirection[i] = m_LineDirection[i] / this->GetScales()[i];
    }
}

double
PowellOptimizer
::GetLineValue(double x) const
{
  PowellOptimizer::ParametersType xCoord( m_SpaceDimension );
  for(unsigned int i=0; i<m_SpaceDimension; i++)
    {
    xCoord[i] = this->m_LineOrigin[i] + x * this->m_LineDirection[i];
    }
  if(m_Maximize)
    {
    return -(this->m_CostFunction->GetValue(xCoord));
    }
  else
    {
    return this->m_CostFunction->GetValue(xCoord);
    }
}

void
PowellOptimizer
::SetCurrentLinePoint(double x, double fx)
{
  PowellOptimizer::ParametersType xCoord( m_SpaceDimension );
  for(unsigned int i=0; i<m_SpaceDimension; i++)
    {
    xCoord[i] = this->m_LineOrigin[i] + x * this->m_LineDirection[i];
    }
  this->SetCurrentPosition(xCoord);
  if(m_Maximize)
    {
    this->SetCurrentCost(-fx);
    }
  else
    {
    this->SetCurrentCost(fx);
    }
}

void
PowellOptimizer
::Swap(double * a, double  * b) const
{
  double tf;
  tf = *a;
  *a = *b;
  *b = tf;
}

void
PowellOptimizer
::Shift(double *a, double *b, double *c, double d) const
{
  *a = *b;
  *b = *c;
  *c = d;
}

void
PowellOptimizer
::LineBracket(double * ax, double * bx, double * cx,
              double * fa, double * fb, double * fc)
{
  double ulim,u,r,q,fu,dq;

  //*fa = this->GetLineValue(*ax);
  *fb = this->GetLineValue(*bx);
  if (*fb > *fa)
    {
    this->Swap(ax, bx);
    this->Swap(fa, fb);
    }

  *cx = (*bx) + POWELL_BRACKET_GOLD * (*bx - *ax);
  *fc = this->GetLineValue(*cx);
  while (*fb > *fc)
    {
    r = (*bx - *ax) * (*fb - *fc);
    q = (*bx - *cx) * (*fb - *fa);

    dq = q - r;
    if (vcl_abs(dq) < POWELL_TINY)
      {
      dq = vnl_math_sgn(dq) * POWELL_TINY;
      }
    u = (*bx) - ( (*bx - *cx) * q - (*bx - *ax) * r ) / (2.0 * dq);
    ulim = (*bx) + POWELL_GLIMIT * (*cx - *bx);

    if ( (*bx - u) * (u - *cx) > 0.0 )
      {
      fu = this->GetLineValue(u);
      if (fu < *fc)
        {
        *ax = (*bx);
        *bx = u;
        *fa = (*fb);
        *fb = fu;
        return;
        }
      else if (fu > *fb)
        {
        *cx=u;
        *fc=fu;
        return;
        }
      u = (*cx) + POWELL_BRACKET_GOLD * (*cx - *bx);
      fu = this->GetLineValue(u);
      }
    else if ( (*cx - u) * (u - ulim) > 0.0 )
      {
      fu = this->GetLineValue(u);
      if (fu < *fc)
        {
        //SHFT(bx,cx,&u,*cx+GOLD*(*cx-*bx)); awf dumped -- c is useless
        this->Shift(bx, cx, &u, u + POWELL_BRACKET_GOLD * (u - *cx));
        this->Shift(fb, fc, &fu, this->GetLineValue(u));
        }
      }
    else if ( (u - ulim) * (ulim - *cx) >= 0.0)
      {
      u = ulim;
      fu = this->GetLineValue(u);
      }
    else
      {
      u = (*cx) + POWELL_BRACKET_GOLD * (*cx - *bx);
      fu = this->GetLineValue(u);
      }

    this->Shift(ax, bx, cx, u);
    this->Shift(fa, fb, fc, fu);
    }

  this->SetCurrentLinePoint(*bx, *fb);

}

void
PowellOptimizer
::BracketedLineOptimize(double ax, double bx, double cx,
                        double itkNotUsed(fa), double fb, double itkNotUsed(fc),
                        double * extX, double * extVal)
{
  double a, b;
  double d=0.0;
  double etemp,fu,fv,fw,fx,p,q,r,tol1,tol2,u,v,w,x,xm;
  double e=0.0;

  a = (ax < cx ? ax : cx);
  b = (ax > cx ? ax : cx);
  x = w = v = bx;
  fw = fv = fx = fb;
  for (m_CurrentLineIteration = 0;
       m_CurrentLineIteration < m_MaximumLineIteration;
       m_CurrentLineIteration++)
    {
    xm = 0.5*(a+b);
    tol1 = m_StepTolerance * vcl_fabs(x) + POWELL_TINY;
    tol2 = 2.0 * tol1;
    if (vcl_fabs(x-xm) <= (tol2 - 0.5*(b-a))
        || 0.5*(b-a) < m_StepTolerance)
      {
      *extX = x;
      *extVal = fx;
      this->SetCurrentLinePoint(x, fx);
      return;
      }
    if (vcl_fabs(e) > tol1)
      {
      r = (x-w) * (fx-fv);
      q = (x-v) * (fx-fw);
      p = (x-v)*q - (x-w)*r;
      q = 2.0 * (q-r);
      if (q > 0.0)
        {
        p = -p;
        }
      q = vcl_fabs(q);
      etemp = e;
      e = d;
      if (vcl_fabs(p) >= vcl_fabs(0.5*q*etemp)
          || p <= q*(a-x)
          || p >= q*(b-x))
        {
        if(x >= xm)
          {
          e = a - x;
          }
        else
          {
          e = b - x;
          }
        d = POWELL_BRENT_GOLD * e;
        }
      else
        {
        d = p/q;
        u = x+d;
        if (u-a < tol2 || b-u < tol2)
          {
          d = tol1 * vnl_math_sgn(xm-x);
          }
        }
      }
    else
      {
      if(x >= xm)
        {
        e = a - x;
        }
      else
        {
        e = b - x;
        }
      d = POWELL_BRENT_GOLD * e;
      }
    if(vcl_fabs(d) >= tol1)
      {
      u = x + d;
      }
    else
      {
      u = x + tol1 * vnl_math_sgn(d);
      }
    fu = this->GetLineValue(u);
    if (fu <= fx)
      {
      if (u >= x)
        {
        a = x;
        }
      else
        {
        b = x;
        }
      this->Shift(&v, &w, &x, u);
      this->Shift(&fv, &fw, &fx, fu);
      }
    else
      {
      if (u < x)
        {
        a = u;
        }
      else
        {
        b = u;
        }
      if (fu <= fw || w == x)
        {
        v = w;
        w = u;
        fv = fw;
        fw = fu;
        }
      else if (fu <= fv || v == x || v == w)
        {
        v = u;
        fv = fu;
        }
      }
    }

  *extX = x;
  *extVal = fx;
  this->SetCurrentLinePoint(x, fx);
}

void
PowellOptimizer
::StartOptimization()
{
  if( m_CostFunction.IsNull() )
    {
    return ;
    }

  this->InvokeEvent( StartEvent() );
  m_Stop = false ;

  m_SpaceDimension = m_CostFunction->GetNumberOfParameters();
  m_LineOrigin.set_size(m_SpaceDimension);
  m_LineDirection.set_size(m_SpaceDimension);

  vnl_matrix<double> xi(m_SpaceDimension, m_SpaceDimension);
  vnl_vector<double> xit(m_SpaceDimension);
  xi.set_identity();
  xit.fill(0);
  xit[0] = 1;

  PowellOptimizer::ParametersType p(m_SpaceDimension);
  PowellOptimizer::ParametersType pt(m_SpaceDimension);
  PowellOptimizer::ParametersType ptt(m_SpaceDimension);
  p = this->GetInitialPosition();
  pt = p;

  unsigned int ibig;
  double fp, del, fptt;
  double ax, xx, bx;
  double fa, fx, fb;

  xx = 0;
  this->SetLine(p, xit);
  fx = this->GetLineValue(0);

  for (m_CurrentIteration = 0;
       m_CurrentIteration <= m_MaximumIteration;
       m_CurrentIteration++)
    {
    fp = fx;
    ibig = 0;
    del = 0.0;

    for (unsigned int i = 0; i < m_SpaceDimension; i++)
      {
      for (unsigned int j = 0; j < m_SpaceDimension; ++j)
        {
        xit[j] = xi[j][i];
        }
      fptt = fx;

      this->SetLine(p, xit);

      ax = 0.0;
      fa = fx;
      xx = m_StepLength;
      this->LineBracket(&ax, &xx, &bx, &fa, &fx, &fb);
      this->BracketedLineOptimize(ax, xx, bx, fa, fx, fb, &xx, &fx);
      this->SetCurrentLinePoint(xx, fx);
      p = this->GetCurrentPosition();

      if (vcl_fabs(fptt-fx) > del)
        {
        del = vcl_fabs(fptt-fx);
        ibig = i;
        }
      }

    if (2.0*vcl_fabs(fp-fx)
        <= m_ValueTolerance*(vcl_fabs(fp)+vcl_fabs(fx)))
      {
      this->InvokeEvent( EndEvent() );
      return;
      }

    for (unsigned int j = 0; j < m_SpaceDimension; ++j)
      {
      ptt[j] = 2.0*p[j] - pt[j];
      xit[j] = p[j] - pt[j];
      pt[j] = p[j];
      }

    this->SetLine(ptt, xit);
    fptt = this->GetLineValue(0);
    if (fptt < fp)
      {
      double t = 2.0 * (fp - 2.0*fx + fptt)
                     * vnl_math_sqr(fp-fx-del)
                     - del * vnl_math_sqr(fp-fptt);
      if (t < 0.0)
        {
        this->SetLine(p, xit);

        ax = 0.0;
        fa = fx;
        xx = 1;
        this->LineBracket(&ax, &xx, &bx, &fa, &fx, &fb);
        this->BracketedLineOptimize(ax, xx, bx, fa, fx, fb, &xx, &fx);
        this->SetCurrentLinePoint(xx, fx);
        p = this->GetCurrentPosition();

        for (unsigned int j = 0; j < m_SpaceDimension; j++)
          {
          xi[j][ibig] = xx * xit[j];
          }
        }
      }

    this->InvokeEvent( IterationEvent() );

    }

  this->InvokeEvent( EndEvent() );

}

/**
 *
 */
void
PowellOptimizer
::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os,indent);

  os << indent << "Space Dimension   " << m_SpaceDimension   << std::endl;
  os << indent << "Maximum Iteration " << m_MaximumIteration << std::endl;
  os << indent << "Current Iteration " << m_CurrentIteration << std::endl;
  os << indent << "Maximize On/Off   " << m_Maximize         << std::endl;
  os << indent << "StepLength        " << m_StepLength       << std::endl;
  os << indent << "StepTolerance     " << m_StepTolerance    << std::endl;
  os << indent << "ValueTolerance    " << m_ValueTolerance   << std::endl;
  os << indent << "LineOrigin        " << m_LineOrigin       << std::endl;
  os << indent << "LineDirection     " << m_LineDirection    << std::endl;
  os << indent << "Current Cost      " << m_CurrentCost      << std::endl;
  os << indent << "Stop              " << m_Stop             << std::endl;
}

} // end of namespace itk
#endif
<|endoftext|>


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

// Add task B2
// author: Eulogio Serradilla <eulogio.serradilla@cern.ch>

Double_t GetMeanNtrk(const TString& period);

AliAnalysisTaskB2* AddTaskB2(const TString& species,
                             const TString& outputfile,
                             const TString& trksel,
                             Int_t pidProc,
                             const TString& periodname,
                             Bool_t simulation=kFALSE,
                             Bool_t heavyIons=kFALSE,
                             Double_t maxDCAxy=1,
                             Double_t maxDCAz=2,
                             Double_t minKNOmult=-10,
                             Double_t maxKNOmult=10000,
                             Bool_t V0AND=kFALSE,
                             Double_t minCentrality=0,
                             Double_t maxCentrality=20)
{
//
// Create, configure and add the analysis task to the analysis manager
//
	using namespace std;

	// sample config

	const Double_t kMaxVx     = 1.;
	const Double_t kMaxVy     = 1.;
	const Double_t kMaxVz     = 10.;

	const Double_t kMaxY      = 0.5;
	const Double_t kMaxEta    = 0.8;
	const Double_t kMaxNSigma = 3.;

	const Int_t kMaxNSigmaITS = 3;
	const Int_t kMaxNSigmaTPC = 3;
	const Int_t kMaxNSigmaTOF = 3;
	const Int_t kMinTPCnCls   = 70;

	TString period = periodname;
	period.ToLower();

	// Get pointer to the existing analysis manager

	AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
	if (!mgr)
	{
		cerr << "AddTaskB2: no analysis manager to connect to" << endl;
		return 0;
	}

	if (!mgr->GetInputEventHandler())
	{
		cerr << "AddTaskB2: this task requires an input event handler" << endl;
		return 0;
	}

	// Create and configure the task

	AliAnalysisTaskB2* task = new AliAnalysisTaskB2(Form("B2_%s",species.Data()));

	task->SetParticleSpecies(species);
	task->SetSimulation(simulation);
	task->SetHeavyIons(heavyIons);
	task->SetV0ANDtrigger(V0AND);

	task->SetMaxNSigmaITS(kMaxNSigmaITS);
	task->SetMaxNSigmaTPC(kMaxNSigmaTPC);
	task->SetMaxNSigmaTOF(kMaxNSigmaTOF);

	task->SetMeanNtrk(GetMeanNtrk(period));
	task->SetKNOmultInterval(minKNOmult, maxKNOmult);
	task->SetVertexXInterval(-kMaxVx, kMaxVx);
	task->SetVertexYInterval(-kMaxVy, kMaxVy);
	task->SetVertexZInterval(-kMaxVz, kMaxVz);

	task->SetCentralityInterval(minCentrality, maxCentrality);

	if(period=="lhc11a_wsdd" || period=="lhc11a_wosdd")
	{
		task->SetNoFastOnlyTrigger();
	}

	// histograms

	gROOT->LoadMacro("$ALICE_ROOT/PWGLF/SPECTRA/Nuclei/B2/macros/CreateHistograms.C");

	AliLnHistoMap* hMap = CreateHistograms(species, simulation, maxDCAxy, kMaxEta, kMaxY, heavyIons);

	task->SetHistogramMap(hMap);

	// track selection criteria

	gROOT->LoadMacro("$ALICE_ROOT/PWGLF/SPECTRA/Nuclei/B2/macros/TrackCuts.C");

	AliESDtrackCuts* trkCuts = TrackCuts(task, trksel, maxDCAxy, maxDCAz, kMaxNSigma, kMinTPCnCls, kMaxEta);
	task->SetESDtrackCuts(trkCuts);

	// PID

	gROOT->LoadMacro("$ALICE_ROOT/PWGLF/SPECTRA/Nuclei/B2/macros/BetheBlochParams.C");

	Double_t bethe[5];
	BetheBlochParams(bethe, period);

	gROOT->LoadMacro("$ALICE_ROOT/PWGLF/SPECTRA/Nuclei/B2/macros/PriorProbabilities.C");

	Double_t prob[9];
	PriorProbabilities(prob, period, trksel);

	AliLnID* lnID = new AliLnID();

	lnID->SetTPCBetheBlochParams(bethe);
	lnID->SetPriorProbabilities(prob);
	lnID->SetPidProcedure(pidProc);

	task->SetPID(lnID);

	// Add task to the manager

	mgr->AddTask(task);

	// input and output containers

	AliAnalysisDataContainer* output = mgr->CreateContainer(outputfile.Data(), AliLnHistoMap::Class(), AliAnalysisManager::kOutputContainer, outputfile.Data());

	mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
	mgr->ConnectOutput(task, 0, output);

	return task;
}

Double_t GetMeanNtrk(const TString& period)
{
//
// average track multiplicity <Ntrk> for the given period
//
	if(period =="lhc10c900")    return 3.70158; // pass3
	if(period =="lhc10b_pass2") return 9.86258;
	if(period =="lhc10c_pass2") return 9.61402;
	if(period =="lhc10b")       return 5.96104; // pass3
	if(period =="lhc10c")       return 5.94719; // pass3
	if(period =="lhc10d")       return 5.82333; // pass2
	if(period =="lhc10e")       return 5.89367; // pass2
	if(period =="lhc11a_wosdd") return 4.28597; // pass3
	if(period =="lhc11a_wsdd")  return 4.57960; // pass4

	// MC
	if(period =="lhc10e13")            return 3.17763;
	if(period =="lhc10f6a")            return 4.41362;
	if(period =="lhc10e21")            return 4.74991;
	if(period =="lhc11e3a_plus_wosdd") return 3.37669;
	if(period =="lhc11e3a_plus_wsdd")  return 3.55973;

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

// Add task B2
// author: Eulogio Serradilla <eulogio.serradilla@cern.ch>

Double_t GetMeanNtrk(const TString& period);

AliAnalysisTaskB2* AddTaskB2(const TString& species,
                             const TString& outputfile,
                             const TString& trksel,
                             Int_t pidProc,
                             const TString& periodname,
                             Bool_t simulation=kFALSE,
                             Bool_t heavyIons=kFALSE,
                             Double_t maxDCAxy=1,
                             Double_t maxDCAz=2,
                             Double_t minKNOmult=-10,
                             Double_t maxKNOmult=10000,
                             Bool_t V0AND=kFALSE,
                             Double_t minCentrality=0,
                             Double_t maxCentrality=20)
{
//
// Create, configure and add the analysis task to the analysis manager
//
	using namespace std;

	// sample config

	const Double_t kMaxVx     = 1.;
	const Double_t kMaxVy     = 1.;
	const Double_t kMaxVz     = 10.;

	const Double_t kMaxY      = 0.5;
	const Double_t kMaxEta    = 0.8;
	const Double_t kMaxNSigma = 3.;

	const Int_t kMaxNSigmaITS = 3;
	const Int_t kMaxNSigmaTPC = 3;
	const Int_t kMaxNSigmaTOF = 3;
	const Int_t kMinTPCnCls   = 70;

	const Double_t kMinM2     = 2.; // for deuterons
	const Double_t kMaxM2     = 6.;

	TString period = periodname;
	period.ToLower();

	// Get pointer to the existing analysis manager

	AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
	if (!mgr)
	{
		cerr << "AddTaskB2: no analysis manager to connect to" << endl;
		return 0;
	}

	if (!mgr->GetInputEventHandler())
	{
		cerr << "AddTaskB2: this task requires an input event handler" << endl;
		return 0;
	}

	// Create and configure the task

	AliAnalysisTaskB2* task = new AliAnalysisTaskB2(Form("B2_%s",species.Data()));

	task->SetParticleSpecies(species);
	task->SetSimulation(simulation);
	task->SetHeavyIons(heavyIons);
	task->SetV0ANDtrigger(V0AND);

	task->SetMaxNSigmaITS(kMaxNSigmaITS);
	task->SetMaxNSigmaTPC(kMaxNSigmaTPC);
	task->SetMaxNSigmaTOF(kMaxNSigmaTOF);

	task->SetMeanNtrk(GetMeanNtrk(period));
	task->SetKNOmultInterval(minKNOmult, maxKNOmult);
	task->SetVertexXInterval(-kMaxVx, kMaxVx);
	task->SetVertexYInterval(-kMaxVy, kMaxVy);
	task->SetVertexZInterval(-kMaxVz, kMaxVz);

	task->SetM2Interval(kMinM2, kMaxM2);

	task->SetCentralityInterval(minCentrality, maxCentrality);

	if(period=="lhc11a_wsdd" || period=="lhc11a_wosdd")
	{
		task->SetNoFastOnlyTrigger();
	}

	// histograms

	gROOT->LoadMacro("$ALICE_ROOT/PWGLF/SPECTRA/Nuclei/B2/macros/CreateHistograms.C");

	AliLnHistoMap* hMap = CreateHistograms(species, simulation, maxDCAxy, kMaxEta, kMaxY, heavyIons);

	task->SetHistogramMap(hMap);

	// track selection criteria

	gROOT->LoadMacro("$ALICE_ROOT/PWGLF/SPECTRA/Nuclei/B2/macros/TrackCuts.C");

	AliESDtrackCuts* trkCuts = TrackCuts(task, trksel, maxDCAxy, maxDCAz, kMaxNSigma, kMinTPCnCls, kMaxEta);
	task->SetESDtrackCuts(trkCuts);

	// PID

	gROOT->LoadMacro("$ALICE_ROOT/PWGLF/SPECTRA/Nuclei/B2/macros/BetheBlochParams.C");

	Double_t bethe[5];
	BetheBlochParams(bethe, period);

	gROOT->LoadMacro("$ALICE_ROOT/PWGLF/SPECTRA/Nuclei/B2/macros/PriorProbabilities.C");

	Double_t prob[9];
	PriorProbabilities(prob, period, trksel);

	AliLnID* lnID = new AliLnID();

	lnID->SetTPCBetheBlochParams(bethe);
	lnID->SetPriorProbabilities(prob);
	lnID->SetPidProcedure(pidProc);

	task->SetPID(lnID);

	// Add task to the manager

	mgr->AddTask(task);

	// input and output containers

	AliAnalysisDataContainer* output = mgr->CreateContainer(outputfile.Data(), AliLnHistoMap::Class(), AliAnalysisManager::kOutputContainer, outputfile.Data());

	mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
	mgr->ConnectOutput(task, 0, output);

	return task;
}

Double_t GetMeanNtrk(const TString& period)
{
//
// average track multiplicity <Ntrk> for the given period
//
	if(period =="lhc10c900")    return 3.70158; // pass3
	if(period =="lhc10b_pass2") return 9.86258;
	if(period =="lhc10c_pass2") return 9.61402;
	if(period =="lhc10b")       return 5.96104; // pass3
	if(period =="lhc10c")       return 5.94719; // pass3
	if(period =="lhc10d")       return 5.82333; // pass2
	if(period =="lhc10e")       return 5.89367; // pass2
	if(period =="lhc11a_wosdd") return 4.28597; // pass3
	if(period =="lhc11a_wsdd")  return 4.57960; // pass4

	// MC
	if(period =="lhc10e13")            return 3.17763;
	if(period =="lhc10f6a")            return 4.41362;
	if(period =="lhc10e21")            return 4.74991;
	if(period =="lhc11e3a_plus_wosdd") return 3.37669;
	if(period =="lhc11e3a_plus_wsdd")  return 3.55973;

	return 1;
}
<|endoftext|>


<commit_before>/*

 This macros setup the TPC calibration task AddTaskTPCCalib
 for CPass1.
 - the run number is required to config TPC OCDB

 The following calibration components are added to the AliTPCAnalysisTaskcalib task:
 1. AliTPCcalibCalib - redo reconstruction with current calibration
 2. AliTPCcalibTimeGain - TPC time dependent gain calibration
 3. AliTPCcalibTime - TPC time dependent drift time calibration

*/

// function to set TPC OCDB parameters
void ConfigOCDB(Int_t crun);

Int_t debugLevel=0;
Int_t streamLevel=0;

//_____________________________________________________________________________
AliAnalysisTask  *AddTaskTPCCalib(Int_t runNumber)
{
  //
  // add calibration task
  //
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskTPCCalib", "No analysis manager to connect to.");
    return NULL;
  }

  // check the input handler
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskTPCCalib", "This task requires an input event handler");
    return NULL;
  }

  // set TPC OCDB parameters
  ConfigOCDB(runNumber);

  // setup task
  AliTPCAnalysisTaskcalib *task1=new AliTPCAnalysisTaskcalib("CalibObjectsTrain1");
  SetupCalibTaskTrain1(task1);
  mgr->AddTask(task1);

  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
  if (!cinput1) cinput1 = mgr->CreateContainer("cchain",TChain::Class(),
                                      AliAnalysisManager::kInputContainer);
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("TPCCalib",TObjArray::Class(), AliAnalysisManager::kOutputContainer, "AliESDfriends_v1.root");

  mgr->ConnectInput(task1,0,cinput1);
  mgr->ConnectOutput(task1,0,coutput1);
  return task1;
}

//_____________________________________________________________________________
void AddCalibCalib(TObject* task){
  //
  // Responsible: Marian Ivanov
  // Description:
  // calibCalib is a prefilter
  // The current OCDB entries transformation are applied on cluster, tracks are refitted
  //
  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;
  AliTPCcalibCalib *calibCalib = new AliTPCcalibCalib("calibTPC","calibTPC");
  calibCalib->SetDebugLevel(0);
  calibCalib->SetStreamLevel(0);
  calibCalib->SetTriggerMask(-1,-1,kFALSE);        //accept everything
  myTask->AddJob(calibCalib);
}

//_____________________________________________________________________________
void AddCalibTimeGain(TObject* task, Bool_t isCosmic = kFALSE, char * name = "calibTimeGain"){
  //
  //  Responsible: Alexander Kalweit
  //  Description: Time Gain calibration
  //

  // Set run time ranges (time stamps)
  AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
  if(!entry) {
    ::Error("AddCalibTimeGain","Cannot get AliCDBEntry");
    return;
  }
  const AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());
  if(!grpData) {
    ::Error("AddCalibTimeGain","Cannot get AliGRPObject");
    return;
  }
  time_t sTime = grpData->GetTimeStart();
  time_t eTime = grpData->GetTimeEnd();
  TTimeStamp startRunTime(sTime);
  TTimeStamp stopRunTime(eTime);

  UInt_t year;
  startRunTime.GetDate(kTRUE,0,&year);
  TTimeStamp startTime(year,1,1,0,0,0);
  TTimeStamp stopTime(year,12,31,23,59,59);

  //
  // setup calibration component
  //

  Bool_t useQmax = (grpData->GetBeamType()).Contains("Pb-Pb");

  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;
  AliTPCcalibTimeGain *calibTimeGain = new AliTPCcalibTimeGain(name,"calibTimeGain", startTime.GetSec(), stopTime.GetSec(), 10*60);
  calibTimeGain->SetIsCosmic(isCosmic);
  calibTimeGain->SetUseCookAnalytical(kTRUE);
  calibTimeGain->SetUseMax(useQmax);
  calibTimeGain->SetDebugLevel(0);
  calibTimeGain->SetStreamLevel(0);
  calibTimeGain->SetTriggerMask(-1,-1,kTRUE);        //reject laser
  calibTimeGain->SetLowerTrunc(0.02);
  calibTimeGain->SetUpperTrunc(0.6);

  myTask->AddJob(calibTimeGain);

  AliTPCcalibGainMult *calibGainMult = new AliTPCcalibGainMult("calibGainMult","calibGainMult");
  calibGainMult->SetUseMax(useQmax);
  calibGainMult->SetDebugLevel(0);
  calibGainMult->SetStreamLevel(0);
  calibGainMult->SetTriggerMask(-1,-1,kTRUE);        //reject laser
  calibGainMult->SetLowerTrunc(0.02);
  calibGainMult->SetUpperTrunc(0.6);

  myTask->AddJob(calibGainMult);

}

//_____________________________________________________________________________
void AddCalibTime(TObject* task){
  //
  // Responsible: Dag Larsen
  // Description: Time V drift calibration
  //

  // Set run time ranges (time stamps)
  AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
  if(!entry) {
    ::Error("AddCalibTime","Cannot get AliCDBEntry");
    return;
  }
  const AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());
  if(!grpData) {
    ::Error("AddCalibTime","Cannot get AliGRPObject");
    return;
  }
  time_t sTime = grpData->GetTimeStart();
  time_t eTime = grpData->GetTimeEnd();

  TTimeStamp startRunTime(sTime);
  TTimeStamp stopRunTime(eTime);

  UInt_t year;
  startRunTime.GetDate(kTRUE,0,&year);
  TTimeStamp startTime(year,1,1,0,0,0);
  TTimeStamp stopTime(year,12,31,23,59,59);

  //
  // setup calibration component
  //
  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;
  AliTPCcalibTime *calibTime = new AliTPCcalibTime("calibTime","calibTime",  startTime.GetSec(), stopTime.GetSec(), 10*60, 2);
  calibTime->SetDebugLevel(0);
  calibTime->SetStreamLevel(0);
  calibTime->SetTriggerMask(-1,-1,kFALSE);        //accept everything

  // max 600 tracks per event
  calibTime->SetCutTracks(600);

  myTask->AddJob(calibTime);
}

void AddCalibTracks(TObject* task){
  //
  // Responsible: Marian Ivanov
  // Description:
  // Histogram residuals and pulls of the track parameters in bins of track parameters
  //
  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;
  AliTPCClusterParam * clusterParam = AliTPCcalibDB::Instance()->GetClusterParam();

   AliTPCcalibTracksCuts *cuts = new AliTPCcalibTracksCuts(30, 0.4, 5, 0.13, 0.018);
  //
  AliTPCcalibTracks *calibTracks =  new AliTPCcalibTracks("calibTracks", "Resolution calibration object for tracks", clusterParam, cuts);
  calibTracks->SetDebugLevel(debugLevel);
  calibTracks->SetStreamLevel(streamLevel);
  calibTracks->SetTriggerMask(-1,-1,kTRUE);
  myTask->AddJob(calibTracks);
}

//_____________________________________________________________________________
void SetupCalibTaskTrain1(TObject* task){
  //
  // Setup tasks for calibration train
  //
  AddCalibCalib(task);
  AddCalibTimeGain(task);
  AddCalibTime(task);
  //AddCalibTracks(task);
}

//_____________________________________________________________________________
void ConfigOCDB(Int_t run){
  //
  // Configure TPC OCDB
  //
  printf("SETUP OCBD for TPC\n");
  printf("SETUP OCBD for TPC\n");
  printf("SETUP OCBD for TPC Run =%d\n", run);
  //
  //
  AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();
  param->ReadGeoMatrices();
  //
  AliMagF* magF= TGeoGlobalMagField::Instance()->GetField();
  printf("\n\nSET EXB FIELD\t\n\n");
  AliTPCcalibDB::Instance()->SetExBField(magF);
  //
  //
  //
  AliTPCTransform *transform     = AliTPCcalibDB::Instance()->GetTransform() ;
  //
  //AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);
  //
  AliCDBEntry* entry = AliCDBManager::Instance()->Get("TPC/Calib/RecoParam");
  if (!entry){
    printf("TPC reco param not available");
  }
  TObjArray * array = (TObjArray*)entry->GetObject();
  if (!array){
    printf("TPC reco param not available");
  }
  // 0 - Low Flux (pp), 1- High Flux (Pb-Pb)
  AliTPCRecoParam * tpcRecoParam = (AliTPCRecoParam*)array->At(1);

  transform->SetCurrentRecoParam(tpcRecoParam);
  tpcRecoParam->SetUseGainCorrectionTime(0);
  tpcRecoParam->SetUseRPHICorrection(kFALSE);
  tpcRecoParam->SetUseTOFCorrection(kFALSE);
  //
  tpcRecoParam->SetUseDriftCorrectionTime(0);
  tpcRecoParam->SetUseDriftCorrectionGY(0);
  //
  tpcRecoParam->SetUseRadialCorrection(kFALSE);
  tpcRecoParam->SetUseQuadrantAlignment(kFALSE);
  //
  tpcRecoParam->SetUseSectorAlignment(kFALSE);
  tpcRecoParam->SetUseFieldCorrection(kFALSE);
  tpcRecoParam->SetUseExBCorrection(kFALSE);
  //
  tpcRecoParam->SetUseMultiplicityCorrectionDedx(kFALSE);
  tpcRecoParam->SetUseAlignmentTime(kFALSE);
  tpcRecoParam->SetUseComposedCorrection(kTRUE);

  AliTPCcalibDB::Instance()->SetRun(run);
}
<commit_msg>Adding the new type of the TPC calibration AliTPCcalibAlign AliTPCcalibLaser AliTPCcalibTracks Output stored in 2 directoris  - TPCAlign and TPCCluster within the AliESDfriends_v1.root<commit_after>/*

 This macros setup the TPC calibration task AddTaskTPCCalib
 for CPass1.
 - the run number is required to config TPC OCDB

 The following calibration components are added to the AliTPCAnalysisTaskcalib task:
 1. AliTPCcalibCalib - redo reconstruction with current calibration
 2. AliTPCcalibTimeGain - TPC time dependent gain calibration
 3. AliTPCcalibTime - TPC time dependent drift time calibration

*/

// function to set TPC OCDB parameters
void ConfigOCDB(Int_t crun);

Int_t debugLevel=0;
Int_t streamLevel=0;

//_____________________________________________________________________________
AliAnalysisTask  *AddTaskTPCCalib(Int_t runNumber)
{
  //
  // add calibration task
  //
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskTPCCalib", "No analysis manager to connect to.");
    return NULL;
  }

  // check the input handler
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskTPCCalib", "This task requires an input event handler");
    return NULL;
  }

  // set TPC OCDB parameters
  ConfigOCDB(runNumber);

  // setup task
  AliTPCAnalysisTaskcalib *task1=new AliTPCAnalysisTaskcalib("CalibObjectsTrain1");
  SetupCalibTaskTrain1(task1);
  mgr->AddTask(task1);

  AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
  if (!cinput1) cinput1 = mgr->CreateContainer("cchain",TChain::Class(),
                                      AliAnalysisManager::kInputContainer);
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("TPCCalib",TObjArray::Class(), AliAnalysisManager::kOutputContainer, "AliESDfriends_v1.root");

  mgr->ConnectInput(task1,0,cinput1);
  mgr->ConnectOutput(task1,0,coutput1);

  AliTPCAnalysisTaskcalib *taskAlign=new AliTPCAnalysisTaskcalib("CalibObjectsTrain1");
  SetupCalibTaskTrainAlign(taskAlign);
  mgr->AddTask(taskAlign);

  AliAnalysisDataContainer *cinputAlign = mgr->GetCommonInputContainer();
  if (!cinputAlign) cinputAlign = mgr->CreateContainer("cchain",TChain::Class(),
                                      AliAnalysisManager::kInputContainer);
  AliAnalysisDataContainer *coutputAlign = mgr->CreateContainer("TPCAlign",TObjArray::Class(), AliAnalysisManager::kOutputContainer, "AliESDfriends_v1.root");

  mgr->ConnectInput(taskAlign,0,cinputAlign);
  mgr->ConnectOutput(taskAlign,0,coutputAlign);

  AliTPCAnalysisTaskcalib *taskCluster=new AliTPCAnalysisTaskcalib("CalibObjectsTrain1");
  SetupCalibTaskTrainCluster(taskCluster);
  mgr->AddTask(taskCluster);
  AliAnalysisDataContainer *coutputAlign = mgr->CreateContainer("TPCCluster",TObjArray::Class(), AliAnalysisManager::kOutputContainer, "AliESDfriends_v1.root");
  mgr->ConnectInput(taskCluster,0,cinput1);
  mgr->ConnectOutput(taskCluster,0,coutputAlign);

  return task1;
}

//_____________________________________________________________________________
void AddCalibCalib(TObject* task){
  //
  // Responsible: Marian Ivanov
  // Description:
  // calibCalib is a prefilter
  // The current OCDB entries transformation are applied on cluster, tracks are refitted
  //
  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;
  AliTPCcalibCalib *calibCalib = new AliTPCcalibCalib("calibTPC","calibTPC");
  calibCalib->SetDebugLevel(0);
  calibCalib->SetStreamLevel(0);
  calibCalib->SetTriggerMask(-1,-1,kFALSE);        //accept everything
  myTask->AddJob(calibCalib);
}

//_____________________________________________________________________________
void AddCalibTimeGain(TObject* task, Bool_t isCosmic = kFALSE, char * name = "calibTimeGain"){
  //
  //  Responsible: Alexander Kalweit
  //  Description: Time Gain calibration
  //

  // Set run time ranges (time stamps)
  AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
  if(!entry) {
    ::Error("AddCalibTimeGain","Cannot get AliCDBEntry");
    return;
  }
  const AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());
  if(!grpData) {
    ::Error("AddCalibTimeGain","Cannot get AliGRPObject");
    return;
  }
  time_t sTime = grpData->GetTimeStart();
  time_t eTime = grpData->GetTimeEnd();
  TTimeStamp startRunTime(sTime);
  TTimeStamp stopRunTime(eTime);

  UInt_t year;
  startRunTime.GetDate(kTRUE,0,&year);
  TTimeStamp startTime(year,1,1,0,0,0);
  TTimeStamp stopTime(year,12,31,23,59,59);

  //
  // setup calibration component
  //

  Bool_t useQmax = (grpData->GetBeamType()).Contains("Pb-Pb");

  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;
  AliTPCcalibTimeGain *calibTimeGain = new AliTPCcalibTimeGain(name,"calibTimeGain", startTime.GetSec(), stopTime.GetSec(), 10*60);
  calibTimeGain->SetIsCosmic(isCosmic);
  calibTimeGain->SetUseCookAnalytical(kTRUE);
  calibTimeGain->SetUseMax(useQmax);
  calibTimeGain->SetDebugLevel(0);
  calibTimeGain->SetStreamLevel(0);
  calibTimeGain->SetTriggerMask(-1,-1,kTRUE);        //reject laser
  calibTimeGain->SetLowerTrunc(0.02);
  calibTimeGain->SetUpperTrunc(0.6);

  myTask->AddJob(calibTimeGain);

  AliTPCcalibGainMult *calibGainMult = new AliTPCcalibGainMult("calibGainMult","calibGainMult");
  calibGainMult->SetUseMax(useQmax);
  calibGainMult->SetDebugLevel(0);
  calibGainMult->SetStreamLevel(0);
  calibGainMult->SetTriggerMask(-1,-1,kTRUE);        //reject laser
  calibGainMult->SetLowerTrunc(0.02);
  calibGainMult->SetUpperTrunc(0.6);

  myTask->AddJob(calibGainMult);

}

//_____________________________________________________________________________
void AddCalibTime(TObject* task){
  //
  // Responsible: Dag Larsen
  // Description: Time V drift calibration
  //

  // Set run time ranges (time stamps)
  AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
  if(!entry) {
    ::Error("AddCalibTime","Cannot get AliCDBEntry");
    return;
  }
  const AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject());
  if(!grpData) {
    ::Error("AddCalibTime","Cannot get AliGRPObject");
    return;
  }
  time_t sTime = grpData->GetTimeStart();
  time_t eTime = grpData->GetTimeEnd();

  TTimeStamp startRunTime(sTime);
  TTimeStamp stopRunTime(eTime);

  UInt_t year;
  startRunTime.GetDate(kTRUE,0,&year);
  TTimeStamp startTime(year,1,1,0,0,0);
  TTimeStamp stopTime(year,12,31,23,59,59);

  //
  // setup calibration component
  //
  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;
  AliTPCcalibTime *calibTime = new AliTPCcalibTime("calibTime","calibTime",  startTime.GetSec(), stopTime.GetSec(), 10*60, 2);
  calibTime->SetDebugLevel(0);
  calibTime->SetStreamLevel(0);
  calibTime->SetTriggerMask(-1,-1,kFALSE);        //accept everything

  // max 5000 tracks per event
  calibTime->SetCutTracks(5000);

  myTask->AddJob(calibTime);
}

void AddCalibTracks(TObject* task){
  //
  // Responsible: Marian Ivanov
  // Description:
  // Histogram residuals and pulls of the track parameters in bins of track parameters
  //
  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;
  AliTPCClusterParam * clusterParam = AliTPCcalibDB::Instance()->GetClusterParam();

   AliTPCcalibTracksCuts *cuts = new AliTPCcalibTracksCuts(30, 0.4, 5, 0.13, 0.018);
  //
  AliTPCcalibTracks *calibTracks =  new AliTPCcalibTracks("calibTracks", "Resolution calibration object for tracks", clusterParam, cuts);
  calibTracks->SetDebugLevel(debugLevel);
  calibTracks->SetStreamLevel(streamLevel);
  calibTracks->SetTriggerMask(-1,-1,kTRUE);
  myTask->AddJob(calibTracks);
}

void AddCalibAlign(TObject* task){
  //
  // Responsible: Marian Ivanov
  // Description:
  //
  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;
  AliTPCcalibAlign *calibAlign = new AliTPCcalibAlign("alignTPC","Alignment of the TPC sectors");
  calibAlign->SetDebugLevel(debugLevel);
  calibAlign->SetStreamLevel(streamLevel);
  calibAlign->SetTriggerMask(-1,-1,kTRUE);        //accept everything
  myTask->AddJob(calibAlign);
}

void AddCalibLaser(TObject* task){
  //
  // Responsible: Marian Ivanov
  // Description:
  //
  AliTPCAnalysisTaskcalib* myTask = (AliTPCAnalysisTaskcalib*) task;
  AliTPCcalibLaser *calibLaser = new AliTPCcalibLaser("laserTPC","laserTPC");
  calibLaser->SetDebugLevel(debugLevel);
  calibLaser->SetStreamLevel(streamLevel);
  calibLaser->SetTriggerMask(-1,-1,kFALSE);        //accept everything
  myTask->AddJob(calibLaser);
}

//_____________________________________________________________________________
void SetupCalibTaskTrain1(TObject* task){
  //
  // Setup tasks for calibration train
  //
  // AddCalibCalib(task); - disable refitting
  AddCalibTimeGain(task);
  AddCalibTime(task);
}

void SetupCalibTaskTrainAlign(TObject* task){
  //
  // Setup tasks for calibration train
  //
  AddCalibAlign(task);
  AddCalibLaser(task);
}

void SetupCalibTaskTrainCluster(TObject* task){
  //
  // Setup tasks for calibration train
  //
  AddCalibTracks(task);
}

//_____________________________________________________________________________
void ConfigOCDB(Int_t run){
  //
  // Configure TPC OCDB
  //
  printf("SETUP OCBD for TPC\n");
  printf("SETUP OCBD for TPC\n");
  printf("SETUP OCBD for TPC Run =%d\n", run);
  //
  //
  AliTPCParam *param= AliTPCcalibDB::Instance()->GetParameters();
  param->ReadGeoMatrices();
  //
  AliMagF* magF= TGeoGlobalMagField::Instance()->GetField();
  printf("\n\nSET EXB FIELD\t\n\n");
  AliTPCcalibDB::Instance()->SetExBField(magF);
  //
  //
  //
  AliTPCTransform *transform     = AliTPCcalibDB::Instance()->GetTransform() ;
  //
  //AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);
  //
  AliCDBEntry* entry = AliCDBManager::Instance()->Get("TPC/Calib/RecoParam");
  if (!entry){
    printf("TPC reco param not available");
  }
  TObjArray * array = (TObjArray*)entry->GetObject();
  if (!array){
    printf("TPC reco param not available");
  }
  // 0 - Low Flux (pp), 1- High Flux (Pb-Pb)
  AliTPCRecoParam * tpcRecoParam = (AliTPCRecoParam*)array->At(1);

  transform->SetCurrentRecoParam(tpcRecoParam);
  // in CPass1 use a default setting
//   tpcRecoParam->SetUseGainCorrectionTime(0);
//   tpcRecoParam->SetUseRPHICorrection(kFALSE);
//   tpcRecoParam->SetUseTOFCorrection(kFALSE);
//   //
//   tpcRecoParam->SetUseDriftCorrectionTime(0);
//   tpcRecoParam->SetUseDriftCorrectionGY(0);
//   //
//   tpcRecoParam->SetUseRadialCorrection(kFALSE);
//   tpcRecoParam->SetUseQuadrantAlignment(kFALSE);
//   //
//   tpcRecoParam->SetUseSectorAlignment(kFALSE);
//   tpcRecoParam->SetUseFieldCorrection(kFALSE);
//   tpcRecoParam->SetUseExBCorrection(kFALSE);
//   //
//   tpcRecoParam->SetUseMultiplicityCorrectionDedx(kFALSE);
//   tpcRecoParam->SetUseAlignmentTime(kFALSE);
//   tpcRecoParam->SetUseComposedCorrection(kTRUE);

  AliTPCcalibDB::Instance()->SetRun(run);
}
<|endoftext|>


<commit_before>#include "Commands/CDirectiveData.h"

#include "Archs/Architecture.h"
#include "Core/Common.h"
#include "Core/FileManager.h"
#include "Core/Misc.h"
#include "Core/SymbolData.h"
#include "Util/FileSystem.h"
#include "Util/Util.h"

//
// TableCommand
//

TableCommand::TableCommand(const fs::path& fileName, TextFile::Encoding encoding)
{
	auto fullName = getFullPathName(fileName);

	if (!fs::exists(fullName))
	{
		Logger::printError(Logger::Error, "Table file \"%s\" does not exist", fileName.u8string());
		return;
	}

	if (!table.load(fullName,encoding))
	{
		Logger::printError(Logger::Error, "Invalid table file \"%s\"",fileName.u8string());
		return;
	}
}

bool TableCommand::Validate(const ValidateState &state)
{
	Global.Table = table;
	return false;
}

//
// CDirectiveData
//

CDirectiveData::CDirectiveData()
{
	mode = EncodingMode::Invalid;
	writeTermination = false;
	endianness = Architecture::current().getEndianness();
}

CDirectiveData::~CDirectiveData()
{

}

void CDirectiveData::setNormal(std::vector<Expression>& entries, size_t unitSize)
{
	switch (unitSize)
	{
	case 1:
		this->mode = EncodingMode::U8;
		break;
	case 2:
		this->mode = EncodingMode::U16;
		break;
	case 4:
		this->mode = EncodingMode::U32;
		break;
	case 8:
		this->mode = EncodingMode::U64;
		break;
	default:
		Logger::printError(Logger::Error, "Invalid data unit size %d",unitSize);
		return;
	}

	this->entries = entries;
	this->writeTermination = false;
	normalData.reserve(entries.size());
}

void CDirectiveData::setFloat(std::vector<Expression>& entries)
{
	this->mode = EncodingMode::Float;
	this->entries = entries;
	this->writeTermination = false;
}

void CDirectiveData::setDouble(std::vector<Expression>& entries)
{
	this->mode = EncodingMode::Double;
	this->entries = entries;
	this->writeTermination = false;
}

void CDirectiveData::setAscii(std::vector<Expression>& entries, bool terminate)
{
	this->mode = EncodingMode::Ascii;
	this->entries = entries;
	this->writeTermination = terminate;
}

void CDirectiveData::setSjis(std::vector<Expression>& entries, bool terminate)
{
	this->mode = EncodingMode::Sjis;
	this->entries = entries;
	this->writeTermination = terminate;
}

void CDirectiveData::setCustom(std::vector<Expression>& entries, bool terminate)
{
	this->mode = EncodingMode::Custom;
	this->entries = entries;
	this->writeTermination = terminate;
}

size_t CDirectiveData::getUnitSize() const
{
	switch (mode)
	{
	case EncodingMode::U8:
	case EncodingMode::Ascii:
	case EncodingMode::Sjis:
	case EncodingMode::Custom:
		return 1;
	case EncodingMode::U16:
		return 2;
	case EncodingMode::U32:
	case EncodingMode::Float:
		return 4;
	case EncodingMode::U64:
	case EncodingMode::Double:
		return 8;
	case EncodingMode::Invalid:
		break;
	}

	return 0;
}

size_t CDirectiveData::getDataSize() const
{
	switch (mode)
	{
	case EncodingMode::Sjis:
	case EncodingMode::Custom:
		return customData.size();
	case EncodingMode::U8:
	case EncodingMode::Ascii:
	case EncodingMode::U16:
	case EncodingMode::U32:
	case EncodingMode::U64:
	case EncodingMode::Float:
	case EncodingMode::Double:
		return normalData.size()*getUnitSize();
	case EncodingMode::Invalid:
		break;
	}

	return 0;
}

void CDirectiveData::encodeCustom(EncodingTable& table)
{
	customData.clear();
	for (size_t i = 0; i < entries.size(); i++)
	{
		ExpressionValue value = entries[i].evaluate();
		if (!value.isValid())
		{
			Logger::queueError(Logger::Error, "Invalid expression");
			continue;
		}

		if (value.isInt())
		{
			customData.appendByte((byte)value.intValue);
		} else if (value.isString())
		{
			ByteArray encoded = table.encodeString(value.strValue.string(),false);
			if (encoded.size() == 0 && value.strValue.size() > 0)
			{
				Logger::queueError(Logger::Error, "Failed to encode \"%s\"",value.strValue);
			}
			customData.append(encoded);
		} else {
			Logger::queueError(Logger::Error, "Invalid expression type");
		}
	}

	if (writeTermination)
	{
		ByteArray encoded = table.encodeTermination();
		customData.append(encoded);
	}
}

void CDirectiveData::encodeSjis()
{
	static EncodingTable sjisTable;
	if (!sjisTable.isLoaded())
	{
		unsigned char hexBuffer[2];

		sjisTable.setTerminationEntry((unsigned char*)"\0",1);

		for (unsigned short SJISValue = 0x0001; SJISValue < 0x0100; SJISValue++)
		{
			if (auto unicodeValue = sjisToUnicode(SJISValue))
			{
				hexBuffer[0] = SJISValue & 0xFF;
				sjisTable.addEntry(hexBuffer, 1, convertUnicodeCharToUtf8(unicodeValue.value()));
			}
		}
		for (unsigned short SJISValue = 0x8100; SJISValue < 0xEF00; SJISValue++)
		{
			if (auto unicodeValue = sjisToUnicode(SJISValue))
			{
				hexBuffer[0] = (SJISValue >> 8) & 0xFF;
				hexBuffer[1] = SJISValue & 0xFF;
				sjisTable.addEntry(hexBuffer, 2, convertUnicodeCharToUtf8(unicodeValue.value()));
			}
		}
	}

	encodeCustom(sjisTable);
}

void CDirectiveData::encodeFloat()
{
	normalData.clear();
	for (size_t i = 0; i < entries.size(); i++)
	{
		ExpressionValue value = entries[i].evaluate();
		if (!value.isValid())
		{
			Logger::queueError(Logger::Error, "Invalid expression");
			continue;
		}

		if (value.isInt() && mode == EncodingMode::Float)
		{
			int32_t num = getFloatBits((float)value.intValue);
			normalData.push_back(num);
		} else if (value.isInt() && mode == EncodingMode::Double)
		{
			int64_t num = getDoubleBits((double)value.intValue);
			normalData.push_back(num);
		} else if (value.isFloat() && mode == EncodingMode::Float)
		{
			int32_t num = getFloatBits((float)value.floatValue);
			normalData.push_back(num);
		} else if (value.isFloat() && mode == EncodingMode::Double)
		{
			int64_t num = getDoubleBits((double)value.floatValue);
			normalData.push_back(num);
		} else {
			Logger::queueError(Logger::Error, "Invalid expression type");
		}
	}
}

void CDirectiveData::encodeNormal()
{
	normalData.clear();
	for (size_t i = 0; i < entries.size(); i++)
	{
		ExpressionValue value = entries[i].evaluate();
		if (!value.isValid())
		{
			Logger::queueError(Logger::Error, "Invalid expression");
			continue;
		}

		if (value.isString())
		{
			bool hadNonAscii = false;
			for (size_t l = 0; l < value.strValue.size(); l++)
			{
				uint64_t num = value.strValue.string()[l];
				normalData.push_back(num);

				if (num >= 0x80 && !hadNonAscii)
				{
					Logger::queueError(Logger::Error, "Non-ASCII character in data directive. Use .string instead");
					hadNonAscii = true;
				}
			}
		} else if (value.isInt())
		{
			int64_t num = value.intValue;
			normalData.push_back(num);
		} else if (value.isFloat() && mode == EncodingMode::U32)
		{
			int32_t num = getFloatBits((float)value.floatValue);
			normalData.push_back(num);
		} else if(value.isFloat() && mode == EncodingMode::U64) {
			int64_t num = getDoubleBits((double)value.floatValue);
			normalData.push_back(num);
		} else {
			Logger::queueError(Logger::Error, "Invalid expression type");
		}
	}

	if (writeTermination)
	{
		normalData.push_back(0);
	}
}

bool CDirectiveData::Validate(const ValidateState &state)
{
	position = g_fileManager->getVirtualAddress();

	size_t oldSize = getDataSize();
	switch (mode)
	{
	case EncodingMode::U8:
	case EncodingMode::U16:
	case EncodingMode::U32:
	case EncodingMode::U64:
	case EncodingMode::Ascii:
		encodeNormal();
		break;
	case EncodingMode::Float:
	case EncodingMode::Double:
		encodeFloat();
		break;
	case EncodingMode::Sjis:
		encodeSjis();
		break;
	case EncodingMode::Custom:
		encodeCustom(Global.Table);
		break;
	default:
		Logger::queueError(Logger::Error, "Invalid encoding type");
		break;
	}

	g_fileManager->advanceMemory(getDataSize());
	return oldSize != getDataSize();
}

void CDirectiveData::Encode() const
{
	switch (mode)
	{
	case EncodingMode::Sjis:
	case EncodingMode::Custom:
		g_fileManager->write(customData.data(),customData.size());
		break;
	case EncodingMode::U8:
	case EncodingMode::Ascii:
		for (auto value: normalData)
		{
			g_fileManager->writeU8((uint8_t)value);
		}
		break;
	case EncodingMode::U16:
		for (auto value: normalData)
		{
			g_fileManager->writeU16((uint16_t)value);
		}
		break;
	case EncodingMode::U32:
	case EncodingMode::Float:
		for (auto value: normalData)
		{
			g_fileManager->writeU32((uint32_t)value);
		}
		break;
	case EncodingMode::U64:
	case EncodingMode::Double:
		for (auto value: normalData)
		{
			g_fileManager->writeU64((uint64_t)value);
		}
		break;
	case EncodingMode::Invalid:
		// TODO: Assert?
		break;
	}
}

void CDirectiveData::writeTempData(TempData& tempData) const
{
	size_t size = (getUnitSize()*2+3)*getDataSize()+20;
	char* str = new char[size];
	char* start = str;

	switch (mode)
	{
	case EncodingMode::Sjis:
	case EncodingMode::Custom:
		str += snprintf(str,20,".byte ");

		for (size_t i = 0; i < customData.size(); i++)
		{
			str += snprintf(str,20,"0x%02X,",(uint8_t)customData[i]);
		}
		break;
	case EncodingMode::U8:
	case EncodingMode::Ascii:
		str += snprintf(str,20,".byte ");

		for (size_t i = 0; i < normalData.size(); i++)
		{
			str += snprintf(str,20,"0x%02X,",(uint8_t)normalData[i]);
		}
		break;
	case EncodingMode::U16:
		str += snprintf(str,20,".halfword ");

		for (size_t i = 0; i < normalData.size(); i++)
		{
			str += snprintf(str,20,"0x%04X,",(uint16_t)normalData[i]);
		}
		break;
	case EncodingMode::U32:
	case EncodingMode::Float:
		str += snprintf(str,20, ".word ");

		for (size_t i = 0; i < normalData.size(); i++)
		{
			str += snprintf(str,20,"0x%08X,",(uint32_t)normalData[i]);
		}
		break;
	case EncodingMode::U64:
	case EncodingMode::Double:
		str += snprintf(str,20,".doubleword ");

		for (size_t i = 0; i < normalData.size(); i++)
		{
			str += snprintf(str,20,"0x%16llX,",(uint64_t)normalData[i]);
		}
		break;
	case EncodingMode::Invalid:
		// TODO: Assert?
		break;
	}

	*(str-1) = 0;
	tempData.writeLine(position,start);
	delete[] start;
}

void CDirectiveData::writeSymData(SymbolData& symData) const
{
	switch (mode)
	{
	case EncodingMode::Ascii:
		symData.addData(position,getDataSize(),SymbolData::DataAscii);
		break;
	case EncodingMode::U8:
	case EncodingMode::Sjis:
	case EncodingMode::Custom:
		symData.addData(position,getDataSize(),SymbolData::Data8);
		break;
	case EncodingMode::U16:
		symData.addData(position,getDataSize(),SymbolData::Data16);
		break;
	case EncodingMode::U32:
	case EncodingMode::Float:
		symData.addData(position,getDataSize(),SymbolData::Data32);
		break;
	case EncodingMode::U64:
	case EncodingMode::Double:
		symData.addData(position,getDataSize(),SymbolData::Data64);
		break;
	case EncodingMode::Invalid:
		// TODO: Assert?
		break;
	}
}
<commit_msg>Resolve a type format warning.<commit_after>#include "Commands/CDirectiveData.h"

#include <cinttypes>
#include "Archs/Architecture.h"
#include "Core/Common.h"
#include "Core/FileManager.h"
#include "Core/Misc.h"
#include "Core/SymbolData.h"
#include "Util/FileSystem.h"
#include "Util/Util.h"

//
// TableCommand
//

TableCommand::TableCommand(const fs::path& fileName, TextFile::Encoding encoding)
{
	auto fullName = getFullPathName(fileName);

	if (!fs::exists(fullName))
	{
		Logger::printError(Logger::Error, "Table file \"%s\" does not exist", fileName.u8string());
		return;
	}

	if (!table.load(fullName,encoding))
	{
		Logger::printError(Logger::Error, "Invalid table file \"%s\"",fileName.u8string());
		return;
	}
}

bool TableCommand::Validate(const ValidateState &state)
{
	Global.Table = table;
	return false;
}

//
// CDirectiveData
//

CDirectiveData::CDirectiveData()
{
	mode = EncodingMode::Invalid;
	writeTermination = false;
	endianness = Architecture::current().getEndianness();
}

CDirectiveData::~CDirectiveData()
{

}

void CDirectiveData::setNormal(std::vector<Expression>& entries, size_t unitSize)
{
	switch (unitSize)
	{
	case 1:
		this->mode = EncodingMode::U8;
		break;
	case 2:
		this->mode = EncodingMode::U16;
		break;
	case 4:
		this->mode = EncodingMode::U32;
		break;
	case 8:
		this->mode = EncodingMode::U64;
		break;
	default:
		Logger::printError(Logger::Error, "Invalid data unit size %d",unitSize);
		return;
	}

	this->entries = entries;
	this->writeTermination = false;
	normalData.reserve(entries.size());
}

void CDirectiveData::setFloat(std::vector<Expression>& entries)
{
	this->mode = EncodingMode::Float;
	this->entries = entries;
	this->writeTermination = false;
}

void CDirectiveData::setDouble(std::vector<Expression>& entries)
{
	this->mode = EncodingMode::Double;
	this->entries = entries;
	this->writeTermination = false;
}

void CDirectiveData::setAscii(std::vector<Expression>& entries, bool terminate)
{
	this->mode = EncodingMode::Ascii;
	this->entries = entries;
	this->writeTermination = terminate;
}

void CDirectiveData::setSjis(std::vector<Expression>& entries, bool terminate)
{
	this->mode = EncodingMode::Sjis;
	this->entries = entries;
	this->writeTermination = terminate;
}

void CDirectiveData::setCustom(std::vector<Expression>& entries, bool terminate)
{
	this->mode = EncodingMode::Custom;
	this->entries = entries;
	this->writeTermination = terminate;
}

size_t CDirectiveData::getUnitSize() const
{
	switch (mode)
	{
	case EncodingMode::U8:
	case EncodingMode::Ascii:
	case EncodingMode::Sjis:
	case EncodingMode::Custom:
		return 1;
	case EncodingMode::U16:
		return 2;
	case EncodingMode::U32:
	case EncodingMode::Float:
		return 4;
	case EncodingMode::U64:
	case EncodingMode::Double:
		return 8;
	case EncodingMode::Invalid:
		break;
	}

	return 0;
}

size_t CDirectiveData::getDataSize() const
{
	switch (mode)
	{
	case EncodingMode::Sjis:
	case EncodingMode::Custom:
		return customData.size();
	case EncodingMode::U8:
	case EncodingMode::Ascii:
	case EncodingMode::U16:
	case EncodingMode::U32:
	case EncodingMode::U64:
	case EncodingMode::Float:
	case EncodingMode::Double:
		return normalData.size()*getUnitSize();
	case EncodingMode::Invalid:
		break;
	}

	return 0;
}

void CDirectiveData::encodeCustom(EncodingTable& table)
{
	customData.clear();
	for (size_t i = 0; i < entries.size(); i++)
	{
		ExpressionValue value = entries[i].evaluate();
		if (!value.isValid())
		{
			Logger::queueError(Logger::Error, "Invalid expression");
			continue;
		}

		if (value.isInt())
		{
			customData.appendByte((byte)value.intValue);
		} else if (value.isString())
		{
			ByteArray encoded = table.encodeString(value.strValue.string(),false);
			if (encoded.size() == 0 && value.strValue.size() > 0)
			{
				Logger::queueError(Logger::Error, "Failed to encode \"%s\"",value.strValue);
			}
			customData.append(encoded);
		} else {
			Logger::queueError(Logger::Error, "Invalid expression type");
		}
	}

	if (writeTermination)
	{
		ByteArray encoded = table.encodeTermination();
		customData.append(encoded);
	}
}

void CDirectiveData::encodeSjis()
{
	static EncodingTable sjisTable;
	if (!sjisTable.isLoaded())
	{
		unsigned char hexBuffer[2];

		sjisTable.setTerminationEntry((unsigned char*)"\0",1);

		for (unsigned short SJISValue = 0x0001; SJISValue < 0x0100; SJISValue++)
		{
			if (auto unicodeValue = sjisToUnicode(SJISValue))
			{
				hexBuffer[0] = SJISValue & 0xFF;
				sjisTable.addEntry(hexBuffer, 1, convertUnicodeCharToUtf8(unicodeValue.value()));
			}
		}
		for (unsigned short SJISValue = 0x8100; SJISValue < 0xEF00; SJISValue++)
		{
			if (auto unicodeValue = sjisToUnicode(SJISValue))
			{
				hexBuffer[0] = (SJISValue >> 8) & 0xFF;
				hexBuffer[1] = SJISValue & 0xFF;
				sjisTable.addEntry(hexBuffer, 2, convertUnicodeCharToUtf8(unicodeValue.value()));
			}
		}
	}

	encodeCustom(sjisTable);
}

void CDirectiveData::encodeFloat()
{
	normalData.clear();
	for (size_t i = 0; i < entries.size(); i++)
	{
		ExpressionValue value = entries[i].evaluate();
		if (!value.isValid())
		{
			Logger::queueError(Logger::Error, "Invalid expression");
			continue;
		}

		if (value.isInt() && mode == EncodingMode::Float)
		{
			int32_t num = getFloatBits((float)value.intValue);
			normalData.push_back(num);
		} else if (value.isInt() && mode == EncodingMode::Double)
		{
			int64_t num = getDoubleBits((double)value.intValue);
			normalData.push_back(num);
		} else if (value.isFloat() && mode == EncodingMode::Float)
		{
			int32_t num = getFloatBits((float)value.floatValue);
			normalData.push_back(num);
		} else if (value.isFloat() && mode == EncodingMode::Double)
		{
			int64_t num = getDoubleBits((double)value.floatValue);
			normalData.push_back(num);
		} else {
			Logger::queueError(Logger::Error, "Invalid expression type");
		}
	}
}

void CDirectiveData::encodeNormal()
{
	normalData.clear();
	for (size_t i = 0; i < entries.size(); i++)
	{
		ExpressionValue value = entries[i].evaluate();
		if (!value.isValid())
		{
			Logger::queueError(Logger::Error, "Invalid expression");
			continue;
		}

		if (value.isString())
		{
			bool hadNonAscii = false;
			for (size_t l = 0; l < value.strValue.size(); l++)
			{
				uint64_t num = value.strValue.string()[l];
				normalData.push_back(num);

				if (num >= 0x80 && !hadNonAscii)
				{
					Logger::queueError(Logger::Error, "Non-ASCII character in data directive. Use .string instead");
					hadNonAscii = true;
				}
			}
		} else if (value.isInt())
		{
			int64_t num = value.intValue;
			normalData.push_back(num);
		} else if (value.isFloat() && mode == EncodingMode::U32)
		{
			int32_t num = getFloatBits((float)value.floatValue);
			normalData.push_back(num);
		} else if(value.isFloat() && mode == EncodingMode::U64) {
			int64_t num = getDoubleBits((double)value.floatValue);
			normalData.push_back(num);
		} else {
			Logger::queueError(Logger::Error, "Invalid expression type");
		}
	}

	if (writeTermination)
	{
		normalData.push_back(0);
	}
}

bool CDirectiveData::Validate(const ValidateState &state)
{
	position = g_fileManager->getVirtualAddress();

	size_t oldSize = getDataSize();
	switch (mode)
	{
	case EncodingMode::U8:
	case EncodingMode::U16:
	case EncodingMode::U32:
	case EncodingMode::U64:
	case EncodingMode::Ascii:
		encodeNormal();
		break;
	case EncodingMode::Float:
	case EncodingMode::Double:
		encodeFloat();
		break;
	case EncodingMode::Sjis:
		encodeSjis();
		break;
	case EncodingMode::Custom:
		encodeCustom(Global.Table);
		break;
	default:
		Logger::queueError(Logger::Error, "Invalid encoding type");
		break;
	}

	g_fileManager->advanceMemory(getDataSize());
	return oldSize != getDataSize();
}

void CDirectiveData::Encode() const
{
	switch (mode)
	{
	case EncodingMode::Sjis:
	case EncodingMode::Custom:
		g_fileManager->write(customData.data(),customData.size());
		break;
	case EncodingMode::U8:
	case EncodingMode::Ascii:
		for (auto value: normalData)
		{
			g_fileManager->writeU8((uint8_t)value);
		}
		break;
	case EncodingMode::U16:
		for (auto value: normalData)
		{
			g_fileManager->writeU16((uint16_t)value);
		}
		break;
	case EncodingMode::U32:
	case EncodingMode::Float:
		for (auto value: normalData)
		{
			g_fileManager->writeU32((uint32_t)value);
		}
		break;
	case EncodingMode::U64:
	case EncodingMode::Double:
		for (auto value: normalData)
		{
			g_fileManager->writeU64((uint64_t)value);
		}
		break;
	case EncodingMode::Invalid:
		// TODO: Assert?
		break;
	}
}

void CDirectiveData::writeTempData(TempData& tempData) const
{
	size_t size = (getUnitSize()*2+3)*getDataSize()+20;
	char* str = new char[size];
	char* start = str;

	switch (mode)
	{
	case EncodingMode::Sjis:
	case EncodingMode::Custom:
		str += snprintf(str,20,".byte ");

		for (size_t i = 0; i < customData.size(); i++)
		{
			str += snprintf(str,20,"0x%02X,",(uint8_t)customData[i]);
		}
		break;
	case EncodingMode::U8:
	case EncodingMode::Ascii:
		str += snprintf(str,20,".byte ");

		for (size_t i = 0; i < normalData.size(); i++)
		{
			str += snprintf(str,20,"0x%02X,",(uint8_t)normalData[i]);
		}
		break;
	case EncodingMode::U16:
		str += snprintf(str,20,".halfword ");

		for (size_t i = 0; i < normalData.size(); i++)
		{
			str += snprintf(str,20,"0x%04X,",(uint16_t)normalData[i]);
		}
		break;
	case EncodingMode::U32:
	case EncodingMode::Float:
		str += snprintf(str,20, ".word ");

		for (size_t i = 0; i < normalData.size(); i++)
		{
			str += snprintf(str,20,"0x%08X,",(uint32_t)normalData[i]);
		}
		break;
	case EncodingMode::U64:
	case EncodingMode::Double:
		str += snprintf(str,20,".doubleword ");

		for (size_t i = 0; i < normalData.size(); i++)
		{
			str += snprintf(str,20,"0x%16" PRIx64 ",",(uint64_t)normalData[i]);
		}
		break;
	case EncodingMode::Invalid:
		// TODO: Assert?
		break;
	}

	*(str-1) = 0;
	tempData.writeLine(position,start);
	delete[] start;
}

void CDirectiveData::writeSymData(SymbolData& symData) const
{
	switch (mode)
	{
	case EncodingMode::Ascii:
		symData.addData(position,getDataSize(),SymbolData::DataAscii);
		break;
	case EncodingMode::U8:
	case EncodingMode::Sjis:
	case EncodingMode::Custom:
		symData.addData(position,getDataSize(),SymbolData::Data8);
		break;
	case EncodingMode::U16:
		symData.addData(position,getDataSize(),SymbolData::Data16);
		break;
	case EncodingMode::U32:
	case EncodingMode::Float:
		symData.addData(position,getDataSize(),SymbolData::Data32);
		break;
	case EncodingMode::U64:
	case EncodingMode::Double:
		symData.addData(position,getDataSize(),SymbolData::Data64);
		break;
	case EncodingMode::Invalid:
		// TODO: Assert?
		break;
	}
}
<|endoftext|>


<commit_before>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2008, Willow Garage, Inc.
 *  Copyright (c) 2012, hiDOF, Inc.
 *  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 the Willow Garage 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 <effort_controllers/joint_velocity_controller.h>
#include <pluginlib/class_list_macros.h>

namespace effort_controllers {

JointVelocityController::JointVelocityController()
: command_(0), loop_count_(0)
{}

JointVelocityController::~JointVelocityController()
{
  sub_command_.shutdown();
}

  bool JointVelocityController::init(hardware_interface::EffortJointInterface *robot,
				     const std::string &joint_name, const control_toolbox::Pid &pid)
{
  joint_ = robot->getJointHandle(joint_name);
  pid_controller_ = pid;

  return true;
}

  bool JointVelocityController::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n)
{
  std::string joint_name;
  if (!n.getParam("joint", joint_name)) {
    ROS_ERROR("No joint given (namespace: %s)", n.getNamespace().c_str());
    return false;
  }

  if (!pid_controller_.init(ros::NodeHandle(n, "pid")))
    return false;

  controller_state_publisher_.reset(
    new realtime_tools::RealtimePublisher<controllers_msgs::JointControllerState>
    (n, "state", 1));

  sub_command_ = n.subscribe<std_msgs::Float64>("command", 1, &JointVelocityController::setCommandCB, this);

  return true;
}

void JointVelocityController::setGains(const double &p, const double &i, const double &d, const double &i_max, const double &i_min)
{
  pid_controller_.setGains(p,i,d,i_max,i_min);

}

void JointVelocityController::getGains(double &p, double &i, double &d, double &i_max, double &i_min)
{
  pid_controller_.getGains(p,i,d,i_max,i_min);
}

std::string JointVelocityController::getJointName()
{
  return joint_.getName();
}

// Set the joint velocity command
void JointVelocityController::setCommand(double cmd)
{
  command_ = cmd;
}

// Return the current velocity command
void JointVelocityController::getCommand(double  & cmd)
{
  cmd = command_;
}

void JointVelocityController::update(const ros::Time& time, const ros::Duration& period)
{
  double error = joint_.getVelocity() - command_;
  double command = pid_controller_.updatePid(error, perido);
  joint_.setCommand(command);

  if(loop_count_ % 10 == 0)
  {
    if(controller_state_publisher_ && controller_state_publisher_->trylock())
    {
      controller_state_publisher_->msg_.header.stamp = time;
      controller_state_publisher_->msg_.set_point = command_;
      controller_state_publisher_->msg_.process_value = joint_.getVelocity();
      controller_state_publisher_->msg_.error = error;
      controller_state_publisher_->msg_.time_step = perido.toSec();
      controller_state_publisher_->msg_.command = command;

      double dummy;
      getGains(controller_state_publisher_->msg_.p,
               controller_state_publisher_->msg_.i,
               controller_state_publisher_->msg_.d,
               controller_state_publisher_->msg_.i_clamp,
               dummy);
      controller_state_publisher_->unlockAndPublish();
    }
  }
  loop_count_++;
}

void JointVelocityController::setCommandCB(const std_msgs::Float64ConstPtr& msg)
{
  command_ = msg->data;
}

} // namespace

PLUGINLIB_DECLARE_CLASS(effort_controllers, JointVelocityController, effort_controllers::JointVelocityController, controller_interface::ControllerBase)
<commit_msg>Fixing typos in JointVelocityController<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2008, Willow Garage, Inc.
 *  Copyright (c) 2012, hiDOF, Inc.
 *  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 the Willow Garage 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 <effort_controllers/joint_velocity_controller.h>
#include <pluginlib/class_list_macros.h>

namespace effort_controllers {

JointVelocityController::JointVelocityController()
: command_(0), loop_count_(0)
{}

JointVelocityController::~JointVelocityController()
{
  sub_command_.shutdown();
}

  bool JointVelocityController::init(hardware_interface::EffortJointInterface *robot,
				     const std::string &joint_name, const control_toolbox::Pid &pid)
{
  joint_ = robot->getJointHandle(joint_name);
  pid_controller_ = pid;

  return true;
}

  bool JointVelocityController::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n)
{
  std::string joint_name;
  if (!n.getParam("joint", joint_name)) {
    ROS_ERROR("No joint given (namespace: %s)", n.getNamespace().c_str());
    return false;
  }

  if (!pid_controller_.init(ros::NodeHandle(n, "pid")))
    return false;

  controller_state_publisher_.reset(
    new realtime_tools::RealtimePublisher<controllers_msgs::JointControllerState>
    (n, "state", 1));

  sub_command_ = n.subscribe<std_msgs::Float64>("command", 1, &JointVelocityController::setCommandCB, this);

  return true;
}

void JointVelocityController::setGains(const double &p, const double &i, const double &d, const double &i_max, const double &i_min)
{
  pid_controller_.setGains(p,i,d,i_max,i_min);

}

void JointVelocityController::getGains(double &p, double &i, double &d, double &i_max, double &i_min)
{
  pid_controller_.getGains(p,i,d,i_max,i_min);
}

std::string JointVelocityController::getJointName()
{
  return joint_.getName();
}

// Set the joint velocity command
void JointVelocityController::setCommand(double cmd)
{
  command_ = cmd;
}

// Return the current velocity command
void JointVelocityController::getCommand(double  & cmd)
{
  cmd = command_;
}

void JointVelocityController::update(const ros::Time& time, const ros::Duration& period)
{
  double error = joint_.getVelocity() - command_;
  double command = pid_controller_.updatePid(error, period);
  joint_.setCommand(command);

  if(loop_count_ % 10 == 0)
  {
    if(controller_state_publisher_ && controller_state_publisher_->trylock())
    {
      controller_state_publisher_->msg_.header.stamp = time;
      controller_state_publisher_->msg_.set_point = command_;
      controller_state_publisher_->msg_.process_value = joint_.getVelocity();
      controller_state_publisher_->msg_.error = error;
      controller_state_publisher_->msg_.time_step = period.toSec();
      controller_state_publisher_->msg_.command = command;

      double dummy;
      getGains(controller_state_publisher_->msg_.p,
               controller_state_publisher_->msg_.i,
               controller_state_publisher_->msg_.d,
               controller_state_publisher_->msg_.i_clamp,
               dummy);
      controller_state_publisher_->unlockAndPublish();
    }
  }
  loop_count_++;
}

void JointVelocityController::setCommandCB(const std_msgs::Float64ConstPtr& msg)
{
  command_ = msg->data;
}

} // namespace

PLUGINLIB_DECLARE_CLASS(effort_controllers, JointVelocityController, effort_controllers::JointVelocityController, controller_interface::ControllerBase)
<|endoftext|>


<commit_before>/**
 * Zillians MMO
 * Copyright (C) 2007-2011 Zillians.com, Inc.
 * For more information see http://www.zillians.com
 *
 * Zillians MMO is the library and runtime for massive multiplayer online game
 * development in utility computing model, which runs as a service for every
 * developer to build their virtual world running on our GPU-assisted machines.
 *
 * This is a close source library intended to be used solely within Zillians.com
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "language/stage/generator/LLVMDebugInfoGeneratorStage.h"
#include "language/stage/generator/detail/LLVMForeach.h"
#include "language/stage/generator/visitor/LLVMDebugInfoGeneratorVisitor.h"
#include "language/context/ParserContext.h"
#include "language/context/GeneratorContext.h"

namespace zillians { namespace language { namespace stage {

LLVMDebugInfoGeneratorStage::LLVMDebugInfoGeneratorStage() : enabled(false)
{ }

LLVMDebugInfoGeneratorStage::~LLVMDebugInfoGeneratorStage()
{ }

const char* LLVMDebugInfoGeneratorStage::name()
{
	return "llvm_debug_info_generator_stage";
}

void LLVMDebugInfoGeneratorStage::initializeOptions(po::options_description& option_desc, po::positional_options_description& positional_desc)
{
    option_desc.add_options()
    ("debug", "enable debugging");
}

bool LLVMDebugInfoGeneratorStage::parseOptions(po::variables_map& vm)
{
	enabled = (vm.count("debug") > 0);
	return true;
}

bool LLVMDebugInfoGeneratorStage::execute(bool& continue_execution)
{
	if (!enabled)
		return true;

	// create visitor to walk through the entire tree and generate instructions accordingly
	visitor::LLVMDebugInfoGeneratorVisitor visitor(*getGeneratorContext().context, *getGeneratorContext().modules[0]);

	if(getParserContext().program)
	{
		visitor.visit(*getParserContext().program);
	}

	return true;
}

} } }
<commit_msg>Remove useless comment<commit_after>/**
 * Zillians MMO
 * Copyright (C) 2007-2011 Zillians.com, Inc.
 * For more information see http://www.zillians.com
 *
 * Zillians MMO is the library and runtime for massive multiplayer online game
 * development in utility computing model, which runs as a service for every
 * developer to build their virtual world running on our GPU-assisted machines.
 *
 * This is a close source library intended to be used solely within Zillians.com
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "language/stage/generator/LLVMDebugInfoGeneratorStage.h"
#include "language/stage/generator/detail/LLVMForeach.h"
#include "language/stage/generator/visitor/LLVMDebugInfoGeneratorVisitor.h"
#include "language/context/ParserContext.h"
#include "language/context/GeneratorContext.h"

namespace zillians { namespace language { namespace stage {

LLVMDebugInfoGeneratorStage::LLVMDebugInfoGeneratorStage() : enabled(false)
{ }

LLVMDebugInfoGeneratorStage::~LLVMDebugInfoGeneratorStage()
{ }

const char* LLVMDebugInfoGeneratorStage::name()
{
	return "llvm_debug_info_generator_stage";
}

void LLVMDebugInfoGeneratorStage::initializeOptions(po::options_description& option_desc, po::positional_options_description& positional_desc)
{
    option_desc.add_options()
    ("debug", "enable debugging");
}

bool LLVMDebugInfoGeneratorStage::parseOptions(po::variables_map& vm)
{
	enabled = (vm.count("debug") > 0);
	return true;
}

bool LLVMDebugInfoGeneratorStage::execute(bool& continue_execution)
{
	if (!enabled)
		return true;

	visitor::LLVMDebugInfoGeneratorVisitor visitor(*getGeneratorContext().context, *getGeneratorContext().modules[0]);

	if(getParserContext().program)
	{
		visitor.visit(*getParserContext().program);
	}

	return true;
}

} } }
<|endoftext|>