<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2014.  All rights reserved
 */
#include    "../../StroikaPreComp.h"

#if     qPlatform_Windows
#include    <Windows.h>
#endif

#include    "../../../Foundation/Characters/Format.h"
#include    "../../../Foundation/Characters/Tokenize.h"
#include    "../../../Foundation/Containers/Sequence.h"
#include    "../../../Foundation/Debug/Assertions.h"
#include    "../../../Foundation/Execution/ProcessRunner.h"
#include    "../../../Foundation/Streams/BasicBinaryInputOutputStream.h"
#include    "../../../Foundation/Streams/TextInputStreamBinaryAdapter.h"

#include    "../CommonMeasurementTypes.h"

#include    "MountedFilesystemUsage.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::Execution;
using   namespace   Stroika::Foundation::Memory;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::SystemPerformance;

namespace {
    struct VolumeInfo_ {
        String  fFileSystemType;
        String  fDeviceOrVolumeName;
        String  fVolumeID;
        String  fMountedOnName;
        Optional<double>    fDiskSizeInBytes;
        Optional<double>    fUsedSizeInBytes;
    };
}

namespace {
#if     qPlatform_Windows
    Sequence<VolumeInfo_> capture_ ()
    {
        Sequence<VolumeInfo_>   result;
        TCHAR volumeNameBuf[1024];
        for (HANDLE hVol = FindFirstVolume (volumeNameBuf, NEltsOf(volumeNameBuf)); hVol != INVALID_HANDLE_VALUE; ) {
            DWORD lpMaximumComponentLength;
            DWORD dwSysFlags;
            TCHAR FileSysNameBuf[1024];
            if (::GetVolumeInformation( volumeNameBuf, NULL, NEltsOf(volumeNameBuf), NULL, &lpMaximumComponentLength, &dwSysFlags, FileSysNameBuf, NEltsOf(FileSysNameBuf))) {
                VolumeInfo_ v;
                v.fFileSystemType = String::FromSDKString (FileSysNameBuf);
                v.fVolumeID = String::FromSDKString (volumeNameBuf);
                {
                    // @todo - use
                    //      http://msdn.microsoft.com/en-us/library/windows/desktop/cc542456(v=vs.85).aspx
                    //      CharCount = QueryDosDeviceW(&VolumeName[4], DeviceName, ARRAYSIZE(DeviceName));
                    //      to get DEVICENAME
                    //
                    TCHAR volPathsBuf[1024];
                    DWORD retLen = 0;
                    DWORD x = GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, NEltsOf(volPathsBuf), &retLen);
                    if (volPathsBuf[0] == 0) {
                        v.fMountedOnName.clear ();
                        result.push_back (v);
                    }
                    else {
                        for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += wcslen(NameIdx) + 1) {
                            v.fMountedOnName = String::FromSDKString (NameIdx);
                            {
                                ULARGE_INTEGER freeBytesAvailable;
                                ULARGE_INTEGER totalNumberOfBytes;
                                ULARGE_INTEGER totalNumberOfFreeBytes;
                                memset (&freeBytesAvailable, 0, sizeof (freeBytesAvailable));
                                memset (&totalNumberOfBytes, 0, sizeof (totalNumberOfBytes));
                                memset (&totalNumberOfFreeBytes, 0, sizeof (totalNumberOfFreeBytes));
                                DWORD xxx = GetDiskFreeSpaceEx (v.fMountedOnName.c_str (), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes);
                                v.fDiskSizeInBytes = static_cast<double> (totalNumberOfBytes.QuadPart);
                                v.fUsedSizeInBytes = *v.fDiskSizeInBytes  - freeBytesAvailable.QuadPart;
                            }
                            result.push_back (v);
                        }
                    }
                }
            }
            else {
                // warning...
            }

            // find next
            if (not ::FindNextVolume (hVol, volumeNameBuf, NEltsOf(volumeNameBuf))) {
                FindVolumeClose (hVol);
                hVol = INVALID_HANDLE_VALUE;
            }
        }
        return result;
    }
#elif   qPlatform_POSIX
    Sequence<VolumeInfo_> capture_ ()
    {
        // I looked through the /proc filesystem stuff and didnt see anything obvious to retrive this info...
        // run def with ProcessRunner
        Sequence<VolumeInfo_>   result;
        ProcessRunner pr (SDKSTR ("/bin/df -k -T"));
        Streams::BasicBinaryInputOutputStream   useStdOut;
        pr.SetStdOut (useStdOut);
        pr.Run ();
        String out;
        Streams::TextInputStreamBinaryAdapter   stdOut  =   Streams::TextInputStreamBinaryAdapter (useStdOut);
        bool skippedHeader = false;
        for (String i = stdOut.ReadLine (); not i.empty (); i = stdOut.ReadLine ()) {
            if (not skippedHeader) {
                skippedHeader = true;
                continue;
            }
            Sequence<String>    l    =  Characters::Tokenize<String> (i, L" ");
            if (l.size () < 7) {
                DbgTrace ("skipping line cuz len=%d", l.size ());
                continue;
            }
            VolumeInfo_ v;
            v.fFileSystemType = l[1].Trim ();
            v.fMountedOnName = l[6].Trim ();
            {
                String  d   =   l[0].Trim ();
                if (not d.empty () and d != L"none") {
                    v.fDeviceOrVolumeName = d;
                }
            }
            v.fDiskSizeInBytes = Characters::String2Float<double> (l[2]) * 1024;
            v.fUsedSizeInBytes = Characters::String2Float<double> (l[3]) * 1024;
            result.Append (v);
        }
        return result;
    }
#endif
}

/*
 ********************************************************************************
 ***************** Instruments::GetMountedFilesystemUsage ***********************
 ********************************************************************************
 */
Instrument  SystemPerformance::Instruments::GetMountedFilesystemUsage ()
{
    static  Instrument  kInstrument_    = Instrument (
            InstrumentNameType (L"Mounted-Filesystem-Usage"),
    [] () -> MeasurementSet {
        MeasurementSet    results;
        DateTime    before = DateTime::Now ();
        Sequence<VolumeInfo_> volumes   =   capture_ ();
        results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
        Sequence<VariantValue>  volumnesAsVariants;
        for (VolumeInfo_ v : volumes)
        {
            Mapping<String, VariantValue> vv;
            if (not v.fFileSystemType.empty ()) {
                vv.Add (L"Filesystem-Type", v.fFileSystemType);
            }
            if (not v.fDeviceOrVolumeName.empty ()) {
                vv.Add (L"Device-Name", v.fDeviceOrVolumeName);
            }
            if (not v.fVolumeID.empty ()) {
                vv.Add (L"Volume-ID", v.fVolumeID);
            }
            vv.Add (L"Mounted-On", v.fMountedOnName);
            if (v.fDiskSizeInBytes.IsPresent ()) {
                vv.Add (L"Disk-Size", *v.fDiskSizeInBytes);
            }
            if (v.fUsedSizeInBytes.IsPresent ()) {
                vv.Add (L"Disk-Used-Size", *v.fUsedSizeInBytes);
            }
            volumnesAsVariants.Append (VariantValue (vv));
        }
        Measurement m;
        m.fValue = volumnesAsVariants;
        m.fType = kMountedVolumeUsage;
        results.fMeasurements.Add (m);
        return results;
    },
    {kMountedVolumeUsage}
                                          );
    return kInstrument_;
}
<commit_msg>minor tweaks for String2Float<> refactoring<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2014.  All rights reserved
 */
#include    "../../StroikaPreComp.h"

#if     qPlatform_Windows
#include    <Windows.h>
#endif

#include    "../../../Foundation/Characters/String2Float.h"
#include    "../../../Foundation/Characters/Tokenize.h"
#include    "../../../Foundation/Containers/Sequence.h"
#include    "../../../Foundation/Debug/Assertions.h"
#include    "../../../Foundation/Execution/ProcessRunner.h"
#include    "../../../Foundation/Streams/BasicBinaryInputOutputStream.h"
#include    "../../../Foundation/Streams/TextInputStreamBinaryAdapter.h"

#include    "../CommonMeasurementTypes.h"

#include    "MountedFilesystemUsage.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::Execution;
using   namespace   Stroika::Foundation::Memory;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::SystemPerformance;

namespace {
    struct VolumeInfo_ {
        String  fFileSystemType;
        String  fDeviceOrVolumeName;
        String  fVolumeID;
        String  fMountedOnName;
        Optional<double>    fDiskSizeInBytes;
        Optional<double>    fUsedSizeInBytes;
    };
}

namespace {
#if     qPlatform_Windows
    Sequence<VolumeInfo_> capture_ ()
    {
        Sequence<VolumeInfo_>   result;
        TCHAR volumeNameBuf[1024];
        for (HANDLE hVol = FindFirstVolume (volumeNameBuf, NEltsOf(volumeNameBuf)); hVol != INVALID_HANDLE_VALUE; ) {
            DWORD lpMaximumComponentLength;
            DWORD dwSysFlags;
            TCHAR FileSysNameBuf[1024];
            if (::GetVolumeInformation( volumeNameBuf, NULL, NEltsOf(volumeNameBuf), NULL, &lpMaximumComponentLength, &dwSysFlags, FileSysNameBuf, NEltsOf(FileSysNameBuf))) {
                VolumeInfo_ v;
                v.fFileSystemType = String::FromSDKString (FileSysNameBuf);
                v.fVolumeID = String::FromSDKString (volumeNameBuf);
                {
                    // @todo - use
                    //      http://msdn.microsoft.com/en-us/library/windows/desktop/cc542456(v=vs.85).aspx
                    //      CharCount = QueryDosDeviceW(&VolumeName[4], DeviceName, ARRAYSIZE(DeviceName));
                    //      to get DEVICENAME
                    //
                    TCHAR volPathsBuf[1024];
                    DWORD retLen = 0;
                    DWORD x = GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, NEltsOf(volPathsBuf), &retLen);
                    if (volPathsBuf[0] == 0) {
                        v.fMountedOnName.clear ();
                        result.push_back (v);
                    }
                    else {
                        for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += wcslen(NameIdx) + 1) {
                            v.fMountedOnName = String::FromSDKString (NameIdx);
                            {
                                ULARGE_INTEGER freeBytesAvailable;
                                ULARGE_INTEGER totalNumberOfBytes;
                                ULARGE_INTEGER totalNumberOfFreeBytes;
                                memset (&freeBytesAvailable, 0, sizeof (freeBytesAvailable));
                                memset (&totalNumberOfBytes, 0, sizeof (totalNumberOfBytes));
                                memset (&totalNumberOfFreeBytes, 0, sizeof (totalNumberOfFreeBytes));
                                DWORD xxx = GetDiskFreeSpaceEx (v.fMountedOnName.c_str (), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes);
                                v.fDiskSizeInBytes = static_cast<double> (totalNumberOfBytes.QuadPart);
                                v.fUsedSizeInBytes = *v.fDiskSizeInBytes  - freeBytesAvailable.QuadPart;
                            }
                            result.push_back (v);
                        }
                    }
                }
            }
            else {
                // warning...
            }

            // find next
            if (not ::FindNextVolume (hVol, volumeNameBuf, NEltsOf(volumeNameBuf))) {
                FindVolumeClose (hVol);
                hVol = INVALID_HANDLE_VALUE;
            }
        }
        return result;
    }
#elif   qPlatform_POSIX
    Sequence<VolumeInfo_> capture_ ()
    {
        // I looked through the /proc filesystem stuff and didnt see anything obvious to retrive this info...
        // run def with ProcessRunner
        Sequence<VolumeInfo_>   result;
        ProcessRunner pr (SDKSTR ("/bin/df -k -T"));
        Streams::BasicBinaryInputOutputStream   useStdOut;
        pr.SetStdOut (useStdOut);
        pr.Run ();
        String out;
        Streams::TextInputStreamBinaryAdapter   stdOut  =   Streams::TextInputStreamBinaryAdapter (useStdOut);
        bool skippedHeader = false;
        for (String i = stdOut.ReadLine (); not i.empty (); i = stdOut.ReadLine ()) {
            if (not skippedHeader) {
                skippedHeader = true;
                continue;
            }
            Sequence<String>    l    =  Characters::Tokenize<String> (i, L" ");
            if (l.size () < 7) {
                DbgTrace ("skipping line cuz len=%d", l.size ());
                continue;
            }
            VolumeInfo_ v;
            v.fFileSystemType = l[1].Trim ();
            v.fMountedOnName = l[6].Trim ();
            {
                String  d   =   l[0].Trim ();
                if (not d.empty () and d != L"none") {
                    v.fDeviceOrVolumeName = d;
                }
            }
            v.fDiskSizeInBytes = Characters::String2Float<double> (l[2]) * 1024;
            v.fUsedSizeInBytes = Characters::String2Float<double> (l[3]) * 1024;
            result.Append (v);
        }
        return result;
    }
#endif
}

/*
 ********************************************************************************
 ***************** Instruments::GetMountedFilesystemUsage ***********************
 ********************************************************************************
 */
Instrument  SystemPerformance::Instruments::GetMountedFilesystemUsage ()
{
    static  Instrument  kInstrument_    = Instrument (
            InstrumentNameType (L"Mounted-Filesystem-Usage"),
    [] () -> MeasurementSet {
        MeasurementSet    results;
        DateTime    before = DateTime::Now ();
        Sequence<VolumeInfo_> volumes   =   capture_ ();
        results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
        Sequence<VariantValue>  volumnesAsVariants;
        for (VolumeInfo_ v : volumes)
        {
            Mapping<String, VariantValue> vv;
            if (not v.fFileSystemType.empty ()) {
                vv.Add (L"Filesystem-Type", v.fFileSystemType);
            }
            if (not v.fDeviceOrVolumeName.empty ()) {
                vv.Add (L"Device-Name", v.fDeviceOrVolumeName);
            }
            if (not v.fVolumeID.empty ()) {
                vv.Add (L"Volume-ID", v.fVolumeID);
            }
            vv.Add (L"Mounted-On", v.fMountedOnName);
            if (v.fDiskSizeInBytes.IsPresent ()) {
                vv.Add (L"Disk-Size", *v.fDiskSizeInBytes);
            }
            if (v.fUsedSizeInBytes.IsPresent ()) {
                vv.Add (L"Disk-Used-Size", *v.fUsedSizeInBytes);
            }
            volumnesAsVariants.Append (VariantValue (vv));
        }
        Measurement m;
        m.fValue = volumnesAsVariants;
        m.fType = kMountedVolumeUsage;
        results.fMeasurements.Add (m);
        return results;
    },
    {kMountedVolumeUsage}
                                          );
    return kInstrument_;
}
<|endoftext|>


<commit_before>// @(#):$Id$
// Author: Andrei Gheata   01/03/11

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

////////////////////////////////////////////////////////////////////////////
//
// TGeoBranchArray - An array of daughter indices making a geometry path.
//   Can be used to backup/restore a state. To setup an object of this type,
// one should use:
//   TGeoBranchArray *array = new TGeoBranchArray(level);
//   array->InitFromNavigator(nav); (To initialize from current navigator state)
// The navigator can be updated to reflect this path array:
//   array->UpdateNavigator();
//
/////////////////////////////////////////////////////////////////////////////

#include "TGeoBranchArray.h"

#include "TMath.h"
#include "TThread.h"
#include "TString.h"
#include "TGeoMatrix.h"
#include "TGeoNavigator.h"
#include "TGeoManager.h"

ClassImp(TGeoBranchArray)

//______________________________________________________________________________
TGeoBranchArray::TGeoBranchArray(UShort_t level)
                :fLevel(level),
                 fArray(NULL),
                 fMatrix(NULL),
                 fClient(NULL)
{
// Constructor. Alocates the array with a size given by level.
   fArray = new UShort_t[level];
}

//______________________________________________________________________________
TGeoBranchArray::~TGeoBranchArray()
{
// Destructor.
   delete [] fArray;
   delete fMatrix;
}

//______________________________________________________________________________
TGeoBranchArray::TGeoBranchArray(const TGeoBranchArray&  other)
                :TObject(other),
                 fLevel(other.fLevel),
                 fArray(NULL),
                 fMatrix(NULL),
                 fClient(other.fClient)
{
// Copy constructor.
   if (fLevel) fArray = new UShort_t[fLevel];
   if (other.fMatrix) fMatrix = new TGeoHMatrix(*(other.fMatrix));
}

//______________________________________________________________________________
TGeoBranchArray& TGeoBranchArray::operator=(const TGeoBranchArray& other)
{
// Assignment.
   if (&other == this) return *this;
   fLevel = other.fLevel;
   if (fLevel) fArray = new UShort_t[fLevel];
   if (other.fMatrix) {
      fMatrix = new TGeoHMatrix();
      fMatrix->CopyFrom(other.fMatrix);
   }
   fClient = other.fClient;
   return *this;
}

//______________________________________________________________________________
void TGeoBranchArray::AddLevel(UShort_t dindex)
{
// Add and extra daughter to the current path array. No validity check performed !
   if (!fLevel) {
      Error("AddLevel", "You must initialize from navigator or copy from another branch array first.");
      return;
   }
   fLevel++;
   UShort_t *array = new UShort_t[fLevel];
   memcpy(array, fArray, (fLevel-1)*sizeof(UShort_t));
   array[fLevel-1] = dindex;
   delete [] fArray;
   fArray = array;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator ==(const TGeoBranchArray& other) const
{
// Is equal operator.
   Int_t value = Compare(&other);
   if (value==0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator !=(const TGeoBranchArray& other) const
{
// Not equal operator.
   Int_t value = Compare(&other);
   if (value!=0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator >(const TGeoBranchArray& other) const
{
// Is equal operator.
   Int_t value = Compare(&other);
   if (value>0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator <(const TGeoBranchArray& other) const
{
// Is equal operator.
   Int_t value = Compare(&other);
   if (value<0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator >=(const TGeoBranchArray& other) const
{
// Is equal operator.
   Int_t value = Compare(&other);
   if (value>=0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator <=(const TGeoBranchArray& other) const
{
// Is equal operator.
   Int_t value = Compare(&other);
   if (value<=0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Long64_t TGeoBranchArray::BinarySearch(Long64_t n, const TGeoBranchArray **array, TGeoBranchArray *value)
{
// Binary search in an array of n pointers to branch arrays, to locate value.
// Returns element index or index of nearest element smaller than value
   Long64_t nabove, nbelow, middle;
   const TGeoBranchArray *pind;
   nabove = n+1;
   nbelow = 0;
   while(nabove-nbelow > 1) {
      middle = (nabove+nbelow)/2;
      pind = array[middle-1];
      if (*value == *pind) return middle-1;
      if (*value  < *pind) nabove = middle;
      else                          nbelow = middle;
   }
   return nbelow-1;
}

//______________________________________________________________________________
Int_t TGeoBranchArray::Compare(const TObject *obj) const
{
// Compare with other object of same type. Returns -1 if this is smaller (first
// smaller array value prevails), 0 if equal (size and values) and 1 if this is
// larger.
   UShort_t i;
   TGeoBranchArray *other = (TGeoBranchArray*)obj;
   UShort_t otherLevel = other->GetLevel();
   UShort_t maxLevel = TMath::Min(fLevel, otherLevel);
   UShort_t *otherArray = other->GetArray();
   for (i=0; i<maxLevel; i++) {
      if (fArray[i]==otherArray[i]) continue;
      if (fArray[i]<otherArray[i]) return -1;
      return 1;
   }
   if (fLevel==otherLevel) return 0;
   if (fLevel<otherLevel) return -1;
   return 1;
}

//______________________________________________________________________________
void TGeoBranchArray::CleanMatrix()
{
// Garbage collect the stored matrix.
   delete fMatrix; fMatrix = 0;
}

//______________________________________________________________________________
TGeoNode *TGeoBranchArray::GetNode(UShort_t level) const
{
   TGeoNode *node = gGeoManager->GetTopNode();
   if (!level) return node;
   if (level>fLevel) return NULL;
   for (Int_t i=0; i<level; i++) node = node->GetVolume()->GetNode(fArray[i]);
   return node;
}

//______________________________________________________________________________
void TGeoBranchArray::InitFromNavigator(TGeoNavigator *nav)
{
// Init the branch array from current navigator state.
   TThread::Lock();
   UShort_t level = (UShort_t)nav->GetLevel();
   if (!fMatrix) fMatrix = new TGeoHMatrix();
   fMatrix->CopyFrom(nav->GetCurrentMatrix());
   if (!level) {
//      delete [] fArray; fArray = 0;
      fLevel = 0;
      return;
   }
   if (!fArray || level>fLevel) {
      delete [] fArray;
      fArray = new UShort_t[level];
   }
   fLevel = level;
   TGeoNode *mother = nav->GetMother(fLevel);
   for (Int_t i=fLevel-1; i>=0; i--) {
      TGeoNode *node = nav->GetMother(i);
      Int_t index = mother->GetVolume()->GetIndex(node);
      fArray[fLevel-i-1] = index;
      mother = node;
   }
   TThread::UnLock();
}

//______________________________________________________________________________
void TGeoBranchArray::GetPath(TString &path) const
{
// Fill path pointed by the array.
   path = "/";
   TGeoNode *node = GetNode(0);
   path += node->GetName();
   for (Int_t i=0; i<fLevel; i++) {
      path += "/";
      node = node->GetVolume()->GetNode(fArray[i]);
      path += node->GetName();
   }
}

//______________________________________________________________________________
void TGeoBranchArray::Print(Option_t *) const
{
// Print branch information
   TString path;
   GetPath(path);
   printf("branch:    %s\n", path.Data());
}

//______________________________________________________________________________
void TGeoBranchArray::Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down)
{
// Sorting of an array of branch array pointers.
   for (Int_t i=0; i<n; i++) index[i] = i;
   if (down)
      std::sort(index, index + n, compareBAdesc(array));
   else
      std::sort(index, index + n, compareBAasc(array));
}

//______________________________________________________________________________
void TGeoBranchArray::UpdateNavigator(TGeoNavigator *nav) const
{
// Update the navigator to reflect the branch.
   nav->CdTop();
   for (Int_t i=0; i<fLevel; i++) nav->CdDown(fArray[i]);
}
<commit_msg>Fix deadlock in TGeoBranchArray<commit_after>// @(#):$Id$
// Author: Andrei Gheata   01/03/11

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

////////////////////////////////////////////////////////////////////////////
//
// TGeoBranchArray - An array of daughter indices making a geometry path.
//   Can be used to backup/restore a state. To setup an object of this type,
// one should use:
//   TGeoBranchArray *array = new TGeoBranchArray(level);
//   array->InitFromNavigator(nav); (To initialize from current navigator state)
// The navigator can be updated to reflect this path array:
//   array->UpdateNavigator();
//
/////////////////////////////////////////////////////////////////////////////

#include "TGeoBranchArray.h"

#include "TMath.h"
#include "TThread.h"
#include "TString.h"
#include "TGeoMatrix.h"
#include "TGeoNavigator.h"
#include "TGeoManager.h"

ClassImp(TGeoBranchArray)

//______________________________________________________________________________
TGeoBranchArray::TGeoBranchArray(UShort_t level)
                :fLevel(level),
                 fArray(NULL),
                 fMatrix(NULL),
                 fClient(NULL)
{
// Constructor. Alocates the array with a size given by level.
   fArray = new UShort_t[level];
}

//______________________________________________________________________________
TGeoBranchArray::~TGeoBranchArray()
{
// Destructor.
   delete [] fArray;
   delete fMatrix;
}

//______________________________________________________________________________
TGeoBranchArray::TGeoBranchArray(const TGeoBranchArray&  other)
                :TObject(other),
                 fLevel(other.fLevel),
                 fArray(NULL),
                 fMatrix(NULL),
                 fClient(other.fClient)
{
// Copy constructor.
   if (fLevel) fArray = new UShort_t[fLevel];
   if (other.fMatrix) fMatrix = new TGeoHMatrix(*(other.fMatrix));
}

//______________________________________________________________________________
TGeoBranchArray& TGeoBranchArray::operator=(const TGeoBranchArray& other)
{
// Assignment.
   if (&other == this) return *this;
   TThread::Lock();
   fLevel = other.fLevel;
   if (fLevel) fArray = new UShort_t[fLevel];
   if (other.fMatrix) {
      fMatrix = new TGeoHMatrix();
      fMatrix->CopyFrom(other.fMatrix);
   }
   fClient = other.fClient;
   TThread::UnLock();
   return *this;
}

//______________________________________________________________________________
void TGeoBranchArray::AddLevel(UShort_t dindex)
{
// Add and extra daughter to the current path array. No validity check performed !
   if (!fLevel) {
      Error("AddLevel", "You must initialize from navigator or copy from another branch array first.");
      return;
   }
   fLevel++;
   UShort_t *array = new UShort_t[fLevel];
   memcpy(array, fArray, (fLevel-1)*sizeof(UShort_t));
   array[fLevel-1] = dindex;
   delete [] fArray;
   fArray = array;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator ==(const TGeoBranchArray& other) const
{
// Is equal operator.
   Int_t value = Compare(&other);
   if (value==0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator !=(const TGeoBranchArray& other) const
{
// Not equal operator.
   Int_t value = Compare(&other);
   if (value!=0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator >(const TGeoBranchArray& other) const
{
// Is equal operator.
   Int_t value = Compare(&other);
   if (value>0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator <(const TGeoBranchArray& other) const
{
// Is equal operator.
   Int_t value = Compare(&other);
   if (value<0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator >=(const TGeoBranchArray& other) const
{
// Is equal operator.
   Int_t value = Compare(&other);
   if (value>=0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Bool_t TGeoBranchArray::operator <=(const TGeoBranchArray& other) const
{
// Is equal operator.
   Int_t value = Compare(&other);
   if (value<=0) return kTRUE;
   return kFALSE;
}

//______________________________________________________________________________
Long64_t TGeoBranchArray::BinarySearch(Long64_t n, const TGeoBranchArray **array, TGeoBranchArray *value)
{
// Binary search in an array of n pointers to branch arrays, to locate value.
// Returns element index or index of nearest element smaller than value
   Long64_t nabove, nbelow, middle;
   const TGeoBranchArray *pind;
   nabove = n+1;
   nbelow = 0;
   while(nabove-nbelow > 1) {
      middle = (nabove+nbelow)/2;
      pind = array[middle-1];
      if (*value == *pind) return middle-1;
      if (*value  < *pind) nabove = middle;
      else                          nbelow = middle;
   }
   return nbelow-1;
}

//______________________________________________________________________________
Int_t TGeoBranchArray::Compare(const TObject *obj) const
{
// Compare with other object of same type. Returns -1 if this is smaller (first
// smaller array value prevails), 0 if equal (size and values) and 1 if this is
// larger.
   UShort_t i;
   TGeoBranchArray *other = (TGeoBranchArray*)obj;
   UShort_t otherLevel = other->GetLevel();
   UShort_t maxLevel = TMath::Min(fLevel, otherLevel);
   UShort_t *otherArray = other->GetArray();
   for (i=0; i<maxLevel; i++) {
      if (fArray[i]==otherArray[i]) continue;
      if (fArray[i]<otherArray[i]) return -1;
      return 1;
   }
   if (fLevel==otherLevel) return 0;
   if (fLevel<otherLevel) return -1;
   return 1;
}

//______________________________________________________________________________
void TGeoBranchArray::CleanMatrix()
{
// Garbage collect the stored matrix.
   delete fMatrix; fMatrix = 0;
}

//______________________________________________________________________________
TGeoNode *TGeoBranchArray::GetNode(UShort_t level) const
{
   TGeoNode *node = gGeoManager->GetTopNode();
   if (!level) return node;
   if (level>fLevel) return NULL;
   for (Int_t i=0; i<level; i++) node = node->GetVolume()->GetNode(fArray[i]);
   return node;
}

//______________________________________________________________________________
void TGeoBranchArray::InitFromNavigator(TGeoNavigator *nav)
{
// Init the branch array from current navigator state.
   TThread::Lock();
   UShort_t level = (UShort_t)nav->GetLevel();
   if (!fMatrix) fMatrix = new TGeoHMatrix();
   fMatrix->CopyFrom(nav->GetCurrentMatrix());
   if (!level) {
//      delete [] fArray; fArray = 0;
      fLevel = 0;
      TThread::UnLock();
      return;
   }
   if (!fArray || level>fLevel) {
      delete [] fArray;
      fArray = new UShort_t[level];
   }
   fLevel = level;
   TGeoNode *mother = nav->GetMother(fLevel);
   for (Int_t i=fLevel-1; i>=0; i--) {
      TGeoNode *node = nav->GetMother(i);
      Int_t index = mother->GetVolume()->GetIndex(node);
      fArray[fLevel-i-1] = index;
      mother = node;
   }
   TThread::UnLock();
}

//______________________________________________________________________________
void TGeoBranchArray::GetPath(TString &path) const
{
// Fill path pointed by the array.
   path = "/";
   TGeoNode *node = GetNode(0);
   path += node->GetName();
   for (Int_t i=0; i<fLevel; i++) {
      path += "/";
      node = node->GetVolume()->GetNode(fArray[i]);
      path += node->GetName();
   }
}

//______________________________________________________________________________
void TGeoBranchArray::Print(Option_t *) const
{
// Print branch information
   TString path;
   GetPath(path);
   printf("branch:    %s\n", path.Data());
}

//______________________________________________________________________________
void TGeoBranchArray::Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down)
{
// Sorting of an array of branch array pointers.
   for (Int_t i=0; i<n; i++) index[i] = i;
   if (down)
      std::sort(index, index + n, compareBAdesc(array));
   else
      std::sort(index, index + n, compareBAasc(array));
}

//______________________________________________________________________________
void TGeoBranchArray::UpdateNavigator(TGeoNavigator *nav) const
{
// Update the navigator to reflect the branch.
   nav->CdTop();
   for (Int_t i=0; i<fLevel; i++) nav->CdDown(fArray[i]);
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Leiden University Medical Center, Erasmus University Medical
 *  Center and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "selxSuperElastixFilterCustomComponents.h"
#include "selxItkDisplacementFieldSourceComponent.h"
#include "selxItkDisplacementFieldSinkComponent.h"
#include "selxItkMeshSourceComponent.h"
#include "selxItkMeshSinkComponent.h"
#include "itkMeshFileReader.h"
#include "itkMeshFileWriter.h"
#include "selxDisplacementFieldMeshWarperComponent.h"

#include "gtest/gtest.h"
#include "selxDataManager.h"

namespace selx {

class DisplacementFieldMeshWarperComponentTest : public ::testing::Test {
public:

  typedef ItkDisplacementFieldMeshWarperComponent< 2, float, float >::ItkDisplacementFieldType DisplacementFieldType;
  typedef DisplacementFieldType::Pointer DisplacementFieldPointer;
  typedef itk::ImageFileReader< DisplacementFieldType > DisplacementFieldReaderType;
  typedef DisplacementFieldReaderType::Pointer DisplacementFieldReaderPointer;
  typedef itk::ImageFileWriter< DisplacementFieldType > DisplacementFieldWriterType;
  typedef DisplacementFieldWriterType::Pointer DisplacementFieldWriterPointer;

  typedef itk::Mesh< float, 2 > MeshType;
  typedef MeshType::Pointer MeshPointer;
  typedef itk::MeshFileReader< MeshType > MeshReaderType;
  typedef MeshReaderType::Pointer MeshReaderPointer;
  typedef itk::MeshFileWriter< MeshType > MeshWriterType;
  typedef MeshWriterType::Pointer MeshWriterPointer;

  typedef Blueprint::Pointer BlueprintPointer;

  typedef TypeList<
    ItkDisplacementFieldSourceComponent< 2, float >,
    ItkDisplacementFieldSinkComponent< 2, float >,
    ItkMeshSourceComponent< 2, float >,
    ItkMeshSinkComponent< 2, float >,
    ItkDisplacementFieldMeshWarperComponent< 2, float, float > > TestComponents;

  typedef SuperElastixFilterCustomComponents< TestComponents > SuperElastixFilterType;
  typedef SuperElastixFilterType::Pointer SuperElastixFilterPointer;

  DataManager::Pointer dataManager = DataManager::New();
};

TEST_F( DisplacementFieldMeshWarperComponentTest, SinkAndSource )
{

  DisplacementFieldPointer displacementField = DisplacementFieldType::New();
  displacementField->SetRegions(DisplacementFieldType::Superclass::SizeType({{3, 3}}));
  displacementField->Allocate();

  DisplacementFieldType::Superclass::IndexType index00, index01, index02,
                                               index10, index11, index12,
                                               index20, index21, index22;

  index00[0] = 0; index00[1] = 0;
  index01[0] = 0; index01[1] = 1;
  index02[0] = 0; index02[1] = 2;
  index10[0] = 1; index10[1] = 0;
  index11[0] = 1; index11[1] = 1;
  index12[0] = 1; index12[1] = 2;
  index20[0] = 2; index20[1] = 0;
  index21[0] = 2; index21[1] = 1;
  index22[0] = 2; index22[1] = 2;

  typedef itk::Vector<float, 2> VectorType;
  VectorType displacement00, displacement01, displacement10, displacement11, displacementminus11;
  displacement00[0] = 0.;
  displacement00[1] = 0.;

  displacement01[0] = 0.;
  displacement01[1] = 1.;

  displacement10[0] = 1.;
  displacement10[1] = 0.;

  displacement11[0] = 1.;
  displacement11[1] = 1.;

  displacementminus11[0] = -1.;
  displacementminus11[1] = -1.;

  displacementField->SetPixel(index00, displacement01);
  displacementField->SetPixel(index01, displacement10);
  displacementField->SetPixel(index02, displacement00);
  displacementField->SetPixel(index10, displacement10);
  displacementField->SetPixel(index11, displacement11);
  displacementField->SetPixel(index12, displacement00);
  displacementField->SetPixel(index20, displacement00);
  displacementField->SetPixel(index21, displacement00);
  displacementField->SetPixel(index22, displacementminus11);

  Logger::Pointer logger = Logger::New();
  logger->AddStream( "cout", std::cout );
  logger->SetLogLevel( LogLevel::TRC );

  BlueprintPointer blueprint = Blueprint::New();
  using ParameterMapType = Blueprint::ParameterMapType;

  ParameterMapType displacementFieldSourceParameters;
  displacementFieldSourceParameters[ "NameOfClass" ]    = { "ItkDisplacementFieldSourceComponent" };
  displacementFieldSourceParameters[ "Dimensionality" ] = { "2" };
  blueprint->SetComponent( "DisplacementFieldSource", displacementFieldSourceParameters );

  ParameterMapType meshSourceParameters;
  meshSourceParameters[ "NameOfClass" ]    = { "ItkMeshSourceComponent" };
  meshSourceParameters[ "Dimensionality" ] = { "2" };
  blueprint->SetComponent( "MeshSource", meshSourceParameters );

  ParameterMapType meshSinkParameters;
  meshSinkParameters[ "NameOfClass" ]    = { "ItkMeshSinkComponent" };
  meshSinkParameters[ "Dimensionality" ] = { "2" };
  blueprint->SetComponent( "MeshSink", meshSinkParameters );

  ParameterMapType displacementFieldMeshWarperParameters;
  displacementFieldMeshWarperParameters[ "NameOfClass" ]    = { "ItkDisplacementFieldMeshWarperComponent" };
  displacementFieldMeshWarperParameters[ "Dimensionality" ] = { "2" };
  blueprint->SetComponent( "DisplacementFieldMeshWarper", displacementFieldMeshWarperParameters );

  ParameterMapType connection0;
  connection0[ "NameOfInterface" ] = { "itkMeshInterface" };
  blueprint->SetConnection( "MeshSource", "DisplacementFieldMeshWarper", connection0 );

  ParameterMapType connection1;
  connection0[ "NameOfInterface" ] = { "itkDisplacementFieldInterface" };
  blueprint->SetConnection( "DisplacementFieldSource", "DisplacementFieldMeshWarper", connection1 );

  ParameterMapType connection2;
  connection0[ "NameOfInterface" ] = { "itkMeshInterface" };
  blueprint->SetConnection( "DisplacementFieldMeshWarper", "MeshSink", connection2 );

  SuperElastixFilterPointer superElastixFilter = SuperElastixFilterType::New();
  superElastixFilter->SetBlueprint(blueprint);
  superElastixFilter->SetLogger(logger);

  MeshReaderPointer meshReader = MeshReaderType::New();
  meshReader->SetFileName( this->dataManager->GetInputFile( "2dSquare.vtk" ) );

  superElastixFilter->SetInput( "DisplacementFieldSource", displacementField );
  superElastixFilter->SetInput( "MeshSource", meshReader->GetOutput() );

  MeshWriterPointer meshWriter = MeshWriterType::New();
  meshWriter->SetFileName( this->dataManager->GetOutputFile( "DisplacementFieldMeshWarperComponentTest.SinkAndSource.WarpedMesh.vtk" ) );
  meshWriter->SetInput( superElastixFilter->GetOutput< MeshType >( "MeshSink" ) );
  meshWriter->Update();
}

} // namespace selx<commit_msg>ENH: Add working test<commit_after>/*=========================================================================
 *
 *  Copyright Leiden University Medical Center, Erasmus University Medical
 *  Center and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "selxSuperElastixFilterCustomComponents.h"
#include "selxItkDisplacementFieldSourceComponent.h"
#include "selxItkDisplacementFieldSinkComponent.h"
#include "selxItkMeshSourceComponent.h"
#include "selxItkMeshSinkComponent.h"
#include "itkMeshFileReader.h"
#include "itkMeshFileWriter.h"
#include "selxDisplacementFieldMeshWarperComponent.h"

#include "gtest/gtest.h"
#include "selxDataManager.h"

namespace selx {

class DisplacementFieldMeshWarperComponentTest : public ::testing::Test {
public:

  typedef ItkDisplacementFieldMeshWarperComponent< 2, float, float >::ItkDisplacementFieldType DisplacementFieldType;
  typedef DisplacementFieldType::Pointer DisplacementFieldPointer;
  typedef itk::ImageFileReader< DisplacementFieldType > DisplacementFieldReaderType;
  typedef DisplacementFieldReaderType::Pointer DisplacementFieldReaderPointer;
  typedef itk::ImageFileWriter< DisplacementFieldType > DisplacementFieldWriterType;
  typedef DisplacementFieldWriterType::Pointer DisplacementFieldWriterPointer;

  typedef itk::Mesh< float, 2 > MeshType;
  typedef MeshType::Pointer MeshPointer;
  typedef itk::MeshFileReader< MeshType > MeshReaderType;
  typedef MeshReaderType::Pointer MeshReaderPointer;
  typedef itk::MeshFileWriter< MeshType > MeshWriterType;
  typedef MeshWriterType::Pointer MeshWriterPointer;

  typedef Blueprint::Pointer BlueprintPointer;

  typedef TypeList<
    ItkDisplacementFieldSourceComponent< 2, float >,
    ItkDisplacementFieldSinkComponent< 2, float >,
    ItkMeshSourceComponent< 2, float >,
    ItkMeshSinkComponent< 2, float >,
    ItkDisplacementFieldMeshWarperComponent< 2, float, float > > TestComponents;

  typedef SuperElastixFilterCustomComponents< TestComponents > SuperElastixFilterType;
  typedef SuperElastixFilterType::Pointer SuperElastixFilterPointer;

  DataManager::Pointer dataManager = DataManager::New();
};

TEST_F( DisplacementFieldMeshWarperComponentTest, SinkAndSource )
{

  DisplacementFieldPointer displacementField = DisplacementFieldType::New();
  displacementField->SetRegions(DisplacementFieldType::Superclass::SizeType({{3, 3}}));
  displacementField->Allocate();

  DisplacementFieldType::Superclass::IndexType index00, index01, index02,
                                               index10, index11, index12,
                                               index20, index21, index22;

  index00[0] = 0; index00[1] = 0;
  index01[0] = 0; index01[1] = 1;
  index02[0] = 0; index02[1] = 2;
  index10[0] = 1; index10[1] = 0;
  index11[0] = 1; index11[1] = 1;
  index12[0] = 1; index12[1] = 2;
  index20[0] = 2; index20[1] = 0;
  index21[0] = 2; index21[1] = 1;
  index22[0] = 2; index22[1] = 2;

  typedef itk::Vector<float, 2> VectorType;
  VectorType displacement00, displacement01, displacement10, displacement11, displacementminus11;
  displacement00[0] = 0.;
  displacement00[1] = 0.;

  displacement01[0] = 0.;
  displacement01[1] = 1.;

  displacement10[0] = 1.;
  displacement10[1] = 0.;

  displacement11[0] = 1.;
  displacement11[1] = 1.;

  displacementminus11[0] = -1.;
  displacementminus11[1] = -1.;

  displacementField->SetPixel(index00, displacement01);
  displacementField->SetPixel(index01, displacement10);
  displacementField->SetPixel(index02, displacement00);
  displacementField->SetPixel(index10, displacement10);
  displacementField->SetPixel(index11, displacement11);
  displacementField->SetPixel(index12, displacement00);
  displacementField->SetPixel(index20, displacement00);
  displacementField->SetPixel(index21, displacement00);
  displacementField->SetPixel(index22, displacementminus11);

  Logger::Pointer logger = Logger::New();
  logger->AddStream( "cout", std::cout );
  logger->SetLogLevel( LogLevel::TRC );

  BlueprintPointer blueprint = Blueprint::New();
  using ParameterMapType = Blueprint::ParameterMapType;

  ParameterMapType displacementFieldSourceParameters;
  displacementFieldSourceParameters[ "NameOfClass" ]    = { "ItkDisplacementFieldSourceComponent" };
  displacementFieldSourceParameters[ "Dimensionality" ] = { "2" };
  blueprint->SetComponent( "DisplacementFieldSource", displacementFieldSourceParameters );

  ParameterMapType meshSourceParameters;
  meshSourceParameters[ "NameOfClass" ]    = { "ItkMeshSourceComponent" };
  meshSourceParameters[ "Dimensionality" ] = { "2" };
  blueprint->SetComponent( "MeshSource", meshSourceParameters );

  ParameterMapType meshSinkParameters;
  meshSinkParameters[ "NameOfClass" ]    = { "ItkMeshSinkComponent" };
  meshSinkParameters[ "Dimensionality" ] = { "2" };
  blueprint->SetComponent( "MeshSink", meshSinkParameters );

  ParameterMapType displacementFieldMeshWarperParameters;
  displacementFieldMeshWarperParameters[ "NameOfClass" ]    = { "ItkDisplacementFieldMeshWarperComponent" };
  displacementFieldMeshWarperParameters[ "Dimensionality" ] = { "2" };
  blueprint->SetComponent( "DisplacementFieldMeshWarper", displacementFieldMeshWarperParameters );

  ParameterMapType connection0;
  connection0[ "NameOfInterface" ] = { "itkMeshInterface" };
  blueprint->SetConnection( "MeshSource", "DisplacementFieldMeshWarper", connection0 );

  ParameterMapType connection1;
  connection0[ "NameOfInterface" ] = { "itkDisplacementFieldInterface" };
  blueprint->SetConnection( "DisplacementFieldSource", "DisplacementFieldMeshWarper", connection1 );

  ParameterMapType connection2;
  connection0[ "NameOfInterface" ] = { "itkMeshInterface" };
  blueprint->SetConnection( "DisplacementFieldMeshWarper", "MeshSink", connection2 );

  SuperElastixFilterPointer superElastixFilter = SuperElastixFilterType::New();
  superElastixFilter->SetBlueprint(blueprint);
  superElastixFilter->SetLogger(logger);

  MeshReaderPointer meshReader = MeshReaderType::New();
  meshReader->SetFileName( this->dataManager->GetInputFile( "2dSquare.vtk" ) );

  superElastixFilter->SetInput( "DisplacementFieldSource", displacementField );
  superElastixFilter->SetInput( "MeshSource", meshReader->GetOutput() );

  MeshWriterPointer meshWriter = MeshWriterType::New();
  meshWriter->SetFileName( this->dataManager->GetOutputFile( "DisplacementFieldMeshWarperComponentTest.SinkAndSource.WarpedMesh.vtk" ) );
  meshWriter->SetInput( superElastixFilter->GetOutput< MeshType >( "MeshSink" ) );
  meshWriter->Update();

  MeshPointer inputMesh = itkDynamicCastInDebugMode< MeshType * >( meshReader->GetOutput() );
  MeshPointer outputMesh = superElastixFilter->GetOutput< MeshType >( "MeshSink" );

  DisplacementFieldType::Superclass::IndexType index;
  displacementField->TransformPhysicalPointToIndex(inputMesh->GetPoint(0), index);
  EXPECT_EQ(inputMesh->GetPoint(0)+displacementField->GetPixel(index), outputMesh->GetPoint(0));
  displacementField->TransformPhysicalPointToIndex(inputMesh->GetPoint(1), index);
  EXPECT_EQ(inputMesh->GetPoint(1)+displacementField->GetPixel(index), outputMesh->GetPoint(1));
  displacementField->TransformPhysicalPointToIndex(inputMesh->GetPoint(2), index);
  EXPECT_EQ(inputMesh->GetPoint(2)+displacementField->GetPixel(index), outputMesh->GetPoint(2));
  displacementField->TransformPhysicalPointToIndex(inputMesh->GetPoint(3), index);
  EXPECT_EQ(inputMesh->GetPoint(3)+displacementField->GetPixel(index), outputMesh->GetPoint(3));
  displacementField->TransformPhysicalPointToIndex(inputMesh->GetPoint(0), index);
}

} // namespace selx<|endoftext|>


<commit_before>
// Copyright (c) 2014 Quanta Research Cambridge, Inc.

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// 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.

#ifdef MATRIX_NT
#include "MmRequestNTProxy.h"
MmRequestNTProxy *mmdevice = 0;
#else
#ifdef MATRIX_TN
#include "MmRequestTNProxy.h"
MmRequestTNProxy *mmdevice = 0;
#endif
#endif
#include <MmIndicationWrapper.h>
#include <MmDebugIndicationWrapper.h>
#include <MmDebugRequestProxy.h>
#include <DmaConfigProxy.h>
#include <GeneratedTypes.h>
//#include <DmaIndicationWrapper.h>
#include <StdDmaIndication.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#include <math.h> // frexp(), fabs()
#include <assert.h>
#include "portalmat.h"
#include "mnist.h"

static int verbose = 0;

class SigmoidIndication;
class MmIndication;
class MmDebugIndication;

#define N 2

RbmRequestProxy *rbmdevice = 0;
MmDebugRequestProxy *mmdebug = 0;
SigmoidIndication *sigmoidindication = 0;
SigmoidRequestProxy *sigmoiddevice = 0;
TimerRequestProxy *timerdevice = 0;
MmIndication *mmdeviceIndication = 0;
MmDebugIndication *mmDebugIndication = 0;
TimerIndication *timerdeviceIndication = 0;
DmaConfigProxy *dmap = 0;
DmaIndicationWrapper *dmaIndication = 0;

long dotprod = 0;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s ", prefix);
    for (int i = 0; i < (len > 64 ? 64 : len) ; i++) {
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
	if (i % 4 == 3)
	  fprintf(stderr, " ");
    }
    fprintf(stderr, "\n");
}

void *dbgThread(void *)
{
  while (1) {
    sleep(2);
    if (dmap) {
      //dmap->getStateDbg(ChannelType_Read);
    }
    if (mmdebug) {
      fprintf(stderr, "Calling mmdebug->debug()\n");
      mmdebug->debug();
    }
  }
  return 0;
}

int main(int argc, const char **argv)
{
  unsigned int srcGen = 0;

  PortalPoller *poller = new PortalPoller();

  fprintf(stderr, "%s %s\n", __DATE__, __TIME__);

#ifdef MATRIX_NT
  mmdevice = new MmRequestNTProxy(IfcNames_MmRequestPortal);
#else
#ifdef MATRIX_TN
  mmdevice = new MmRequestTNProxy(IfcNames_MmRequestPortal);
#endif
#endif
  mmdebug = new MmDebugRequestProxy(IfcNames_MmDebugRequestPortal);
  mmdeviceIndication = new MmIndication(IfcNames_MmIndicationPortal);
  mmDebugIndication = new MmDebugIndication(IfcNames_MmDebugIndicationPortal);
  timerdevice = new TimerRequestProxy(IfcNames_TimerRequestPortal, poller);
  timerdeviceIndication = new TimerIndication(IfcNames_TimerIndicationPortal);

  dmap = new DmaConfigProxy(IfcNames_DmaConfigPortal);
  DmaManager *dma = new DmaManager(dmap);
  dmaIndication = new DmaIndication(dma, IfcNames_DmaIndicationPortal);

  if(sem_init(&mul_sem, 1, 0)){
    fprintf(stderr, "failed to init mul_sem\n");
    return -1;
  }

  pthread_t tid;
  fprintf(stderr, "creating exec thread\n");
  if(pthread_create(&tid, NULL,  portalExec, NULL)){
   fprintf(stderr, "error creating exec thread\n");
   exit(1);
  }

  long req_freq = 100000000;
  long freq = 0;
  setClockFrequency(0, req_freq, &freq);
  fprintf(stderr, "Requested FCLK[0]=%d actually %d\n", req_freq, freq);

  matAllocator = new PortalMatAllocator(dmap, dma);

#define LARGE_MAT
#ifdef LARGE_MAT
#ifdef BSIM
  int A = 64;
  int B = 512;
#else
  int A = 256;
  int B = 2048;
#endif
  if (argc > 1) {
    B = strtoul(argv[1], 0, 0);
    A = 2*B;
  }
  cv::Mat m1(A,B,CV_32F);
  cv::Mat m2(B,A,CV_32F);
  float v = 0;
  for(int a = 0; a < A; a++){
    for(int b = 0; b < B; b++){
      m2.at<float>(b,a) = (A*B)+v;
      m1.at<float>(a,b) = v;
      v++;
    }
  }
#else
  cv::Mat m1 = (cv::Mat_<float>(4,8) <<
		11,12,13,14,15,16,17,18,
		21,22,23,24,25,26,27,28,
		31,32,33,34,35,36,37,38,
		41,42,43,44,45,46,47,48
		);
  cv::Mat m2 = (cv::Mat_<float>(8,4) <<
		51,62,53,54,
		55,56,57,58,
		61,62,63,64,
		65,66,67,68,
		71,72,73,74,
		75,76,77,78,
		81,82,83,84,
		85,86,87,88
		);
#endif

  FILE *octave_file = fopen("foo.m", "w");

  fprintf(stderr, "OpenCV matmul\n");
  start_timer(0);
  cv::Mat  m3 = m1 * m2;
  uint64_t opencv_hw_cycles = lap_timer(0);

  PortalMat tm3;
  fprintf(stderr, "Naive matmul\n");
  start_timer(0);
  tm3.naive_mul(m1,m2, octave_file);
  uint64_t naive_hw_cycles = lap_timer(0);

  bool sane = 1;
  if (1) {
    fprintf(stderr, "DumpMat\n");
    dumpMatOctave<float>("m1",  "%10.5f", m1,  octave_file);
    dumpMatOctave<float>("m2",  "%10.5f", m2,  octave_file);
    dumpMatOctave<float>("m3",  "%10.5f", m3,  octave_file);
    dumpMatOctave<float>("tm3", "%10.5f", tm3, octave_file);
    fclose(octave_file);
    sane = tm3.compare(m3, 0, 0, 0.0001, 0, false);
    fprintf(stderr, "sane=%d\n", sane);
    fflush(stdout);
  }

#ifdef MATRIX_TN
  fprintf(stderr, "pm1t\n");
  PortalMat pm1t(m1.t());
  fprintf(stderr, "pm2\n");
  PortalMat pm2(m2);
#else
#ifdef MATRIX_NT
  fprintf(stderr, "pm1\n");
  PortalMat pm1(m1);
  fprintf(stderr, "pm2t\n");
  PortalMat pm2t(m2.t());
#endif
#endif
  PortalMat pm3;

  // now reference the matrices so we do not count that in the timer
#ifdef MATRIX_TN
  pm1t.reference();
  pm2.reference();
#else
#ifdef MATRIX_NT
  pm1.reference();
  pm2t.reference();
#endif
#endif
  pm3.create(m1.rows, m2.cols, CV_32F);
  pm3.reference();

  pthread_t dbgtid;
  fprintf(stderr, "creating debug thread\n");
  if(pthread_create(&dbgtid, NULL,  dbgThread, NULL)){
   fprintf(stderr, "error creating debug thread\n");
   exit(1);
  }

  fprintf(stderr, "HW matmul\n");
  start_timer(0);
#ifdef MATRIX_TN
  pm3.multf(pm1t, pm2, mmdeviceIndication);
#else
#ifdef MATRIX_NT
  pm3.multf(pm1, pm2t, mmdeviceIndication);
#endif
#endif
  uint64_t hw_cycles = lap_timer(0);
  uint64_t read_beats = dma->show_mem_stats(ChannelType_Read);
  uint64_t write_beats = dma->show_mem_stats(ChannelType_Write);
  float read_util = (float)read_beats/(float)mmdeviceIndication->ccnt;
  float write_util = (float)write_beats/(float)mmdeviceIndication->ccnt;
  float read_bw = read_util * N * 4 * (float)freq / 1.0e9;
  float write_bw = write_util * N * 4 * (float)freq / 1.0e9;
  float macs = m1.rows * m2.rows * m2.cols;
  fprintf(stderr, "Bus frequency %f MHz\n", (float)freq / 1.0e6);
  fprintf(stderr, "memory read  beats %f utilization %f (beats/cycle), bandwidth %f (GB/s)\n", (float)read_beats, read_util, read_bw);
  fprintf(stderr, "memory write beats %f utilization %f (beats/cycle), bandwidth %f (GB/s)\n", (float)write_beats, write_util, write_bw);
  fprintf(stderr, "Throughput %f macs/cycle %f GFLOP/s\n",
	  (float)macs / (float)mmdeviceIndication->ccnt,
	  2.0 * (float)macs / (float)mmdeviceIndication->ccnt * freq / 1.0e9);
  fprintf(stderr, "Time %f cycles, opencv matmul %f cycles (speedup %f), naive matmul %f cycles (speedup %f)\n",
	  (float)mmdeviceIndication->ccnt,
	  (float)opencv_hw_cycles, (float)opencv_hw_cycles/(float)mmdeviceIndication->ccnt,
	  (float)naive_hw_cycles, (float)naive_hw_cycles/(float)mmdeviceIndication->ccnt);

  if (0) {
    dumpMat<float>("pm3", "%5.1f", pm3);
    dumpMat<float>(" m3", "%5.1f", m3);
  }
  //bool eq = std::equal(m3.begin<float>(), m3.end<float>(), pm3.begin<float>());
  bool eq = pm3.compare(m3);
  fprintf(stderr, "XXXXXXXXXXXXXXXXXXXXXXXXXX eq=%d\n", eq);
  //device->finish();
  exit(!eq&&!sane);
}
<commit_msg>progress in getting testmm back up and running<commit_after>
// Copyright (c) 2014 Quanta Research Cambridge, Inc.

// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// 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.

#ifdef MATRIX_NT
#include "MmRequestNTProxy.h"
MmRequestNTProxy *mmdevice = 0;
#else
#ifdef MATRIX_TN
#include "MmRequestTNProxy.h"
MmRequestTNProxy *mmdevice = 0;
#endif
#endif
#include <MmIndicationWrapper.h>
#include <MmDebugIndicationWrapper.h>
#include <MmDebugRequestProxy.h>
#include <DmaConfigProxy.h>
#include <GeneratedTypes.h>
//#include <DmaIndicationWrapper.h>
#include <StdDmaIndication.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#include <math.h> // frexp(), fabs()
#include <assert.h>
#include "portalmat.h"
#include "mnist.h"

static int verbose = 0;

class SigmoidIndication;
class MmIndication;
class MmDebugIndication;

#define N 2

RbmRequestProxy *rbmdevice = 0;
MmDebugRequestProxy *mmdebug = 0;
SigmoidIndication *sigmoidindication = 0;
SigmoidRequestProxy *sigmoiddevice = 0;
TimerRequestProxy *timerdevice = 0;
MmIndication *mmdeviceIndication = 0;
MmDebugIndication *mmDebugIndication = 0;
TimerIndication *timerdeviceIndication = 0;
DmaConfigProxy *dmap = 0;
DmaIndicationWrapper *dmaIndication = 0;

long dotprod = 0;

void dump(const char *prefix, char *buf, size_t len)
{
    fprintf(stderr, "%s ", prefix);
    for (int i = 0; i < (len > 64 ? 64 : len) ; i++) {
	fprintf(stderr, "%02x", (unsigned char)buf[i]);
	if (i % 4 == 3)
	  fprintf(stderr, " ");
    }
    fprintf(stderr, "\n");
}

void *dbgThread(void *)
{
  while (1) {
    sleep(2);
    if (dmap) {
      //dmap->getStateDbg(ChannelType_Read);
    }
    if (mmdebug) {
      fprintf(stderr, "Calling mmdebug->debug()\n");
      mmdebug->debug();
    }
  }
  return 0;
}

int main(int argc, const char **argv)
{
  unsigned int srcGen = 0;

  PortalPoller *poller = new PortalPoller();

  fprintf(stderr, "%s %s\n", __DATE__, __TIME__);

#ifdef MATRIX_NT
  mmdevice = new MmRequestNTProxy(IfcNames_MmRequestPortal);
#else
#ifdef MATRIX_TN
  mmdevice = new MmRequestTNProxy(IfcNames_MmRequestPortal);
#endif
#endif
  mmdebug = new MmDebugRequestProxy(IfcNames_MmDebugRequestPortal);
  mmdeviceIndication = new MmIndication(IfcNames_MmIndicationPortal);
  mmDebugIndication = new MmDebugIndication(IfcNames_MmDebugIndicationPortal);
  timerdevice = new TimerRequestProxy(IfcNames_TimerRequestPortal, poller);
  timerdeviceIndication = new TimerIndication(IfcNames_TimerIndicationPortal);

  dmap = new DmaConfigProxy(IfcNames_DmaConfigPortal);
  DmaManager *dma = new DmaManager(dmap);
  dmaIndication = new DmaIndication(dma, IfcNames_DmaIndicationPortal);

  if(sem_init(&mul_sem, 1, 0)){
    fprintf(stderr, "failed to init mul_sem\n");
    return -1;
  }

  pthread_t tid;
  fprintf(stderr, "creating exec thread\n");
  if(pthread_create(&tid, NULL,  portalExec, NULL)){
   fprintf(stderr, "error creating exec thread\n");
   exit(1);
  }

  long req_freq = 100000000;
  long freq = 0;
  setClockFrequency(0, req_freq, &freq);
  fprintf(stderr, "Requested FCLK[0]=%d actually %d\n", req_freq, freq);

  matAllocator = new PortalMatAllocator(dmap, dma);

#define LARGE_MAT
#ifdef LARGE_MAT
#ifdef BSIM
  int A = 64;
  int B = 128;
#else
  int A = 256;
  int B = 2048;
#endif
  if (argc > 1) {
    B = strtoul(argv[1], 0, 0);
    A = 2*B;
  }
  srand(A*B);
  cv::Mat m1(A,B,CV_32F);
  cv::Mat m2(B,A,CV_32F);
  for(int a = 0; a < A; a++){
    for(int b = 0; b < B; b++){
      float v = (float)(rand() % 10);
      m2.at<float>(b,a) = (A*B)+v;
      m1.at<float>(a,b) = v;
    }
  }
#else
  cv::Mat m1 = (cv::Mat_<float>(4,8) <<
		11,12,13,14,15,16,17,18,
		21,22,23,24,25,26,27,28,
		31,32,33,34,35,36,37,38,
		41,42,43,44,45,46,47,48
		);
  cv::Mat m2 = (cv::Mat_<float>(8,4) <<
		51,62,53,54,
		55,56,57,58,
		61,62,63,64,
		65,66,67,68,
		71,72,73,74,
		75,76,77,78,
		81,82,83,84,
		85,86,87,88
		);
#endif

  FILE *octave_file = fopen("foo.m", "w");

  fprintf(stderr, "OpenCV matmul\n");
  start_timer(0);
  cv::Mat  m3 = m1 * m2;
  uint64_t opencv_hw_cycles = lap_timer(0);

  PortalMat tm3;
  fprintf(stderr, "Naive matmul\n");
  start_timer(0);
  tm3.naive_mul(m1,m2, octave_file);
  uint64_t naive_hw_cycles = lap_timer(0);

  bool sane = 1;
  if (1) {
    fprintf(stderr, "DumpMat\n");
    dumpMatOctave<float>("m1",  "%10.5f", m1,  octave_file);
    dumpMatOctave<float>("m2",  "%10.5f", m2,  octave_file);
    dumpMatOctave<float>("m3",  "%10.5f", m3,  octave_file);
    dumpMatOctave<float>("tm3", "%10.5f", tm3, octave_file);
    fclose(octave_file);
    sane = tm3.compare(m3, 0, 0, 0.0001, 0, false);
    fprintf(stderr, "sane=%d\n", sane);
    fflush(stdout);
  }

#ifdef MATRIX_TN
  fprintf(stderr, "pm1t\n");
  PortalMat pm1t(m1.t());
  fprintf(stderr, "pm2\n");
  PortalMat pm2(m2);
#else
#ifdef MATRIX_NT
  fprintf(stderr, "pm1\n");
  PortalMat pm1(m1);
  fprintf(stderr, "pm2t\n");
  PortalMat pm2t(m2.t());
#endif
#endif
  PortalMat pm3;

  // now reference the matrices so we do not count that in the timer
#ifdef MATRIX_TN
  pm1t.reference();
  pm2.reference();
#else
#ifdef MATRIX_NT
  pm1.reference();
  pm2t.reference();
#endif
#endif
  pm3.create(m1.rows, m2.cols, CV_32F);
  pm3.reference();

  pthread_t dbgtid;
  fprintf(stderr, "creating debug thread\n");
  if(pthread_create(&dbgtid, NULL,  dbgThread, NULL)){
   fprintf(stderr, "error creating debug thread\n");
   exit(1);
  }

  fprintf(stderr, "HW matmul\n");
  start_timer(0);
#ifdef MATRIX_TN
  pm3.multf(pm1t, pm2, mmdeviceIndication);
#else
#ifdef MATRIX_NT
  pm3.multf(pm1, pm2t, mmdeviceIndication);
#endif
#endif
  uint64_t hw_cycles = lap_timer(0);
  uint64_t read_beats = dma->show_mem_stats(ChannelType_Read);
  uint64_t write_beats = dma->show_mem_stats(ChannelType_Write);
  float read_util = (float)read_beats/(float)mmdeviceIndication->ccnt;
  float write_util = (float)write_beats/(float)mmdeviceIndication->ccnt;
  float read_bw = read_util * N * 4 * (float)freq / 1.0e9;
  float write_bw = write_util * N * 4 * (float)freq / 1.0e9;
  float macs = m1.rows * m2.rows * m2.cols;
  fprintf(stderr, "Bus frequency %f MHz\n", (float)freq / 1.0e6);
  fprintf(stderr, "memory read  beats %f utilization %f (beats/cycle), bandwidth %f (GB/s)\n", (float)read_beats, read_util, read_bw);
  fprintf(stderr, "memory write beats %f utilization %f (beats/cycle), bandwidth %f (GB/s)\n", (float)write_beats, write_util, write_bw);
  fprintf(stderr, "Throughput %f macs/cycle %f GFLOP/s\n",
	  (float)macs / (float)mmdeviceIndication->ccnt,
	  2.0 * (float)macs / (float)mmdeviceIndication->ccnt * freq / 1.0e9);
  fprintf(stderr, "Time %f cycles, opencv matmul %f cycles (speedup %f), naive matmul %f cycles (speedup %f)\n",
	  (float)mmdeviceIndication->ccnt,
	  (float)opencv_hw_cycles, (float)opencv_hw_cycles/(float)mmdeviceIndication->ccnt,
	  (float)naive_hw_cycles, (float)naive_hw_cycles/(float)mmdeviceIndication->ccnt);

  if (0) {
    dumpMat<float>("pm3", "%5.1f", pm3);
    dumpMat<float>(" m3", "%5.1f", m3);
  }
  bool eq = pm3.compare(m3);
  fprintf(stderr, "XXXXXXXXXXXXXXXXXXXXXXXXXX eq=%d\n", eq);
  exit(!(eq&&sane));
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014, Julien Bernard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS 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 <game/graphics/Group.h>

#include "config.h"

int main() {
  // initialize
  game::Group group;
  sf::RenderWindow window(sf::VideoMode(1024, 768), "Foo (version " GAME_VERSION ")");
  window.setKeyRepeatEnabled(false);

  // load resources

  // add entities

  // main loop
  sf::Clock clock;

  while (window.isOpen()) {
    // input
    sf::Event event;

    while (window.pollEvent(event)) {
      if (event.type == sf::Event::Closed) {
        window.close();
      } else if (event.type == sf::Event::KeyPressed) {

        switch (event.key.code) {
          case sf::Keyboard::Escape:
            window.close();
            break;

          default:
            break;
        }

      }
    }

    // update
    sf::Time elapsed = clock.restart();
    group.update(elapsed.asSeconds());

    // render
    window.clear(sf::Color::White);
    group.render(window);
    window.display();
  }

  return 0;
}
<commit_msg>improve the template<commit_after>/*
 * Copyright (c) 2014, Julien Bernard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS 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 <game/graphics/Group.h>

#include "config.h"

int main() {
  // initialize

  static constexpr unsigned INITIAL_WIDTH = 1024;
  static constexpr unsigned INITIAL_HEIGHT = 768;

  sf::RenderWindow window(sf::VideoMode(INITIAL_WIDTH, INITIAL_HEIGHT), "Game template (version " GAME_VERSION ")");
  window.setKeyRepeatEnabled(false);

  // load resources

  // add entities

  game::Group group;

  // main loop
  sf::Clock clock;

  while (window.isOpen()) {
    // input
    sf::Event event;

    while (window.pollEvent(event)) {
      if (event.type == sf::Event::Closed) {
        window.close();
      } else if (event.type == sf::Event::KeyPressed) {

        switch (event.key.code) {
          case sf::Keyboard::Escape:
            window.close();
            break;

          default:
            break;
        }

      }
    }

    // update
    sf::Time elapsed = clock.restart();
    group.update(elapsed.asSeconds());

    // render
    window.clear(sf::Color::White);
    group.render(window);
    window.display();
  }

  return 0;
}
<|endoftext|>


<commit_before>/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alpaka is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/

#pragma once

#include <alpaka/block/sync/Traits.hpp> // SyncBlockThreads

#include <alpaka/core/Common.hpp>       // ALPAKA_FN_ACC

#include <boost/core/ignore_unused.hpp> // boost::ignore_unused

namespace alpaka
{
    namespace block
    {
        namespace sync
        {
            //#############################################################################
            //! The no op block synchronization.
            //#############################################################################
            class BlockSyncNoOp
            {
            public:
                using BlockSyncBase = BlockSyncNoOp;

                //-----------------------------------------------------------------------------
                //! Default constructor.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC BlockSyncNoOp() = default;
                //-----------------------------------------------------------------------------
                //! Copy constructor.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC BlockSyncNoOp(BlockSyncNoOp const &) = delete;
                //-----------------------------------------------------------------------------
                //! Move constructor.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC BlockSyncNoOp(BlockSyncNoOp &&) = delete;
                //-----------------------------------------------------------------------------
                //! Copy assignment operator.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC auto operator=(BlockSyncNoOp const &) -> BlockSyncNoOp & = delete;
                //-----------------------------------------------------------------------------
                //! Move assignment operator.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC auto operator=(BlockSyncNoOp &&) -> BlockSyncNoOp & = delete;
                //-----------------------------------------------------------------------------
                //! Destructor.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC /*virtual*/ ~BlockSyncNoOp() = default;
            };

            namespace traits
            {
                //#############################################################################
                //!
                //#############################################################################
                template<>
                struct SyncBlockThreads<
                    BlockSyncNoOp>
                {
                    //-----------------------------------------------------------------------------
                    //
                    //-----------------------------------------------------------------------------
                    ALPAKA_FN_ACC static auto syncBlockThreads(
                        block::sync::BlockSyncNoOp const & blockSync)
                    -> void
                    {
                        boost::ignore_unused(blockSync);

                        // Nothing to do.
                    }
                };
            }
        }
    }
}
<commit_msg>fix nvcc host device warning<commit_after>/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alpaka is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/

#pragma once

#include <alpaka/block/sync/Traits.hpp> // SyncBlockThreads

#include <alpaka/core/Common.hpp>       // ALPAKA_FN_ACC

#include <boost/core/ignore_unused.hpp> // boost::ignore_unused

namespace alpaka
{
    namespace block
    {
        namespace sync
        {
            //#############################################################################
            //! The no op block synchronization.
            //#############################################################################
            class BlockSyncNoOp
            {
            public:
                using BlockSyncBase = BlockSyncNoOp;

                //-----------------------------------------------------------------------------
                //! Default constructor.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC BlockSyncNoOp() = default;
                //-----------------------------------------------------------------------------
                //! Copy constructor.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC BlockSyncNoOp(BlockSyncNoOp const &) = delete;
                //-----------------------------------------------------------------------------
                //! Move constructor.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC BlockSyncNoOp(BlockSyncNoOp &&) = delete;
                //-----------------------------------------------------------------------------
                //! Copy assignment operator.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC auto operator=(BlockSyncNoOp const &) -> BlockSyncNoOp & = delete;
                //-----------------------------------------------------------------------------
                //! Move assignment operator.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC auto operator=(BlockSyncNoOp &&) -> BlockSyncNoOp & = delete;
                //-----------------------------------------------------------------------------
                //! Destructor.
                //-----------------------------------------------------------------------------
                ALPAKA_FN_ACC /*virtual*/ ~BlockSyncNoOp() = default;
            };

            namespace traits
            {
                //#############################################################################
                //!
                //#############################################################################
                template<>
                struct SyncBlockThreads<
                    BlockSyncNoOp>
                {
                    //-----------------------------------------------------------------------------
                    //
                    //-----------------------------------------------------------------------------
                    ALPAKA_FN_ACC static auto syncBlockThreads(
                        block::sync::BlockSyncNoOp const & /*blockSync*/)
                    -> void
                    {
                        //boost::ignore_unused(blockSync);
                        // Nothing to do.
                    }
                };
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>[CP-SAT] fix cores<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2019 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include <iostream>
#include <sstream>
#include <string>
#include <thread>

#include <franka/exception.h>
#include <franka/vacuum_gripper.h>

/**
 * @example vacuum_object.cpp
 * An example showing how to control FRANKA's vacuum gripper.
 */

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage: ./vacuum_object <vacuum-gripper-hostname>" << std::endl;
    return -1;
  }

  try {
    franka::VacuumGripper vacuum_gripper(argv[1]);

    // Print a vacuum gripper state.
    franka::VacuumGripperState vacuum_gripper_state = vacuum_gripper.readOnce();
    std::cout << "Vacuum gripper state: " << vacuum_gripper_state << std::endl;

    // Vacuum the object.
    if (!vacuum_gripper.vacuum(100, 0, std::chrono::milliseconds(1000))) {
      std::cout << "Failed to vacuum the object." << std::endl;
      return -1;
    }

    // Wait 3s and check afterwards, if the object is still grasped.
    std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(3000));

    vacuum_gripper_state = vacuum_gripper.readOnce();
    if (!vacuum_gripper_state.in_control_range) {
      std::cout << "Object lost." << std::endl;
      return -1;
    }

    std::cout << "Vacuumed object, will release it now." << std::endl;
    vacuum_gripper.dropOff(std::chrono::milliseconds(1000));
  } catch (franka::Exception const& e) {
    std::cout << e.what() << std::endl;
    return -1;
  }

  return 0;
}
<commit_msg>Improve vacuum example.<commit_after>// Copyright (c) 2019 Franka Emika GmbH
// Use of this source code is governed by the Apache-2.0 license, see LICENSE
#include <iostream>
#include <sstream>
#include <string>
#include <thread>

#include <franka/exception.h>
#include <franka/vacuum_gripper.h>

/**
 * @example vacuum_object.cpp
 * An example showing how to control FRANKA's vacuum gripper.
 */

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage: ./vacuum_object <vacuum-gripper-hostname>" << std::endl;
    return -1;
  }

  try {
    franka::VacuumGripper vacuum_gripper(argv[1]);

    // Print a vacuum gripper state.
    franka::VacuumGripperState vacuum_gripper_state = vacuum_gripper.readOnce();
    std::cout << "Initial vacuum gripper state: " << vacuum_gripper_state << std::endl;

    // Vacuum the object.
    if (!vacuum_gripper.vacuum(100, 0, std::chrono::milliseconds(1000))) {
      std::cout << "Failed to vacuum the object." << std::endl;
      return -1;
    }

    vacuum_gripper_state = vacuum_gripper.readOnce();
    std::cout << "Vacuum gripper state after applying vacuum: " << vacuum_gripper_state
              << std::endl;

    // Wait 3s and check afterwards, if the object is still grasped.
    std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(3000));

    vacuum_gripper_state = vacuum_gripper.readOnce();
    if (!vacuum_gripper_state.in_control_range) {
      std::cout << "Object lost." << std::endl;
      return -1;
    }

    std::cout << "Vacuumed object, will release it now." << std::endl;
    vacuum_gripper.dropOff(std::chrono::milliseconds(1000));
  } catch (franka::Exception const& e) {
    std::cout << e.what() << std::endl;
    return -1;
  }

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>use LanguageTag<commit_after><|endoftext|>


<commit_before>#include "ins_sdk.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include <algorithm>
#include <vector>
#include <iostream>

using namespace galaxy::ins::sdk;

int main(int argc, char* argv[]) {
    std::vector<std::string> members;
    if (argc < 2) {
        fprintf(stderr, "./sample [read|write]\n");
        return 1;
    }
    if (strcmp("write", argv[1]) == 0) {
        fprintf(stderr, "write test\n");
        InsSDK::ParseFlagFromArgs(argc, argv, &members);
        InsSDK sdk(members);
        char key_buf[1024] = {'\0'};
        char value_buf[1024] = {'\0'};
        SDKError err;
        for (int i=1; i<=100000; i++) {
            snprintf(key_buf, sizeof(key_buf), "key_%d", i);
            snprintf(value_buf, sizeof(value_buf), "value_%d", i);
            sdk.Put(key_buf, value_buf, &err);
            if (err == kClusterDown) {
                i--;
                printf("try put again: %s", key_buf);
                sleep(2);
            }
            printf("%s\n", key_buf);
        }
    } else if(strcmp("read", argv[1]) == 0) {
        fprintf(stderr, "read test\n");
        InsSDK::ParseFlagFromArgs(argc, argv, &members);
        InsSDK sdk(members);
        char key_buf[1024] = {'\0'};
        char value_buf[1024] = {'\0'};
        SDKError err;
        for (int i=1; i<=100000; i++) {
            snprintf(key_buf, sizeof(key_buf), "key_%d", i);
            snprintf(value_buf, sizeof(value_buf), "value_%d", i);
            std::string value;
            sdk.Get(key_buf, &value, &err);
            if (err == kClusterDown) {
                i--;
                printf("try get again: %s", key_buf);
                sleep(2);
            }
            printf("%s\n", value_buf);
        }
    }
    return 0;
}

<commit_msg>fix sample<commit_after>#include "ins_sdk.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include <algorithm>
#include <vector>
#include <iostream>

using namespace galaxy::ins::sdk;

int main(int argc, char* argv[]) {
    std::vector<std::string> members;
    if (argc < 2) {
        fprintf(stderr, "./sample [read|write]\n");
        return 1;
    }
    if (strcmp("write", argv[1]) == 0) {
        fprintf(stderr, "write test\n");
        InsSDK::ParseFlagFromArgs(argc, argv, &members);
        InsSDK sdk(members);
        char key_buf[1024] = {'\0'};
        char value_buf[1024] = {'\0'};
        SDKError err;
        for (int i=1; i<=100000; i++) {
            snprintf(key_buf, sizeof(key_buf), "key_%d", i);
            snprintf(value_buf, sizeof(value_buf), "value_%d", i);
            sdk.Put(key_buf, value_buf, &err);
            if (err == kClusterDown) {
                i--;
                printf("try put again: %s\n", key_buf);
                sleep(2);
                continue;
            }
            printf("%s\n", key_buf);
        }
    } else if(strcmp("read", argv[1]) == 0) {
        fprintf(stderr, "read test\n");
        InsSDK::ParseFlagFromArgs(argc, argv, &members);
        InsSDK sdk(members);
        char key_buf[1024] = {'\0'};
        char value_buf[1024] = {'\0'};
        SDKError err;
        for (int i=1; i<=100000; i++) {
            snprintf(key_buf, sizeof(key_buf), "key_%d", i);
            snprintf(value_buf, sizeof(value_buf), "value_%d", i);
            std::string value;
            sdk.Get(key_buf, &value, &err);
            if (err == kClusterDown) {
                i--;
                printf("try get again: %s", key_buf);
                sleep(2);
                continue;
            }
            printf("%s\n", value_buf);
        }
    }
    return 0;
}

<|endoftext|>