text:
#include "vtkboneFiniteElementModel.h"
#include "vtkboneMacros.h"
#include "vtkboneConstraintCollection.h"
#include "vtkboneConstraint.h"
#include "vtkboneConstraintUtilities.h"
#include "vtkboneMaterialTable.h"
#include "vtkObjectFactory.h"
#include "vtkIdTypeArray.h"
#include "vtkDataArrayCollection.h"
#include "vtkPolyData.h"
#include "vtkCell.h"
#include "vtkGenericCell.h"
#include "vtkCellArray.h"
#include "vtkDataArray.h"
#include "vtkIntArray.h"
#include "vtkFloatArray.h"
#include "vtkPoints.h"
#include "vtkPointData.h"
#include "vtkDoubleArray.h"
#include "vtkCharArray.h"
#include "vtkSelection.h"
#include "vtkExtractSelection.h"
#include "vtkCellData.h"
#include "vtkConvertSelection.h"
#include "vtkboneSelectionUtilities.h"
#include "vtkDataSetAttributes.h"
#include "vtkGeometryFilter.h"
#include "vtkSelectionNode.h"
#include "vtkSmartPointer.h"
#include "vtkboneMacros.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <map>
#include <cassert>

vtkStandardNewMacro (vtkboneFiniteElementModel);

vtkCxxSetObjectMacro (vtkboneFiniteElementModel, Constraints, vtkboneConstraintCollection);
vtkCxxSetObjectMacro (vtkboneFiniteElementModel, MaterialTable, vtkboneMaterialTable);
vtkCxxSetObjectMacro (vtkboneFiniteElementModel, ConvergenceSet, vtkboneConstraint);
vtkCxxSetObjectMacro (vtkboneFiniteElementModel, NodeSets, vtkDataArrayCollection);
vtkCxxSetObjectMacro (vtkboneFiniteElementModel, ElementSets, vtkDataArrayCollection);
vtkCxxSetObjectMacro (vtkboneFiniteElementModel, GaussPointData, vtkDataArrayCollection);

const char* const ElementType_s[] = {
    "UNKNOWN",
    "TETRAHEDRON",
    "HEXAHEDRON",
    "MIXED"};
vtkboneGetAsStringMacro (vtkboneFiniteElementModel, ElementType);

//----------------------------------------------------------------------------
vtkboneFiniteElementModel::vtkboneFiniteElementModel()
{
  this->Constraints = vtkboneConstraintCollection::New();
  this->Constraints->Register(this);
  this->Constraints->Delete();  // Otherwise reference count is 2
  this->MaterialTable = vtkboneMaterialTable::New();
  this->MaterialTable->Register(this);
  this->MaterialTable->Delete();  // Otherwise reference count is 2
  this->ConvergenceSet = NULL;
  this->Name = NULL;
  this->History = NULL;
  this->Log = NULL;
  this->NodeSets = vtkDataArrayCollection::New();
  this->NodeSets->Register(this);
  this->NodeSets->Delete();  // Otherwise reference count is 2
  this->ElementSets = vtkDataArrayCollection::New();
  this->ElementSets->Register(this);
  this->ElementSets->Delete();  // Otherwise reference count is 2
  this->GaussPointData = vtkDataArrayCollection::New();
  this->GaussPointData->Register(this);
  this->GaussPointData->Delete();  // Otherwise reference count is 2
}

//----------------------------------------------------------------------------
vtkboneFiniteElementModel::~vtkboneFiniteElementModel()
  {
  this->SetConstraints(NULL);
  this->SetMaterialTable(NULL);
  this->SetConvergenceSet(NULL);
  this->SetName(NULL);
  this->SetHistory(NULL);
  this->SetLog(NULL);
  this->SetNodeSets(NULL);
  this->SetElementSets(NULL);
  this->SetGaussPointData(NULL);
  }

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

  if (this->History)
    { os << indent << "History :\n" << this->History << "\n"; }
  else
    { os << indent << "History : (None)\n"; }
  if (this->NodeSets)
    {
    os << indent << "Node Sets :\n";
    this->NodeSets->PrintSelf(os, indent.GetNextIndent());
    }
  else
    { os << indent << "Node Sets : (None)\n"; }
  if (this->ElementSets)
    {
    os << indent << "Element Sets :\n";
    this->ElementSets->PrintSelf(os, indent.GetNextIndent());
    }
  else
    { os << indent << "Element Sets : (None)\n"; }
  if (this->GaussPointData)
    {
    os << indent << "Gauss Point Data :\n";
    this->GaussPointData->PrintSelf(os, indent.GetNextIndent());
    }
  else
    { os << indent << "Gauss Point Data : (None)\n"; }

    {
    vtkboneConstraint *tmp;
    vtkIdType num = this->Constraints->GetNumberOfItems();
    os << indent << "Number Of Contraints : " << num << endl;
    for (vtkIdType i=0; i<num; i++)
      {
      if ((tmp = vtkboneConstraint::SafeDownCast(this->Constraints->GetItemAsObject(i))))
        {
        if (tmp->GetName())
          os << indent << indent << i << " : " << tmp->GetName() << endl;
        else
          os << indent << indent << i << " : " << tmp << endl;
        }
      }
    }

  if (this->MaterialTable)
    {
    this->MaterialTable->PrintSelf(os, indent.GetNextIndent());
    }

}

//----------------------------------------------------------------------------
void vtkboneFiniteElementModel::AppendHistory(const char* s)
{
  if (s == NULL) return;
  std::ostringstream newHistory;
  if (this->History != NULL)
    {
    size_t len = strlen(this->History);
    if (len > 0)
      {
      newHistory << this->History;
      if (this->History[len - 1] != '\n')
        { newHistory << "\n"; }
      }
    }
  boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
  newHistory << now << " " << s;
  this->SetHistory(newHistory.str().c_str());
}

//----------------------------------------------------------------------------
void vtkboneFiniteElementModel::AppendLog(const char* s)
{
  if (s == NULL) return;
  std::ostringstream newLog;
  if (this->Log != NULL)
    {
    size_t len = strlen(this->Log);
    if (len > 0)
      {
      newLog << this->Log;
      if (this->Log[len - 1] != '\n')
        { newLog << "\n"; }
      newLog << "\n";
      }
    }
  boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
  newLog << now << "\n" << s;
  this->SetLog(newLog.str().c_str());
}

//----------------------------------------------------------------------------
void vtkboneFiniteElementModel::AddNodeSet (vtkIdTypeArray *ids)
{
  if (ids->GetName() == NULL || strlen(ids->GetName()) == 0)
    {
    vtkErrorMacro(<<"Attempt to add NodeSet with no name.");
    return;
    }
  if (vtkIdTypeArray* existingNodeSet = this->GetNodeSet(ids->GetName()))
    {
    this->NodeSets->RemoveItem (existingNodeSet);
    }
  this->NodeSets->AddItem (ids);
}

//----------------------------------------------------------------------------
void vtkboneFiniteElementModel::AddElementSet (vtkIdTypeArray *ids)
{
  if (ids->GetName() == NULL || strlen(ids->GetName()) == 0)
    {
    vtkErrorMacro(<<"Attempt to add ElementSet with no name.");
    return;
    }
  if (vtkIdTypeArray* existingElementSet = this->GetElementSet(ids->GetName()))
    {
    this->ElementSets->RemoveItem (existingElementSet);
    }
  this->ElementSets->AddItem (ids);
}

//----------------------------------------------------------------------------
vtkIdTypeArray* vtkboneFiniteElementModel::GetNodeSet (const char* nodeSetName)
{
  vtkCollectionSimpleIterator cookie;
  this->NodeSets->InitTraversal(cookie);
  while (vtkDataArray* d = this->NodeSets->GetNextDataArray(cookie))
    {
    if (strcmp(d->GetName(),nodeSetName) == 0)
      {
      return vtkIdTypeArray::SafeDownCast(d);
      }
    }
  return NULL;
}

//----------------------------------------------------------------------------
vtkIdTypeArray* vtkboneFiniteElementModel::GetElementSet (const char* elementSetName)
{
  vtkCollectionSimpleIterator cookie;
  this->ElementSets->InitTraversal(cookie);
  while (vtkDataArray* d = this->ElementSets->GetNextDataArray(cookie))
    {
    if (strcmp(d->GetName(),elementSetName) == 0)
      {
      return vtkIdTypeArray::SafeDownCast(d);
      }
    }
  return NULL;
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::RemoveNodeSet (const char* nodeSetName)
{
  vtkIdTypeArray* nodeSet = this->GetNodeSet(nodeSetName);
  if (nodeSet)
    {
    this->NodeSets->RemoveItem(nodeSet);
    return VTK_OK;
    }
  else
    {
    return VTK_ERROR;
    }
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::RemoveElementSet (const char* elementSetName)
{
  vtkIdTypeArray* elementSet = this->GetElementSet(elementSetName);
  if (elementSet)
    {
    this->ElementSets->RemoveItem(elementSet);
    return VTK_OK;
    }
  else
    {
    return VTK_ERROR;
    }
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::GetAssociatedElementsFromNodeSet
(const char *nodeSetName, vtkIdTypeArray* ids)
{
  ids->Initialize();
  vtkIdTypeArray* nodeIds = this->GetNodeSet (nodeSetName);
  if (!nodeIds)
    {
    return VTK_ERROR;
    }
  ids->SetName (nodeIds->GetName());
  vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New();
  vtkboneSelectionUtilities::PointSelectionFromIds (selection, this, nodeIds);
  vtkboneSelectionUtilities::GetContainingCells (selection, this, ids);
  return VTK_OK;
}

//----------------------------------------------------------------------------
vtkIdTypeArray* vtkboneFiniteElementModel::GetAssociatedElementsFromNodeSet
(const char *nodeSetName)
{
  vtkIdTypeArray* ids = vtkIdTypeArray::New();
  int returnVal = this->GetAssociatedElementsFromNodeSet (nodeSetName, ids);
  if (returnVal != VTK_OK)
    {
    ids->Delete();
    return NULL;
    }
  return ids;
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::DataSetFromNodeSet
(const vtkIdTypeArray *nodeSet, vtkUnstructuredGrid* data)
{
  vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New();
  vtkboneSelectionUtilities::PointSelectionFromIds (selection, this, nodeSet);
  vtkSmartPointer<vtkExtractSelection> extractor = vtkSmartPointer<vtkExtractSelection>::New();
  extractor->SetInputData (0, this);
  extractor->SetInputData (1, selection);
  extractor->Update();
  data->ShallowCopy (extractor->GetOutput());
  return VTK_OK;
}

//----------------------------------------------------------------------------
vtkUnstructuredGrid* vtkboneFiniteElementModel::DataSetFromNodeSet
(const vtkIdTypeArray *nodeSet)
{
  vtkUnstructuredGrid* data = vtkUnstructuredGrid::New();
  int returnVal = this->DataSetFromNodeSet (nodeSet, data);
  if (returnVal != VTK_OK)
    {
    data->Delete();
    return NULL;
    }
  return data;
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::DataSetFromNodeSet
(const char *nodeSetName, vtkUnstructuredGrid* data)
{
  vtkIdTypeArray* nodeIds = this->GetNodeSet (nodeSetName);
  if (!nodeIds)
    {
    return VTK_ERROR;
    }
  return this->DataSetFromNodeSet (nodeIds, data);
}

//----------------------------------------------------------------------------
vtkUnstructuredGrid* vtkboneFiniteElementModel::DataSetFromNodeSet
(const char *nodeSetName)
{
  vtkUnstructuredGrid* data = vtkUnstructuredGrid::New();
  int returnVal = this->DataSetFromNodeSet (nodeSetName, data);
  if (returnVal != VTK_OK)
    {
    data->Delete();
    return NULL;
    }
  return data;
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::DataSetFromElementSet
(const vtkIdTypeArray *elementSet, vtkUnstructuredGrid* data)
{
  vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New();
  vtkboneSelectionUtilities::CellSelectionFromIds (selection, this, elementSet);
  vtkSmartPointer<vtkExtractSelection> extractor = vtkSmartPointer<vtkExtractSelection>::New();
  extractor->SetInputData (0, this);
  extractor->SetInputData (1, selection);
  extractor->Update();
  data->ShallowCopy (extractor->GetOutput());
  return VTK_OK;
}

//----------------------------------------------------------------------------
vtkUnstructuredGrid* vtkboneFiniteElementModel::DataSetFromElementSet
(const vtkIdTypeArray *elementSet)
{
  vtkUnstructuredGrid* data = vtkUnstructuredGrid::New();
  int returnVal = this->DataSetFromElementSet (elementSet, data);
  if (returnVal != VTK_OK)
    {
    data->Delete();
    return NULL;
    }
  return data;
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::DataSetFromElementSet
(const char *elementSetName, vtkUnstructuredGrid* data)
{
  vtkIdTypeArray* elementIds = this->GetElementSet (elementSetName);
  if (!elementIds)
    {
    return VTK_ERROR;
    }
  return this->DataSetFromElementSet (elementIds, data);
}

//----------------------------------------------------------------------------
vtkUnstructuredGrid* vtkboneFiniteElementModel::DataSetFromElementSet
(const char *elementSetName)
{
  vtkUnstructuredGrid* data = vtkUnstructuredGrid::New();
  int returnVal = this->DataSetFromElementSet (elementSetName, data);
  if (returnVal != VTK_OK)
    {
    data->Delete();
    return NULL;
    }
  return data;
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::GetElementType()
{
  vtkSmartPointer<vtkCellTypes> cellTypes = vtkSmartPointer<vtkCellTypes>::New();
  this->GetCellTypes(cellTypes);
  if (cellTypes->GetNumberOfTypes() == 0)
    {
    return N88_UNKNOWN;
    }
  else if (cellTypes->GetNumberOfTypes() == 1)   // single type
    {
    if (cellTypes->IsType(VTK_TETRA))
      {
      return N88_TETRAHEDRON;
      }
    else if (cellTypes->IsType(VTK_HEXAHEDRON) || cellTypes->IsType(VTK_VOXEL))
      {
      return N88_HEXAHEDRON;
      }
    else
      {
      return N88_UNKNOWN;
      }
    }
  else if (cellTypes->GetNumberOfTypes() == 2)
    {
    if (cellTypes->IsType(VTK_HEXAHEDRON) && cellTypes->IsType(VTK_VOXEL))
      {
      return N88_HEXAHEDRON;
      }
    else
      {
      return N88_MIXED;
      }
    }
  else
    {
    return N88_MIXED;
    }
}

//----------------------------------------------------------------------------
void vtkboneFiniteElementModel::GetAllCellPoints (vtkIdTypeArray* allCellPoints)
{
  int types = this->GetElementType();
  vtkIdType nodesPerElement = 8; // default
  if (types == N88_TETRAHEDRON)
    {
    vtkIdType nodesPerElement = 4;
    }
  vtkIdType numCells = this->GetNumberOfCells();
  allCellPoints->Reset();
  allCellPoints->Allocate (numCells*nodesPerElement, numCells*nodesPerElement/4);
  vtkIdType npts = 0;
  vtkIdType* pts = NULL;
  for (vtkIdType cellId=0; cellId < numCells; ++cellId)
    {
    this->GetCellPoints(cellId, npts, pts);
    for (int i=0; i<npts; ++i)
      {
      allCellPoints->InsertNextValue(pts[i]);
      }
    }
}

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

vtkIdTypeArray* vtkboneFiniteElementModel::GetAllCellPoints ()
{
  vtkIdTypeArray* allCellPoints = vtkIdTypeArray::New();
  this->GetAllCellPoints (allCellPoints);
  return allCellPoints;
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ApplyBoundaryCondition
(
  vtkIdTypeArray* ids,
  vtkDataArray* senses,
  vtkDataArray* displacements,
  const char* constraintName
)
{
  if (!vtkFloatArray::SafeDownCast(displacements) &&
      !vtkDoubleArray::SafeDownCast(displacements))
    {
    vtkErrorMacro(<<"Displacements must be either type vtkFloatArray or vtkDoubleArray.");
    return VTK_ERROR;
    }

  vtkIdType N = ids->GetNumberOfTuples();
  if (senses->GetNumberOfTuples() != N ||
      displacements->GetNumberOfTuples() != N)
    {
    vtkErrorMacro(<<"ids/senses/displacements not all the same length.");
    return VTK_ERROR;
    }

  vtkSmartPointer<vtkboneConstraint> newConstraint =
      vtkSmartPointer<vtkboneConstraint>::Take(
        vtkboneConstraintUtilities::CreateBoundaryCondition(ids,senses,displacements,constraintName));

  if (this->GetConstraints()->GetItem(constraintName))
    {
    vtkboneConstraint* constraint = this->GetConstraints()->GetItem(constraintName);
    if ((constraint->GetConstraintType() != vtkboneConstraint::DISPLACEMENT) ||
        (constraint->GetConstraintAppliedTo() != vtkboneConstraint::NODES))
      {
      vtkErrorMacro(<<"Inconsistent constraint types.");
      return VTK_ERROR;
      }
    constraint->Merge(newConstraint);
    }
  else  // No existing constraint with this name.
    {
    this->GetConstraints()->AddItem(newConstraint);
    }

  return VTK_OK;
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ApplyBoundaryCondition
(
  vtkIdTypeArray* ids,
  int sense,
  double displacement,
  const char* constraintName
)
{
  vtkIdType N = ids->GetNumberOfTuples();
  vtkSmartPointer<vtkCharArray> senses = vtkSmartPointer<vtkCharArray>::New();
  senses->SetNumberOfValues(N);
  for (vtkIdType i=0; i<N; i++)
    {
    senses->SetValue(i, sense);
    }
  vtkSmartPointer<vtkDoubleArray> displacements = vtkSmartPointer<vtkDoubleArray>::New();
  displacements->SetNumberOfValues(N);
  for (vtkIdType i=0; i<N; i++)
    {
    displacements->SetValue(i, displacement);
    }

  return this->ApplyBoundaryCondition(ids, senses, displacements, constraintName);
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ApplyBoundaryCondition
(
  vtkIdType id,
  int sense,
  double displacement,
  const char* constraintName
)
{
  vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New();
  ids->SetNumberOfValues(1);
  ids->SetValue(0, id);
  vtkSmartPointer<vtkCharArray> senses = vtkSmartPointer<vtkCharArray>::New();
  senses->SetNumberOfValues(1);
  senses->SetValue(0, sense);
  vtkSmartPointer<vtkDoubleArray> displacements = vtkSmartPointer<vtkDoubleArray>::New();
  displacements->SetNumberOfValues(1);
  displacements->SetValue(0, displacement);

  return this->ApplyBoundaryCondition(ids, senses, displacements, constraintName);
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ApplyBoundaryCondition
(
  const char* nodeSetName,
  int sense,
  double displacement,
  const char* constraintName
)
{
  vtkIdTypeArray* ids = this->GetNodeSet (nodeSetName);
  if (!ids)
    {
    vtkErrorMacro(<<"No such node set: " << nodeSetName);
    return VTK_ERROR;
    }
  return this->ApplyBoundaryCondition(ids, sense, displacement, constraintName);
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::FixNodes
(
  vtkIdTypeArray* ids,
  const char* constraintName
)
{
  vtkIdType N = ids->GetNumberOfTuples();
  // Used to be possible to set these: currently we set them all, since
  // that is nearly always the desired usage of FixNodes.
  const int xFlag = 1;
  const int yFlag = 1;
  const int zFlag = 1;
  int senseCount = (xFlag != 0) + (yFlag != 0) + (zFlag != 0);

  // Create new larger Ids array and add senses array
  vtkSmartPointer<vtkIdTypeArray> expandedIds = vtkSmartPointer<vtkIdTypeArray>::New();
  expandedIds->SetNumberOfValues(N*senseCount);
  vtkSmartPointer<vtkCharArray> senses = vtkSmartPointer<vtkCharArray>::New();
  senses->SetNumberOfValues(N*senseCount);
  vtkIdType j=0;
  for (vtkIdType i=0; i<N; i++)
    {
    vtkIdType id = ids->GetValue(i);
    if (xFlag)
      {
      expandedIds->SetValue(j, id);
      senses->SetValue(j, 0);
      j++;
      }
    if (yFlag)
      {
      expandedIds->SetValue(j, id);
      senses->SetValue(j, 1);
      j++;
      }
    if (zFlag)
      {
      expandedIds->SetValue(j, id);
      senses->SetValue(j, 2);
      j++;
      }
    }
  assert(j == N*senseCount);

  vtkSmartPointer<vtkDoubleArray> displacements = vtkSmartPointer<vtkDoubleArray>::New();
  displacements->SetNumberOfValues(senseCount*N);
  for (vtkIdType i=0; i<senseCount*N; i++)
    {
    displacements->SetValue(i, 0.0);
    }

  return this->ApplyBoundaryCondition(expandedIds, senses, displacements, constraintName);
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::FixNodes
(
  vtkIdType id,
  const char* constraintName
)
{
  vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New();
  ids->SetNumberOfValues(1);
  ids->SetValue(0, id);

  return this->FixNodes(ids, constraintName);
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::FixNodes
(
  const char* nodeSetName,
  const char* constraintName
)
{
  vtkIdTypeArray* ids = this->GetNodeSet (nodeSetName);
  if (!ids)
    {
    vtkErrorMacro(<<"No such node set: " << nodeSetName);
    return VTK_ERROR;
    }
  return this->FixNodes(ids, constraintName);
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ApplyLoad
(
  vtkIdTypeArray* ids,
  vtkDataArray* distributions,
  vtkDataArray* senses,
  vtkDataArray* forces,
  const char* constraintName
)
{
  if (!vtkFloatArray::SafeDownCast(forces) &&
      !vtkDoubleArray::SafeDownCast(forces))
    {
    vtkErrorMacro(<<"Forces must be either type vtkFloatArray or vtkDoubleArray.");
    return VTK_ERROR;
    }

  vtkIdType N = ids->GetNumberOfTuples();
  if (distributions->GetNumberOfTuples() != N ||
      senses->GetNumberOfTuples() != N ||
      forces->GetNumberOfTuples() != N)
    {
    vtkErrorMacro(<<"ids/distributions/senses/forces not all the same length.");
    return VTK_ERROR;
    }

  vtkSmartPointer<vtkboneConstraint> newConstraint =
      vtkSmartPointer<vtkboneConstraint>::Take(
        vtkboneConstraintUtilities::CreateAppliedLoad(ids,distributions,senses,forces,constraintName));

  if (this->GetConstraints()->GetItem(constraintName))
    {
    vtkboneConstraint* constraint = this->GetConstraints()->GetItem(constraintName);
    if ((constraint->GetConstraintType() != vtkboneConstraint::FORCE) ||
        (constraint->GetConstraintAppliedTo() != vtkboneConstraint::ELEMENTS))
      {
      vtkErrorMacro(<<"Inconsistent constraint types.");
      return VTK_ERROR;
      }
    constraint->Merge(newConstraint);
    }
  else  // No existing constraint with this name.
    {
    this->GetConstraints()->AddItem(newConstraint);
    }

  return VTK_OK;
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ApplyLoad
  (
  vtkIdTypeArray* ids,
  int distribution,
  vtkDataArray* senses,
  vtkDataArray* forces,
  const char* constraintName
  )
  {
  vtkIdType N = ids->GetNumberOfTuples();

  vtkSmartPointer<vtkCharArray> distributions = vtkSmartPointer<vtkCharArray>::New();
  distributions->SetNumberOfValues(N);
  for (vtkIdType i=0; i<N; i++)
    {
    distributions->SetValue(i, distribution);
    }

  return this->ApplyLoad(ids, distributions, senses, forces, constraintName);
  }

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ApplyLoad
  (
  vtkIdTypeArray* ids,
  int distribution,
  int sense,
  double total_force,
  const char* constraintName
  )
  {
  vtkIdType N = ids->GetNumberOfTuples();

  vtkSmartPointer<vtkCharArray> distributions = vtkSmartPointer<vtkCharArray>::New();
  distributions->SetNumberOfValues(N);
  for (vtkIdType i=0; i<N; i++)
    {
    distributions->SetValue(i, distribution);
    }
  vtkSmartPointer<vtkCharArray> senses = vtkSmartPointer<vtkCharArray>::New();
  senses->SetNumberOfValues(N);
  for (vtkIdType i=0; i<N; i++)
    {
    senses->SetValue(i, sense);
    }
  double force = total_force / N;
  vtkSmartPointer<vtkDoubleArray> forces = vtkSmartPointer<vtkDoubleArray>::New();
  forces->SetNumberOfValues(N);
  for (vtkIdType i=0; i<N; i++)
    {
    forces->SetValue(i, force);
    }

  return this->ApplyLoad(ids, distributions, senses, forces, constraintName);
  }

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ApplyLoad
  (
  vtkIdType id,
  int distribution,
  int sense,
  double force,
  const char* constraintName
  )
  {
  vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New();
  ids->SetNumberOfValues(1);
  ids->SetValue(0, id);
  vtkSmartPointer<vtkCharArray> distributions = vtkSmartPointer<vtkCharArray>::New();
  distributions->SetNumberOfValues(1);
  distributions->SetValue(0, distribution);
  vtkSmartPointer<vtkCharArray> senses = vtkSmartPointer<vtkCharArray>::New();
  senses->SetNumberOfValues(1);
  senses->SetValue(0, sense);
  vtkSmartPointer<vtkDoubleArray> forces = vtkSmartPointer<vtkDoubleArray>::New();
  forces->SetNumberOfValues(1);
  forces->SetValue(0, force);

  return this->ApplyLoad(ids, distributions, senses, forces, constraintName);
  }

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ApplyLoad
  (
  const char* elementSetName,
  int distribution,
  int sense,
  double total_force,
  const char* constraintName
  )
  {
  vtkIdTypeArray* ids = this->GetElementSet (elementSetName);
  if (!ids)
    {
    vtkErrorMacro(<<"No such element set: " << elementSetName);
    return 0;
    }
  return this->ApplyLoad(ids, distribution, sense, total_force, constraintName);
  }

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ConvergenceSetFromConstraint(vtkboneConstraint* input_constraint)
  {
  // If constraint is applied to elements, distribute it to nodes.
  vtkSmartPointer<vtkboneConstraint> constraint;
  if (input_constraint->GetConstraintAppliedTo() == vtkboneConstraint::ELEMENTS)
    {
    constraint = vtkSmartPointer<vtkboneConstraint>::Take(
        vtkboneConstraintUtilities::DistributeConstraintToNodes(this, input_constraint));
    if (constraint.GetPointer() == NULL)
      {
      vtkErrorMacro (<< "Error converting to convergence set.");
      return VTK_ERROR;
      }
    constraint->SetConstraintType (input_constraint->GetConstraintType());
    }
  else
    {
    constraint = input_constraint;
    }

  vtkDataArray* values = constraint->GetAttributes()->GetArray("VALUE");
  if (!values)
    {
    vtkErrorMacro(<< "Constraint has no VALUES attribute.");
    return VTK_ERROR;
    }
  bool all_zero = true;
  for (vtkIdType i=0; i<values->GetNumberOfTuples(); ++i)
    {
    if (values->GetTuple1(i) != 0)
      {
      all_zero = false;
      break;
      }
    }
  if (all_zero)
    {
    vtkErrorMacro(<< "A constraint with all zero values cannot be specified as the convergence set.");
    return VTK_ERROR;
    }

  vtkSmartPointer<vtkboneConstraint> convergence_set = vtkSmartPointer<vtkboneConstraint>::New();
  convergence_set->DeepCopy (constraint);
  if (convergence_set->GetConstraintType() == vtkboneConstraint::FORCE)
    {
    convergence_set->SetConstraintType(vtkboneConstraint::DISPLACEMENT);
    }
  else
    {
    convergence_set->SetConstraintType(vtkboneConstraint::FORCE);
    }
  convergence_set->SetName("convergence_set");
  this->SetConvergenceSet (convergence_set);
  return VTK_OK;
  }

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::ConvergenceSetFromConstraint(const char* constraintName)
  {
  return this->ConvergenceSetFromConstraint(
           this->GetConstraints()->GetItem(constraintName));
  }

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::DataSetFromConstraint(
  vtkboneConstraint* constraint,
  vtkUnstructuredGrid* data)
{
  vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New();
  if (constraint->GetConstraintAppliedTo() == vtkboneConstraint::NODES)
    {
    this->DataSetFromNodeSet(constraint->GetIndices(), data);
    }
  else
    {
    this->DataSetFromElementSet(constraint->GetIndices(), data);
    }
  // Can copy all attribute arrays to Cell Data
  for (int i=0; i<constraint->GetAttributes()->GetNumberOfArrays(); i++)
    {
    data->GetCellData()->AddArray(constraint->GetAttributes()->GetArray(i));
    // If is a node constraint, then can also add the attribute arrays to the
    // Point Data.
    if (constraint->GetConstraintAppliedTo() == vtkboneConstraint::NODES)
      {
      data->GetPointData()->AddArray(constraint->GetAttributes()->GetArray(i));
      }
    }
  return 1;
}

//----------------------------------------------------------------------------
vtkUnstructuredGrid* vtkboneFiniteElementModel::DataSetFromConstraint(
  vtkboneConstraint* constraint)
{
  vtkUnstructuredGrid* data = vtkUnstructuredGrid::New();
  this->DataSetFromConstraint(constraint, data);
  return data;
}

//----------------------------------------------------------------------------
int vtkboneFiniteElementModel::DataSetFromConstraint(
  const char *constraintName,
  vtkUnstructuredGrid* data)
{
  vtkboneConstraint* constraint = this->GetConstraints()->GetItem(constraintName);
  if (!constraint)
    {
    return 0;
    }
  return this->DataSetFromConstraint(constraint, data);
}

//----------------------------------------------------------------------------
vtkUnstructuredGrid* vtkboneFiniteElementModel::DataSetFromConstraint(
  const char *constraintName)
{
  vtkboneConstraint* constraint = this->GetConstraints()->GetItem(constraintName);
  if (!constraint)
    {
    return 0;
    }
  return this->DataSetFromConstraint(constraint);
}

//----------------------------------------------------------------------------
void vtkboneFiniteElementModel::ShallowCopy (vtkDataObject *dataObject)
{
  vtkboneFiniteElementModel *meshModel = vtkboneFiniteElementModel::SafeDownCast(dataObject);

  if (meshModel != NULL)
    {

    this->SetName (meshModel->GetName());
    this->SetHistory (meshModel->GetHistory());
    this->SetLog (meshModel->GetLog());

    if (this->NodeSets)
      {
      this->NodeSets->UnRegister(this);
      }
    this->NodeSets = meshModel->NodeSets;
    if (this->NodeSets)
      {
      this->NodeSets->Register(this);
      }

    if (this->ElementSets)
      {
      this->ElementSets->UnRegister(this);
      }
    this->ElementSets = meshModel->ElementSets;
    if (this->ElementSets)
      {
      this->ElementSets->Register(this);
      }

    if (this->Constraints)
      {
      this->Constraints->UnRegister(this);
      }
    this->Constraints = meshModel->Constraints;
    if (this->Constraints)
      {
      this->Constraints->Register(this);
      }

    if (this->MaterialTable)
      {
      this->MaterialTable->UnRegister(this);
      }
    this->MaterialTable = meshModel->MaterialTable;
    if (this->MaterialTable)
      {
      this->MaterialTable->Register(this);
      }

    if (this->ConvergenceSet)
      {
      this->ConvergenceSet->UnRegister(this);
      }
    this->ConvergenceSet = meshModel->ConvergenceSet;
    if (this->ConvergenceSet)
      {
      this->ConvergenceSet->Register(this);
      }

    if (this->GaussPointData)
      {
      this->GaussPointData->UnRegister(this);
      }
    this->GaussPointData = meshModel->GaussPointData;
    if (this->GaussPointData)
      {
      this->GaussPointData->Register(this);
      }

    }

  // Do superclass
  this->vtkUnstructuredGrid::ShallowCopy(dataObject);
}

//----------------------------------------------------------------------------
void vtkboneFiniteElementModel::DeepCopy (vtkDataObject *dataObject)
{
  cerr << "vtkboneFiniteElementModel::DeepCopy not implemented yet.\n";
  exit(1);
}


text:
#include <frovedis.hpp>
#include <frovedis/ml/glm/logistic_regression_with_lbfgs.hpp>

#define BOOST_TEST_MODULE FrovedisTest
#include <boost/test/unit_test.hpp>
#include "../../rmse.hpp"

using namespace frovedis;
using namespace std;

double to_double(std::string& line) {
  return boost::lexical_cast<double>(line);
}

BOOST_AUTO_TEST_CASE( frovedis_test )
{
    int argc = 1;
    char** argv = NULL;
    use_frovedis use(argc, argv);

    auto data = make_crs_matrix_load<double> ("./data");
    auto label = make_dvector_loadline("./label").map(to_double);

    size_t num_iteration = 200;
    double alpha = 1.0;
    size_t hist_size = 10;
    bool intercept = true;
    RegType rt = L2;
    double regParam = 0.01;

    auto model = logistic_regression_with_lbfgs::train(std::move(data),label,
                                   num_iteration, alpha, hist_size,
                                   regParam, rt, intercept);

    auto mat = make_crs_matrix_local_load<double>("./data");
    auto out_p = model.predict(mat);
    auto out_pb = model.predict_probability(mat);
    for(auto i: out_p) cout << i << " "; cout << endl;
    for(auto i: out_pb) cout << i << " "; cout << endl;

    double tol = 0.01;
    std::vector<double> expected_out_p = {1.0, -1.0, 1.0, 1.0};
    std::vector<double> expected_out_pb = {1.0, 0.0, 1.0, 1.0};
    BOOST_CHECK (calc_rms_err<double> (out_p,expected_out_p) < tol);
    BOOST_CHECK (calc_rms_err<double> (out_pb,expected_out_pb) < tol);
}

ext: cc

max_stars_repo_name: XpressAI/frovedis

max_issues_repo_name: XpressAI/frovedis

max_forks_repo_name: XpressAI/frovedis


text:
// Copyright (C) 2007 Douglas Gregor

// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// This file contains a simplification of the "trigger" method for
// process groups. The simple trigger handles the common case where
// the handler associated with a trigger is a member function bound to
// a particular pointer.

// File moved
#include <boost/property_map/parallel/simple_trigger.hpp>

ext: hpp


text:
#include "HWE.hpp"
#include "GateFunction.hpp"
// #include <boost/tokenizer.hpp>
#include "xacc_service.hpp"
#include <regex>

using namespace xacc::quantum;

namespace xacc {
namespace vqe {

std::shared_ptr<Function>
HWE::generate(std::map<std::string, InstructionParameter> &parameters) {

  std::vector<InstructionParameter> params;
  if (!parameters.count("layers")) {
    params.push_back(InstructionParameter(1));
  } else {
    params.push_back(parameters["layers"]);
  }

  if (!parameters.count("n_qubits")) {
    xacc::error("HWE needs n_qubits parameter.");
  }

  params.push_back(parameters["n_qubits"]);

  if (!parameters.count("connectivity")) {
    xacc::error("HWE needs to know the connectivity of the qubits.");
  }

  params.push_back(parameters["connectivity"]);

  return generate(nullptr, params);
}

std::shared_ptr<Function>
HWE::generate(std::shared_ptr<AcceleratorBuffer> buffer,
              std::vector<InstructionParameter> parameters) {

  int nQubits = 0, layers = 1;
  std::vector<std::pair<int, int>> connectivity;
  try {
    nQubits = parameters[1].as<int>();
    layers = parameters[0].as<int>();
    auto cStr = parameters[2].as<std::string>();
    cStr = std::regex_replace(cStr, std::regex("'"), "");

    // boost::replace_all(cStr, "'", "");

    // xacc::info("CONNECTIVITY STRING: " + cStr);
    std::vector<int> ints;
    // boost::char_separator<char> sep(",");
    // boost::tokenizer<char_separator<char>> tokens(cStr, sep);
    auto tokens = xacc::split(cStr, ',');
    for (auto &t : tokens) {
      std::stringstream s;
      s << t;
      auto tmp = s.str();
      tmp = std::regex_replace(tmp, std::regex("\\["), "");
      tmp = std::regex_replace(tmp, std::regex("\\]"), "");

      xacc::trim(tmp);
      int value;
      if (std::stringstream(tmp) >> value)
        ints.push_back(value);
    }

    if (ints.size() % 2 != 0)
      xacc::error(std::to_string(ints.size()) +
                  ", You must provide the connectivity as a list of pairs.");

    for (int i = 0; i < ints.size(); i += 2) {
      connectivity.push_back({ints[i], ints[i + 1]});
    }

  } catch (std::exception &e) {
    xacc::error("Could not cast HWE parameter to correct type: " +
                std::string(e.what()));
  }

  std::vector<InstructionParameter> fParams;
  for (int nP = 0; nP < (2*nQubits + 3 * nQubits * layers); nP++)
    fParams.push_back(InstructionParameter("t" + std::to_string(nP)));

  auto provider = xacc::getService<IRProvider>("gate");
  auto f = provider->createFunction("hwe", {}, fParams);
  int angleCounter = 0;

  // Zeroth layer, start with X and Z rotations
  for (int q = 0; q < nQubits; q++) {
    auto rx = provider->createInstruction(
        "Rx", {q}, {InstructionParameter("t" + std::to_string(angleCounter))});
    auto rz = provider->createInstruction(
        "Rz", {q}, {InstructionParameter("t" + std::to_string(angleCounter+1))});
    f->addInstruction(rx);
    f->addInstruction(rz);
    angleCounter+=2;
  }

  for (int d = 0; d < layers; d++) {
    for (auto &p : connectivity) {
      auto cnot = provider->createInstruction("CNOT", {p.first, p.second});
      f->addInstruction(cnot);
    }
    for (int q = 0; q < nQubits; q++) {
      auto rz1 = provider->createInstruction(
          "Rz", {q},
          {InstructionParameter("t" + std::to_string(angleCounter))});
      f->addInstruction(rz1);

      auto rx = provider->createInstruction(
          "Rx", {q},
          {InstructionParameter("t" + std::to_string(angleCounter+1))});
      f->addInstruction(rx);

      auto rz2 = provider->createInstruction(
          "Rz", {q},
          {InstructionParameter("t" + std::to_string(angleCounter + 2))});
      f->addInstruction(rz2);

      angleCounter += 3;
    }
  }

  //   std::cout << "THE FUNCTION:\n" << f->toString("q") << "\n";
  return f;
}

} // namespace vqe
} // namespace xacc

ext: cpp


text:
/*
 * Software License Agreement(BSD License)
 *
 *  Copyright(c) 2011, The MITRE Corporation
 *  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 Willow Garage, Inc. 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.
 *
 * Author: Keven Ring <keven@mitre.org>
 */

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/pcd_io.h>
#include <boost/program_options.hpp>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <typeinfo>

#include "gps_hdl_grabber.h"

using namespace std;
using namespace pcl;
using namespace pcl::console;

#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = getTime();\
    double now = getTime(); \
    ++count; \
    if(now - last >= 1.0) \
    { \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
    } \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class LDRConverter
{
  public:
    typedef PointCloud<PointXYZRGBA> Cloud;
    typedef Cloud::Ptr CloudPtr;
    typedef Cloud::ConstPtr CloudConstPtr;

    LDRConverter(Grabber& grabber)
      : grabber_(grabber)
    {
      cloud_.reset(new pcl::PointCloud<pcl::PointXYZRGBA>());
    }

    void
    cloud_callback(const CloudConstPtr& cloud, float start, float end, bool restart)
    {
      FPS_CALC("cloud callback");
      boost::mutex::scoped_lock lock(cloud_mutex_);
      if (restart)
      {
          writeLDRFile(_dir, cloud_);
          cloud_.reset(new pcl::PointCloud<pcl::PointXYZRGBA>());
          cloud_->header.stamp = cloud->header.stamp;
          cloud_times_.clear();
      }
      (*cloud_) += *cloud;
      for (int k = 0; k < cloud->size(); k++)
          cloud_times_.push_back(cloud->header.stamp);
    }

    void
    run(const string& folder_name)
    {
      boost::filesystem::create_directories(folder_name);
      _dir = folder_name;
      cout << folder_name << " was created" << endl;

      boost::function<void(const CloudConstPtr&, float, float, bool)> cloud_cb = boost::bind(
              &LDRConverter::cloud_callback, this, _1, _2, _3, _4);
      boost::signals2::connection cloud_connection = grabber_.registerCallback(
              cloud_cb);
      grabber_.start();

      uint64_t last_stamp = 0;
      while(grabber_.isRunning())
      {
        boost::this_thread::sleep(boost::posix_time::microseconds(100));
      }

      grabber_.stop();

      cloud_connection.disconnect();
    }

    void
    writeLDRFile(const std::string& dir, const CloudConstPtr& cloud)
    {
      PointCloud<PointXYZRGBA> dataCloud = *cloud.get();
      uint64_t timeStamp = dataCloud.header.stamp;

      // The timestamp is in microseconds since Jan 1, 1970 (epoch time)
      stringstream ss;
      ss << dir << timeStamp << ".ldr";

      FILE *ldrFile = fopen(ss.str().c_str(), "wb");
      uint32_t k = 0;
      for(PointCloud<PointXYZRGBA>::iterator iter = dataCloud.begin(); iter != dataCloud.end(); ++iter)
      {
          //File format is little endian, 3 floats, 1 short, 1 short (16 bytes) per entry
          float intensity = (float) ( (iter->rgba & 0xffff0000) >> 16);
          float laser_num = (float) ( (iter->rgba & 0x0000ffff) );
          uint64_t cloud_time = cloud_times_[k];
          float cloud_time_delta = (float) ((uint32_t) (timeStamp - cloud_time));  // NOTE Sweep goes backwards
          float pBuffer[] = {iter->x, iter->y, iter->z, intensity, laser_num, cloud_time_delta};
          fwrite(pBuffer, 1, sizeof(pBuffer), ldrFile);
          k++;
          //uint32_t iBuffer[] = {iter->rgba};
          //fwrite(iBuffer, 1, sizeof(iBuffer), ldrFile);
      }
      fclose(ldrFile);
    }

    Grabber& grabber_;
    boost::mutex cloud_mutex_;
    boost::mutex visual_cloud_mutex_;
    string _dir;

    CloudPtr cloud_;
    std::vector<uint64_t> cloud_times_;
};

void
usage(char ** argv)
{
  cout << "usage: " << argv[0]
      << " [-hdlCalibration <path-to-calibration-file>] [-pcapFile <path-to-pcap-file>] [-ip <ip-address>] [-h | --help]"
      << endl;
  cout << argv[0] << " -h | --help : shows this help" << endl;
  return;
}

int
main(int argc, char ** argv)
{
  string hdlCalibration, pcapFile;
  namespace po = boost::program_options;

  po::options_description desc("Allowed options");
  desc.add_options()
    ("help", "produce help message")
    ("hdlcalibration", po::value<string>(), "<path-to-calibration-file")
    ("p", po::value<string>(), "<path-to-pcap-file>")
  ;
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help")) {
    cout << desc << endl;
    return 0;
  }

  if (vm.count("hdlcalibration")) {
    hdlCalibration = vm["hdlcalibration"].as<string>();
  }

  if (vm.count("p")) {
    pcapFile = vm["p"].as<string>();
    cout << "Pcap File: " << pcapFile << endl;
  }

  /*
  if(find_switch(argc, argv, "-h") ||
      find_switch(argc, argv, "--help"))
  {
    usage(argv);
    return(0);
  }
  */

  //parse_argument(argc, argv, "-calibrationFile", hdlCalibration);
  //parse_argument(argc, argv, "-pcapFile", pcapFile);

  GPSHDLGrabber *grabber = new GPSHDLGrabber(hdlCalibration, pcapFile);
  float minDistance = 0.00001f;
  grabber->setMinimumDistanceThreshold(minDistance);

  LDRConverter v(*grabber);
  boost::filesystem::path const p(pcapFile);
  string output_folder(p.branch_path().string() + "/" + p.stem().string() + "_frames/");
  v.run(output_folder);

  return(0);
}

max_stars_repo_name: sameeptandon/sail-car-log

max_issues_repo_name: sameeptandon/sail-car-log

max_forks_repo_name: sameeptandon/sail-car-log


text:
#ifndef BOOST_PP_IS_ITERATING
    ///////////////////////////////////////////////////////////////////////////////
    /// \file callable.hpp
    /// Definintion of callable_context\<\>, an evaluation context for
    /// proto::eval() that explodes each node and calls the derived context
    /// type with the expressions constituents. If the derived context doesn't
    /// have an overload that handles this node, fall-back to the default_context.
    /// TODO: make the fall-back configurable!
    //
    //  Copyright 2007 Eric Niebler. Distributed under the Boost
    //  Software License, Version 1.0. (See accompanying file
    //  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

    #ifndef BOOST_PROTO_CONTEXT_CALLABLE_HPP_EAN_06_23_2007
    #define BOOST_PROTO_CONTEXT_CALLABLE_HPP_EAN_06_23_2007

    #include <boost/xpressive/proto/detail/prefix.hpp> // must be first include
    #include <boost/config.hpp>
    #include <boost/detail/workaround.hpp>
    #include <boost/preprocessor/cat.hpp>
    #include <boost/preprocessor/iteration/iterate.hpp>
    #include <boost/preprocessor/facilities/intercept.hpp>
    #include <boost/preprocessor/repetition/enum_params.hpp>
    #include <boost/preprocessor/repetition/enum_trailing.hpp>
    #include <boost/preprocessor/arithmetic/inc.hpp>
    #include <boost/preprocessor/selection/max.hpp>
    #include <boost/mpl/if.hpp>
    #include <boost/mpl/bool.hpp>
    #include <boost/utility/result_of.hpp>
    #include <boost/type_traits/remove_cv.hpp>
    #include <boost/xpressive/proto/proto_fwd.hpp>
    #include <boost/xpressive/proto/traits.hpp> // for arg_c
    #include <boost/xpressive/proto/detail/suffix.hpp> // must be last include

    namespace boost { namespace proto
    {
        namespace detail
        {
            struct private_type_
            {
                private_type_ const &operator,(int) const;
            };

            template<typename T>
            yes_type check_is_expr_handled(T const &);

            no_type check_is_expr_handled(private_type_ const &);

            template<typename Context, long Arity>
            struct callable_context_wrapper;

            template<typename Expr, typename Context, long Arity = Expr::proto_arity::value>
            struct is_expr_handled;
        }

        namespace context
        {
            /// callable_eval
            ///
            template<typename Expr, typename Context, long Arity>
            struct callable_eval
            {};

            /// callable_context
            ///
            template<typename Context, typename DefaultCtx>
            struct callable_context
            {
                /// callable_context::eval
                ///
                template<typename Expr, typename ThisContext = Context>
                struct eval
                  : mpl::if_<
                        detail::is_expr_handled<Expr, Context>
                      , callable_eval<Expr, ThisContext>
                      , typename DefaultCtx::template eval<Expr, Context>
                    >::type
                {};
            };
        }

    #define BOOST_PROTO_ARG_N_TYPE(Z, N, Expr)                                                      \
        typename proto::result_of::arg_c<Expr, N>::const_reference                                  \
        /**/

    #define BOOST_PROTO_ARG_N(Z, N, expr)                                                           \
        proto::arg_c<N>(expr)                                                                       \
        /**/

    #define BOOST_PP_ITERATION_PARAMS_1                                                             \
        (3, (0, BOOST_PROTO_MAX_ARITY, <boost/xpressive/proto/context/callable.hpp>))               \
        /**/

    #include BOOST_PP_ITERATE()

    #undef BOOST_PROTO_ARG_N_TYPE
    #undef BOOST_PROTO_ARG_N

    }}

    #endif

#else

    #define N BOOST_PP_ITERATION()
    #define ARG_COUNT BOOST_PP_MAX(1, N)

        namespace detail
        {
            #if N > 0
            template<typename Context>
            struct callable_context_wrapper<Context, N>
              : remove_cv<Context>::type
            {
                callable_context_wrapper();
                typedef private_type_ const &(*pointer_to_function)(BOOST_PP_ENUM_PARAMS(BOOST_PP_INC(ARG_COUNT), detail::dont_care BOOST_PP_INTERCEPT));
                operator pointer_to_function() const;
            };
            #endif

            template<typename Expr, typename Context>
            struct is_expr_handled<Expr, Context, N>
            {
                static callable_context_wrapper<Context, ARG_COUNT> &sctx_;
                static Expr &sexpr_;

                BOOST_STATIC_CONSTANT(bool, value =
                (
                    sizeof(yes_type) ==
                    sizeof(
                        detail::check_is_expr_handled(
                            (sctx_(
                                typename Expr::proto_tag()
                                BOOST_PP_ENUM_TRAILING(ARG_COUNT, BOOST_PROTO_ARG_N, sexpr_)
                            ), 0)
                        )
                )));

                typedef mpl::bool_<value> type;
            };
        }

        namespace context
        {
            template<typename Expr, typename Context>
            struct callable_eval<Expr, Context, N>
            {
                typedef
                    typename boost::result_of<
                        Context(
                            typename Expr::proto_tag
                            BOOST_PP_ENUM_TRAILING(ARG_COUNT, BOOST_PROTO_ARG_N_TYPE, Expr)
                        )
                    >::type
                result_type;

                result_type operator ()(Expr &expr, Context &context) const
                {
                    return context(
                        typename Expr::proto_tag()
                        BOOST_PP_ENUM_TRAILING(ARG_COUNT, BOOST_PROTO_ARG_N, expr)
                    );
                }
            };
        }

    #undef N
    #undef ARG_COUNT

#endif

max_stars_repo_name: foxostro/CheeseTesseract

max_issues_repo_name: foxostro/CheeseTesseract

max_forks_repo_name: foxostro/CheeseTesseract


text:
/****************************************************************************/
/* Copyright 2005-2006, Francis Russell                                     */
/*                                                                          */
/* 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                           */
/*                                                                          */
/* Unless required by applicable law or agreed to in writing, software      */
/* distributed under the License is distributed on an AS IS BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and      */
/* limitations under the License.                                           */
/*                                                                          */
/****************************************************************************/

#ifndef DESOLA_SCALAR_PIECEWISE
#define DESOLA_SCALAR_PIECEWISE

#include <boost/array.hpp>
#include <desola/Desola_fwd.hpp>

namespace desola
{

namespace detail
{

namespace
{
  template<typename exprType, typename T_element>
  class GetScalarPiecewiseSize
  {
  public:
    Maybe<double> operator()(const ExprNode<exprType, T_element>& e) const
    {
      const boost::array<std::size_t, ExprDimensions<exprType>::dims> dimensions(e.getDims());
      return std::accumulate(dimensions.begin(), dimensions.end(), 1.0, std::multiplies<double>());
    }
  };

  template<typename T_element>
  class GetScalarPiecewiseSize<matrix, T_element>
  {
  public:
    Maybe<double> getSize(const ExprNode<matrix, T_element>& e)
    {
      return Maybe<double>(e.nnz());
    }
  };
}

template<typename exprType, typename T_element>
class ScalarPiecewise : public BinOp<exprType, exprType, scalar, T_element>
{
private:
  const ScalarPiecewiseOp operation;

public:
  ScalarPiecewise(const ScalarPiecewiseOp op, ExprNode<exprType, T_element>& o, ExprNode<scalar, T_element>& s) : BinOp<exprType, exprType, scalar, T_element>(o.getDims(), o, s), operation(op)
  {
  }

  ScalarPiecewiseOp getOperation() const
  {
    return operation;
  }

  void accept(ExpressionNodeVisitor<T_element>& v)
  {
    v.visit(*this);
  }

  virtual Maybe<double> getFlops() const
  {
    return GetScalarPiecewiseSize<exprType, T_element>()(this->getLeft());
  }
};

}

}
#endif

max_stars_repo_name: FrancisRussell/desola

max_issues_repo_name: FrancisRussell/desola

max_forks_repo_name: FrancisRussell/desola


text:
/*
    Copyright 2007-2012 Christian Henning, Andreas Pokorny, Lubomir Bourdev
    Use, modification and distribution are subject to the Boost Software License,
    Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt).
*/

/*************************************************************************************************/

#ifndef BOOST_GIL_EXTENSION_IO_READ_AND_CONVERT_IMAGE_HPP
#define BOOST_GIL_EXTENSION_IO_READ_AND_CONVERT_IMAGE_HPP

////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief
/// \author Christian Henning, Andreas Pokorny, Lubomir Bourdev \n
///
/// \date   2007-2012 \n
///
////////////////////////////////////////////////////////////////////////////////////////

#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/mpl/and.hpp>
#include <boost/utility/enable_if.hpp>

#include "base.hpp"
#include "io_device.hpp"
#include "path_spec.hpp"
#include "conversion_policies.hpp"

namespace boost{ namespace gil {

/// \ingroup IO

/// \brief Reads and color-converts an image. Image memory is allocated.
/// \param reader    An image reader.
/// \param img       The image in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \param cc        Color converter function object.
/// \throw std::ios_base::failure
template< typename Reader
        , typename Image
        >
inline
void read_and_convert_image( Reader&                                 reader
                           , Image&                                  img
                           , typename enable_if< mpl::and_< detail::is_reader< Reader >
                                                          , is_format_tag< typename Reader::format_tag_t >
                                                          >
                           >::type* /* ptr */ = 0
                           )
{
    reader.init_image( img
                     , reader._settings
                     );

    reader.apply( view( img ));
}

/// \brief Reads and color-converts an image. Image memory is allocated.
/// \param device    Must satisfy is_input_device metafunction.
/// \param img       The image in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \param cc        Color converter function object.
/// \throw std::ios_base::failure
template< typename Device
        , typename Image
        , typename ColorConverter
        , typename FormatTag
        >
inline
void read_and_convert_image( Device&                                 device
                           , Image&                                  img
                           , const image_read_settings< FormatTag >& settings
                           , const ColorConverter&                   cc
                           , typename enable_if< mpl::and_< detail::is_read_device< FormatTag
                                                                                , Device
                                                                                >
                                                          , is_format_tag< FormatTag >
                                                          >
                                                >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< Device
                               , FormatTag
                               , detail::read_and_convert< ColorConverter >
                               >::type reader_t;

    reader_t reader = make_reader( device
                                 , settings
                                 , detail::read_and_convert< ColorConverter >( cc )
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param img       The image in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \param cc        Color converter function object.
/// \throw std::ios_base::failure
template < typename String
         , typename Image
         , typename ColorConverter
         , typename FormatTag
         >
inline
void read_and_convert_image( const String&                           file_name
                           , Image&                                  img
                           , const image_read_settings< FormatTag >& settings
                           , const ColorConverter&                   cc
                           , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                          , detail::is_supported_path_spec< String >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< String
                               , FormatTag
                               , detail::read_and_convert< ColorConverter >
                               >::type reader_t;

    reader_t reader = make_reader( file_name
                                 , settings
                                 , detail::read_and_convert< ColorConverter >( cc )
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param img       The image in which the data is read into.
/// \param cc        Color converter function object.
/// \param tag       Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename String
         , typename Image
         , typename ColorConverter
         , typename FormatTag
         >
inline
void read_and_convert_image( const String&         file_name
                           , Image&                img
                           , const ColorConverter& cc
                           , const FormatTag&      tag
                           , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                          , detail::is_supported_path_spec< String >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< String
                               , FormatTag
                               , detail::read_and_convert< ColorConverter >
                               >::type reader_t;

    reader_t reader = make_reader( file_name
                                 , tag
                                 , detail::read_and_convert< ColorConverter >( cc )
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated.
/// \param device Must satisfy is_input_device metafunction or is_adaptable_input_device.
/// \param img    The image in which the data is read into.
/// \param cc     Color converter function object.
/// \param tag    Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename Device
         , typename Image
         , typename ColorConverter
         , typename FormatTag
         >
inline
void read_and_convert_image( Device&               device
                           , Image&                img
                           , const ColorConverter& cc
                           , const FormatTag&      tag
                           , typename enable_if< mpl::and_< detail::is_read_device< FormatTag
                                                                                , Device
                                                                                >
                                                          , is_format_tag< FormatTag >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< Device
                               , FormatTag
                               , detail::read_and_convert< ColorConverter >
                               >::type reader_t;

    reader_t reader = make_reader( device
                                 , tag
                                 , detail::read_and_convert< ColorConverter >( cc )
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param img       The image in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \throw std::ios_base::failure
template < typename String
         , typename Image
         , typename FormatTag
         >
inline
void read_and_convert_image( const String&                           file_name
                           , Image&                                  img
                           , const image_read_settings< FormatTag >& settings
                           , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                          , detail::is_supported_path_spec< String >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< String
                               , FormatTag
                               , detail::read_and_convert< default_color_converter >
                               >::type reader_t;

    reader_t reader = make_reader( file_name
                                 , settings
                                 , detail::read_and_convert< default_color_converter >()
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used.
/// \param device    It's a device. Must satisfy is_input_device metafunction or is_adaptable_input_device.
/// \param img       The image in which the data is read into.
/// \param settings  Specifies read settings depending on the image format.
/// \throw std::ios_base::failure
template < typename Device
         , typename Image
         , typename FormatTag
         >
inline
void read_and_convert_image( Device&                                 device
                           , Image&                                  img
                           , const image_read_settings< FormatTag >& settings
                           , typename enable_if< mpl::and_< detail::is_read_device< FormatTag
                                                                                , Device
                                                                                >
                                                          , is_format_tag< FormatTag >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< Device
                               , FormatTag
                               , detail::read_and_convert< default_color_converter >
                               >::type reader_t;

    reader_t reader = make_reader( device
                                 , settings
                                 , detail::read_and_convert< default_color_converter >()
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param img       The image in which the data is read into.
/// \param tag       Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename String
         , typename Image
         , typename FormatTag
         >
inline
void read_and_convert_image( const String&    file_name
                           , Image&           img
                           , const FormatTag& tag
                           , typename enable_if< mpl::and_< is_format_tag< FormatTag >
                                                          , detail::is_supported_path_spec< String >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< String
                               , FormatTag
                               , detail::read_and_convert< default_color_converter >
                               >::type reader_t;

    reader_t reader = make_reader( file_name
                                 , tag
                                 , detail::read_and_convert< default_color_converter >()
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

/// \brief Reads and color-converts an image. Image memory is allocated. Default color converter is used.
/// \param file_name File name. Must satisfy is_supported_path_spec metafunction.
/// \param img       The image in which the data is read into.
/// \param tag       Defines the image format. Must satisfy is_format_tag metafunction.
/// \throw std::ios_base::failure
template < typename Device
         , typename Image
         , typename FormatTag
         >
inline
void read_and_convert_image( Device&          device
                           , Image&           img
                           , const FormatTag& tag
                           , typename enable_if< mpl::and_< detail::is_read_device< FormatTag
                                                                                , Device
                                                                                >
                                                          , is_format_tag< FormatTag >
                                                          >
                                               >::type* /* ptr */ = 0
                           )
{
    typedef typename get_reader< Device
                               , FormatTag
                               , detail::read_and_convert< default_color_converter >
                               >::type reader_t;

    reader_t reader = make_reader( device
                                 , tag
                                 , detail::read_and_convert< default_color_converter >()
                                 );

    read_and_convert_image( reader
                          , img
                          );
}

} // namespace gil
} // namespace boost

#endif // BOOST_GIL_EXTENSION_IO_READ_AND_CONVERT_IMAGE_HPP

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
// Copyright (c) 2005 - 2012 Marc de Kamps
//						2012 David-Matthias Sichau
// 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 copyright holder 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.
//

//Hack to test privat members
#define private public
#define protected public
#include <MPILib/algorithm/WilsonCowanAlgorithm.hpp>
#undef protected
#undef private

#include <MPILib/include/report/handler/RootReportHandler.hpp>
#include <MPILib/include/SimulationRunParameter.hpp>

#include <boost/test/minimal.hpp>
using namespace boost::unit_test;
using namespace MPILib::algorithm;

void test_Constructor() {

	MPILib::Time tau = 10e-3; //10 ms
	MPILib::Rate rate_max = 100.0;
	double noise = 1.0;

	// Define the receiving node
	WilsonCowanParameter par_sigmoid(tau, rate_max, noise);

	WilsonCowanAlgorithm algorithm_exc(par_sigmoid);

	BOOST_CHECK(algorithm_exc._parameter._f_noise == par_sigmoid._f_noise);
	BOOST_CHECK(
			algorithm_exc._integrator.Parameter()._f_noise == par_sigmoid._f_noise);

}

void test_clone() {
	MPILib::Time tau = 10e-3; //10 ms
	MPILib::Rate rate_max = 100.0;
	double noise = 1.0;

	// Define the receiving node
	WilsonCowanParameter par_sigmoid(tau, rate_max, noise);

	WilsonCowanAlgorithm algorithm_exc(par_sigmoid);

	WilsonCowanAlgorithm* alg = algorithm_exc.clone();
	BOOST_CHECK(alg->_parameter._f_noise == 1.0);
	delete alg;

	AlgorithmInterface<double>* algI;
	algI = algorithm_exc.clone();

	if (dynamic_cast<WilsonCowanAlgorithm *>(algI)) {
	} else {
		BOOST_ERROR("should be of dynamic type WilsonCowanAlgorithm");
	}
	delete algI;
}

void test_configure() {
	const MPILib::report::handler::RootReportHandler WILSONCOWAN_HANDLER(
			"test/wilsonresponse.root", // file where the simulation results are written
			false // only rate diagrams
			);

	const MPILib::SimulationRunParameter PAR_WILSONCOWAN(WILSONCOWAN_HANDLER, // the handler object
			1000000, // maximum number of iterations
			0, // start time of simulation
			0.5, // end time of simulation
			1e-4, // report time
			1e-5, // network step time
			"test/wilsonresponse.log" // log file name
			);

	MPILib::Time tau = 10e-3; //10 ms
	MPILib::Rate rate_max = 100.0;
	double noise = 1.0;

	// Define the receiving node
	WilsonCowanParameter par_sigmoid(tau, rate_max, noise);

	WilsonCowanAlgorithm algorithm_exc(par_sigmoid);

	algorithm_exc.configure(PAR_WILSONCOWAN);
	BOOST_CHECK(algorithm_exc._integrator._time_begin==0);
	BOOST_CHECK(algorithm_exc._integrator._step==1e-5);

}

void test_evolveNodeState() {
	/// @todo DS implement this test
}

void test_getCurrentTime() {
	MPILib::Time tau = 10e-3; //10 ms
	MPILib::Rate rate_max = 100.0;
	double noise = 1.0;

	// Define the receiving node
	WilsonCowanParameter par_sigmoid(tau, rate_max, noise);

	WilsonCowanAlgorithm algorithm_exc(par_sigmoid);
	BOOST_CHECK(algorithm_exc.getCurrentTime() == 0.0);
}

void test_getCurrentRate() {
	MPILib::Time tau = 10e-3; //10 ms
	MPILib::Rate rate_max = 100.0;
	double noise = 1.0;

	// Define the receiving node
	WilsonCowanParameter par_sigmoid(tau, rate_max, noise);

	WilsonCowanAlgorithm algorithm_exc(par_sigmoid);
	BOOST_CHECK(algorithm_exc.getCurrentTime() == 0.0);
}

void test_innerProduct() {
	MPILib::Time tau = 10e-3; //10 ms
	MPILib::Rate rate_max = 100.0;
	double noise = 1.0;

	// Define the receiving node
	WilsonCowanParameter par_sigmoid(tau, rate_max, noise);

	WilsonCowanAlgorithm algorithm_exc(par_sigmoid);

	std::vector<double> weightVector {4.5,5.2,7.2};

	std::vector<double> nodeVector {2.3,5.3,9.3};

	//need to calculate this
	double res = algorithm_exc.innerProduct(weightVector, nodeVector);
	// only works if in the correct range
	BOOST_CHECK(int(res) == 104);

}

void test_getInitialState() {
	MPILib::Time tau = 10e-3; //10 ms
	MPILib::Rate rate_max = 100.0;
	double noise = 1.0;

	// Define the receiving node
	WilsonCowanParameter par_sigmoid(tau, rate_max, noise);

	WilsonCowanAlgorithm alg(par_sigmoid);

	std::vector<double> v =alg.getInitialState();
	BOOST_CHECK(v[0]==0);
}

void test_getGrid() {
	MPILib::Time tau = 10e-3; //10 ms
	MPILib::Rate rate_max = 100.0;
	double noise = 1.0;

	// Define the receiving node
	WilsonCowanParameter par_sigmoid(tau, rate_max, noise);

	WilsonCowanAlgorithm alg(par_sigmoid);
	AlgorithmGrid grid = alg.getGrid(0);
	BOOST_CHECK(grid._arrayState[0]==0.0);
	BOOST_CHECK(grid._arrayInterpretation[0]==0.0);
}

int test_main(int argc, char* argv[]) // note the name!
		{

	test_Constructor();
	test_clone();
	test_configure();
	test_evolveNodeState();
	test_getCurrentTime();
	test_getCurrentRate();
	test_innerProduct();
	test_getInitialState();
	test_getGrid();

	return 0;
//    // six ways to detect and report the same error:
//    BOOST_CHECK( add( 2,2 ) == 4 );        // #1 continues on error
//    BOOST_CHECK( add( 2,2 ) == 4 );      // #2 throws on error
//    if( add( 2,2 ) != 4 )
//        BOOST_ERROR( "Ouch..." );          // #3 continues on error
//    if( add( 2,2 ) != 4 )
//        BOOST_FAIL( "Ouch..." );           // #4 throws on error
//    if( add( 2,2 ) != 4 ) throw "Oops..."; // #5 throws on error
//
//    return add( 2, 2 ) == 4 ? 0 : 1;       // #6 returns error code
}

max_stars_repo_name: dekamps/miind

max_issues_repo_name: dekamps/miind

max_forks_repo_name: dekamps/miind


text:
//============================================================================
// Name        :
// Author      : Avi
// Revision    : $Revision: #57 $
//
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//============================================================================

#include <iostream>
#include <boost/test/unit_test.hpp>

#include "ZombieUtil.hpp"
#include "AssertTimer.hpp"
#include "Zombie.hpp"
#include "TestFixture.hpp"

using namespace std;
using namespace ecf;

void ZombieUtil::test_clean_up(int timeout) {

   // try to tidy up. Avoid leaving zombie process that mess up tests
   TestFixture::client().zombieGet();
   std::vector<Zombie> zombies = TestFixture::client().server_reply().zombies();
   if (!zombies.empty()) {
      cout << "\nZombieUtil::test_clean_up: Found Zombies:\n";
      cout << "Client Environment:\n" << TestFixture::client().to_string() << "\n";
      cout << Zombie::pretty_print( zombies , 9) << "\n, attempting to *fob* then *remove* ...\n";

      int no_fobed = do_zombie_user_action(User::FOB, zombies.size(), timeout, false /* don't fail if it takes to long */);

      // In order to FOB, we must wait, till a child command, talks to the server.
      if (no_fobed) {
         int wait = 5;
#if defined(HPUX) || defined(_AIX)
         wait += 5; // On these platforms wait longer,
#endif
         cout << "   Fobed " << no_fobed << " left over zombies. sleeping for " << wait << "s before attempting to remove\n";
         sleep(wait);
      }
      (void) do_zombie_user_action(User::REMOVE, no_fobed, timeout, false /* don't fail if it takes to long */);
   }
}

int ZombieUtil::do_zombie_user_action(User::Action uc, int expected_action_cnt, int max_time_to_wait, bool fail_if_to_long)
{
   /// return the number of zombies set to user action;
   bool ecf_debug_zombies = false;
   if (getenv("ECF_DEBUG_ZOMBIES")) {
      ecf_debug_zombies = true;
      cout << "\n   do_zombie_user_action " << User::to_string(uc) << " expected_action_cnt " << expected_action_cnt << "\n";
   }

   int action_set =  0;
   std::vector<Zombie> action_set_zombies;
   AssertTimer assertTimer(max_time_to_wait,false); // Bomb out after n seconds, fall back if test fail
   while (true) {
      BOOST_REQUIRE_MESSAGE(TestFixture::client().zombieGet() == 0, "zombieGet failed should return 0\n" << TestFixture::client().errorMsg());
      std::vector<Zombie> zombies = TestFixture::client().server_reply().zombies();
      bool continue_looping = false;
      for(const Zombie& z: zombies) {
         switch (uc) {
            case User::FOB: {
               if (!z.fob()) {
                  TestFixture::client().zombieFob(z); // UNBLOCK, child commands, allow zombie to complete, will clear server_reply().zombies()
                  continue_looping = true;
                  action_set++;
                  action_set_zombies.push_back(z);
               }
               break;
            }
            case User::FAIL: {
               if (!z.fail()) {
                  TestFixture::client().zombieFail(z); // UNBLOCK, child commands, allow zombie to complete, will clear server_reply().zombies()
                  continue_looping = true;
                  action_set++;
                  action_set_zombies.push_back(z);
               }
               break;
            }
            case User::ADOPT: {
               if (!z.adopt()) {
                  TestFixture::client().zombieAdopt(z); // UNBLOCK, child commands, allow zombie to complete, will clear server_reply().zombies()
                  continue_looping = true;
                  action_set++;
                  action_set_zombies.push_back(z);
               }
               break;
            }
            case User::REMOVE: {
               if (!z.remove()) {             // should always return false
                  TestFixture::client().zombieRemove(z);  // This should be immediate, and is not remembered
                  continue_looping = true;
                  action_set++;
                  action_set_zombies.push_back(z);
               }
               break;
            }
            case User::BLOCK:  {
               if (!z.block()) {
                  TestFixture::client().zombieBlock(z);
                  continue_looping = true;
                  action_set++;
                  action_set_zombies.push_back(z);
               }
               break;
            }
            case User::KILL:  {
                if (!z.kill()) {
                   TestFixture::client().zombieKill(z);
                   continue_looping = true;
                   action_set++;
                   action_set_zombies.push_back(z);
                }
                break;
             }
         }
      }

      if (expected_action_cnt == action_set) {
         break; // return
      }

      if ( !continue_looping && action_set > 0) {
         if (expected_action_cnt == 0) break;          // return, some clients set this as 0
      }

      // make sure test does not take too long.
      if ( assertTimer.duration() >=  assertTimer.timeConstraint() ) {

         if (expected_action_cnt > 0 && action_set > 0) {
            if (ecf_debug_zombies) cout << "   timeing out after action_set = " << action_set << " expected_action_cnt = " << expected_action_cnt << "\n";
            break;
         }

         std::stringstream ss;
         ss << "do_zombie_user_action:\nExpected " << expected_action_cnt
            << " zombies with user action " << User::to_string(uc) << " but found " << action_set << "\naction set zombies\n"
            << Zombie::pretty_print( action_set_zombies , 6)
            << ", Test taking longer than time constraint of "
            << assertTimer.timeConstraint();
         if (fail_if_to_long) {
            BOOST_REQUIRE_MESSAGE(false,ss.str() << " aborting\n" << Zombie::pretty_print( zombies , 6));
         }
         else {
            cout << ss.str() << " breaking out\n" << Zombie::pretty_print( zombies , 6) << "\n";
            break;
         }
      }
      sleep(1);
   }

   if (ecf_debug_zombies) {
      cout << "   " << action_set << " zombies set to user action " << User::to_string(uc) << " returning\n";
      cout << Zombie::pretty_print( action_set_zombies, 6);
   }
   return action_set;
}

max_stars_repo_name: ecmwf/ecflow

max_issues_repo_name: CoollRock/ecflow

max_forks_repo_name: CoollRock/ecflow


text:
#include <twitterlib/objects/entities.hpp>

#include <string>

#include <boost/property_tree/ptree.hpp>

#include <twitterlib/detail/utility.hpp>
#include <twitterlib/objects/hashtag.hpp>
#include <twitterlib/objects/media.hpp>
#include <twitterlib/objects/symbol.hpp>
#include <twitterlib/objects/url.hpp>
#include <twitterlib/objects/user_mention.hpp>

namespace twitter {

auto to_string(Entities const& entities) -> std::string
{
    auto x = std::string{};
    x.append("hashtags:\n");
    for (auto const& hashtag : entities.hashtags)
        x.append(add_indention_level(to_string(hashtag)).append(1, '\n'));

    x.append("media:\n");
    for (auto const& m : entities.media)
        x.append(add_indention_level(to_string(m)).append(1, '\n'));

    x.append("urls:\n");
    for (auto const& url : entities.urls)
        x.append(add_indention_level(to_string(url)).append(1, '\n'));

    x.append("user_mentions:\n");
    for (auto const& mention : entities.user_mentions)
        x.append(add_indention_level(to_string(mention)).append(1, '\n'));

    x.append("symbols:\n");
    for (auto const& symbol : entities.symbols)
        x.append(add_indention_level(to_string(symbol)).append(1, '\n'));

    x.pop_back();  // '\n'
    return x;
}

auto parse_entities(boost::property_tree::ptree const& tree) -> Entities
{
    auto x     = Entities{};
    x.hashtags = as_vector<Hashtag>(
        tree.get_child("hashtags", {}),
        [](auto const& tree) { return parse_hashtag(tree); });

    x.media =
        as_vector<Media>(tree.get_child("media", {}),
                         [](auto const& tree) { return parse_media(tree); });

    x.urls = as_vector<URL>(tree.get_child("urls", {}),
                            [](auto const& tree) { return parse_url(tree); });

    x.user_mentions = as_vector<User_mention>(
        tree.get_child("user_mentions", {}),
        [](auto const& tree) { return parse_user_mention(tree); });

    x.symbols =
        as_vector<Symbol>(tree.get_child("symbols", {}),
                          [](auto const& tree) { return parse_symbol(tree); });

    return x;
}

// Entities_data::operator std::string() const
// {
//     std::stringstream ss;
//     ss << "hashtags:";
//     for (const auto& ht : hashtags) {
//         ss << "\n" << ht;
//     }
//     ss << "\nmedia: ";
//     for (const auto& m : media) {
//         ss << "\n" << m;
//     }
//     ss << "\nurls: ";
//     for (const auto& url : urls) {
//         ss << "\n" << url;
//     }
//     ss << "\nuser_mentions: ";
//     for (const auto& um : user_mentions) {
//         ss << "\n" << um;
//     }
//     return ss.str();
// }

// void Entities_data::construct(const boost::property_tree::ptree& tree)
// {
//     auto hashtags_tree =
//         tree.get_child("hashtags", boost::property_tree::ptree());
//     for (auto& pair : hashtags_tree) {
//         hashtags.push_back(Hashtag{pair.second});
//     }
//     auto media_tree = tree.get_child("media", boost::property_tree::ptree());
//     for (auto& pair : media_tree) {
//         media.push_back(Media{pair.second});
//     }
//     auto urls_tree = tree.get_child("urls", boost::property_tree::ptree());
//     for (auto& pair : urls_tree) {
//         urls.push_back(URL{pair.second});
//     }
//     auto user_mentions_tree =
//         tree.get_child("user_mentions", boost::property_tree::ptree());
//     for (auto& pair : user_mentions_tree) {
//         user_mentions.push_back(User_mention{pair.second});
//     }
// }

}  // namespace twitter


text:
#include "frovedis/core/config.hpp"
#ifndef USE_CEREAL_FOR_EXRPC
#include <boost/integer.hpp>
#include "portable_iarchive.hpp"
#include "portable_oarchive.hpp"

// just instanciate archive
// see the comment of above headers
#endif

max_stars_repo_name: wmeddie/frovedis

max_issues_repo_name: wmeddie/frovedis

max_forks_repo_name: wmeddie/frovedis