<commit_before>#ifndef CAFFE_MOLGRID_DATA_LAYER_HPP_
#define CAFFE_MOLGRID_DATA_LAYER_HPP_

#include <string>
#include <utility>
#include <vector>

#include <boost/array.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/unordered_map.hpp>
#include <boost/math/quaternion.hpp>
#include <boost/multi_array/multi_array_ref.hpp>
#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/proto/caffe.pb.h"

#include "gnina/src/lib/atom_constants.h"
#include "gnina/src/lib/gridmaker.h"

namespace caffe {

/**
 * @brief Provides data to the Net from n-dimension  files of raw floating point data.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class MolGridDataLayer : public BaseDataLayer<Dtype> {
 public:
  explicit MolGridDataLayer(const LayerParameter& param)
      : BaseDataLayer<Dtype>(param), actives_pos_(0),
        decoys_pos_(0), all_pos_(0), num_rotations(0), current_rotation(0),
        example_size(0),balanced(false),inmem(false),
				resolution(0.5), dimension(23.5), radiusmultiple(1.5), randtranslate(0),
				binary(false), randrotate(false), dim(0), numgridpoints(0),
				numReceptorTypes(0),numLigandTypes(0), gpu_alloc_size(0),
				gpu_gridatoms(NULL), gpu_gridwhich(NULL) {}
  virtual ~MolGridDataLayer();
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  virtual inline const char* type() const { return "MolGridData"; }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int ExactNumTopBlobs() const { return 2; }

  virtual inline void resetRotation() { current_rotation = 0; }

  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  //set in memory buffer
  template<typename Atom>
  void setReceptor(const vector<Atom>& receptor)
  {
    //make this a template mostly so I don't have to pull in gnina atom class
    mem_rec.atoms.clear();
    mem_rec.whichGrid.clear();

    //receptor atoms
    for(unsigned i = 0, n = receptor.size(); i < n; i++)
    {
      const Atom& a = receptor[i];
      smt t = a.sm;
      float4 ainfo;
      ainfo.x = a.coords[0];
      ainfo.y = a.coords[1];
      ainfo.z = a.coords[2];
      ainfo.w = xs_radius(t);
      mem_rec.atoms.push_back(ainfo);
      mem_rec.whichGrid.push_back(rmap[t]);
    }
  }

  //set in memory buffer
  template<typename Atom, typename Vec3>
  void setLigand(const vector<Atom>& ligand, const vector<Vec3>& coords)
  {
    //ligand atoms, grid positions offset and coordinates are specified separately
    vec center(0,0,0);
    unsigned acnt = 0;
    for(unsigned i = 0, n = ligand.size(); i < n; i++)
    {
      smt t = ligand[i].sm;
      if(lmap[t] >= 0)
      {
        const Vec3& coord = coords[i];
        float4 ainfo;
        ainfo.x = coord[0];
        ainfo.y = coord[1];
        ainfo.z = coord[2];
        ainfo.w = xs_radius(t);
        mem_lig.atoms.push_back(ainfo);
        mem_lig.whichGrid.push_back(lmap[t]+numReceptorTypes);
        center += coord;
	acnt++;
      }
    }
    center /= acnt; //not ligand.size() because of hydrogens

    mem_lig.center = center;
  }

 protected:

  typedef GridMaker::quaternion quaternion;
  typedef typename boost::multi_array_ref<Dtype, 4>  Grids;

  struct example
	{
  	string receptor;
  	string ligand;
  	Dtype label;

  	example(): label(0) {}
  	example(Dtype l, const string& r, const string& lig): receptor(r), ligand(lig), label(l) {}
	};

  virtual void Shuffle();

  vector<example> actives_;
  vector<example> decoys_;
  vector<example> all_;
  string root_folder;
  int actives_pos_, decoys_pos_, all_pos_;
  unsigned num_rotations;
  unsigned current_rotation;
  unsigned example_size; //channels*numgridpoints
  vector<int> top_shape;
  bool balanced;
  bool inmem;
  vector<Dtype> labels;

  //grid stuff
  GridMaker gmaker;
  double resolution;
  double dimension;
  double radiusmultiple; //extra to consider past vdw radius
  double randtranslate;
  bool binary; //produce binary occupancies
  bool randrotate;

  unsigned dim; //grid points on one side
  unsigned numgridpoints; //dim*dim*dim

  vector<int> rmap; //map atom types to position in grid vectors
  vector<int> lmap;
  unsigned numReceptorTypes;
  unsigned numLigandTypes;

  unsigned gpu_alloc_size;
  float4 *gpu_gridatoms;
  short *gpu_gridwhich;

  void allocateGPUMem(unsigned sz);

  struct mol_info {
    vector<float4> atoms;
    vector<short> whichGrid; //separate for better memory layout on gpu
    vec center; //precalculate centroid, includes any random translation
    boost::array< pair<float, float>, 3> dims;

    mol_info() { center[0] = center[1] = center[2] = 0;}

    void append(const mol_info& a)
    {
      atoms.insert(atoms.end(), a.atoms.begin(), a.atoms.end());
      whichGrid.insert(whichGrid.end(), a.whichGrid.begin(), a.whichGrid.end());
    }
  };

  boost::unordered_map<string, mol_info> molcache;
  mol_info mem_rec; //molecular data set programmatically with setMemory
  mol_info mem_lig; //molecular data set programmatically with setMemory

  quaternion axial_quaternion();
  void set_mol_info(const string& file, const vector<int>& atommap, unsigned atomoffset, mol_info& minfo);
  void set_grid_ex(Dtype *grid, const example& ex, bool gpu);
  void set_grid_minfo(Dtype *grid, const mol_info& recatoms, const mol_info& ligatoms, bool gpu);

  void forward(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top, bool gpu);
};

}  // namespace caffe

#endif  // CAFFE_MOLGRID_DATA_LAYER_HPP_
<commit_msg>fix reinit bug<commit_after>#ifndef CAFFE_MOLGRID_DATA_LAYER_HPP_
#define CAFFE_MOLGRID_DATA_LAYER_HPP_

#include <string>
#include <utility>
#include <vector>

#include <boost/array.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/unordered_map.hpp>
#include <boost/math/quaternion.hpp>
#include <boost/multi_array/multi_array_ref.hpp>
#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/proto/caffe.pb.h"

#include "gnina/src/lib/atom_constants.h"
#include "gnina/src/lib/gridmaker.h"

namespace caffe {

/**
 * @brief Provides data to the Net from n-dimension  files of raw floating point data.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class MolGridDataLayer : public BaseDataLayer<Dtype> {
 public:
  explicit MolGridDataLayer(const LayerParameter& param)
      : BaseDataLayer<Dtype>(param), actives_pos_(0),
        decoys_pos_(0), all_pos_(0), num_rotations(0), current_rotation(0),
        example_size(0),balanced(false),inmem(false),
				resolution(0.5), dimension(23.5), radiusmultiple(1.5), randtranslate(0),
				binary(false), randrotate(false), dim(0), numgridpoints(0),
				numReceptorTypes(0),numLigandTypes(0), gpu_alloc_size(0),
				gpu_gridatoms(NULL), gpu_gridwhich(NULL) {}
  virtual ~MolGridDataLayer();
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  virtual inline const char* type() const { return "MolGridData"; }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int ExactNumTopBlobs() const { return 2; }

  virtual inline void resetRotation() { current_rotation = 0; }

  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  //set in memory buffer
  template<typename Atom>
  void setReceptor(const vector<Atom>& receptor)
  {
    //make this a template mostly so I don't have to pull in gnina atom class
    mem_rec.atoms.clear();
    mem_rec.whichGrid.clear();

    //receptor atoms
    for(unsigned i = 0, n = receptor.size(); i < n; i++)
    {
      const Atom& a = receptor[i];
      smt t = a.sm;
      float4 ainfo;
      ainfo.x = a.coords[0];
      ainfo.y = a.coords[1];
      ainfo.z = a.coords[2];
      ainfo.w = xs_radius(t);
      mem_rec.atoms.push_back(ainfo);
      mem_rec.whichGrid.push_back(rmap[t]);
    }
  }

  //set in memory buffer
  template<typename Atom, typename Vec3>
  void setLigand(const vector<Atom>& ligand, const vector<Vec3>& coords)
  {
    mem_lig.atoms.clear();
    mem_lig.whichGrid.clear();
    //ligand atoms, grid positions offset and coordinates are specified separately
    vec center(0,0,0);
    unsigned acnt = 0;
    for(unsigned i = 0, n = ligand.size(); i < n; i++)
    {
      smt t = ligand[i].sm;
      if(lmap[t] >= 0)
      {
        const Vec3& coord = coords[i];
        float4 ainfo;
        ainfo.x = coord[0];
        ainfo.y = coord[1];
        ainfo.z = coord[2];
        ainfo.w = xs_radius(t);
        mem_lig.atoms.push_back(ainfo);
        mem_lig.whichGrid.push_back(lmap[t]+numReceptorTypes);
        center += coord;
        acnt++;
      }
    }
    center /= acnt; //not ligand.size() because of hydrogens

    mem_lig.center = center;
  }

 protected:

  typedef GridMaker::quaternion quaternion;
  typedef typename boost::multi_array_ref<Dtype, 4>  Grids;

  struct example
	{
  	string receptor;
  	string ligand;
  	Dtype label;

  	example(): label(0) {}
  	example(Dtype l, const string& r, const string& lig): receptor(r), ligand(lig), label(l) {}
	};

  virtual void Shuffle();

  vector<example> actives_;
  vector<example> decoys_;
  vector<example> all_;
  string root_folder;
  int actives_pos_, decoys_pos_, all_pos_;
  unsigned num_rotations;
  unsigned current_rotation;
  unsigned example_size; //channels*numgridpoints
  vector<int> top_shape;
  bool balanced;
  bool inmem;
  vector<Dtype> labels;

  //grid stuff
  GridMaker gmaker;
  double resolution;
  double dimension;
  double radiusmultiple; //extra to consider past vdw radius
  double randtranslate;
  bool binary; //produce binary occupancies
  bool randrotate;

  unsigned dim; //grid points on one side
  unsigned numgridpoints; //dim*dim*dim

  vector<int> rmap; //map atom types to position in grid vectors
  vector<int> lmap;
  unsigned numReceptorTypes;
  unsigned numLigandTypes;

  unsigned gpu_alloc_size;
  float4 *gpu_gridatoms;
  short *gpu_gridwhich;

  void allocateGPUMem(unsigned sz);

  struct mol_info {
    vector<float4> atoms;
    vector<short> whichGrid; //separate for better memory layout on gpu
    vec center; //precalculate centroid, includes any random translation
    boost::array< pair<float, float>, 3> dims;

    mol_info() { center[0] = center[1] = center[2] = 0;}

    void append(const mol_info& a)
    {
      atoms.insert(atoms.end(), a.atoms.begin(), a.atoms.end());
      whichGrid.insert(whichGrid.end(), a.whichGrid.begin(), a.whichGrid.end());
    }
  };

  boost::unordered_map<string, mol_info> molcache;
  mol_info mem_rec; //molecular data set programmatically with setMemory
  mol_info mem_lig; //molecular data set programmatically with setMemory

  quaternion axial_quaternion();
  void set_mol_info(const string& file, const vector<int>& atommap, unsigned atomoffset, mol_info& minfo);
  void set_grid_ex(Dtype *grid, const example& ex, bool gpu);
  void set_grid_minfo(Dtype *grid, const mol_info& recatoms, const mol_info& ligatoms, bool gpu);

  void forward(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top, bool gpu);
};

}  // namespace caffe

#endif  // CAFFE_MOLGRID_DATA_LAYER_HPP_
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkQuadraturePointsGenerator.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

#include "vtkQuadraturePointsGenerator.h"

#include "vtkUnstructuredGrid.h"
#include "vtkPolyData.h"
#include "vtkPoints.h"
#include "vtkType.h"
#include "vtkDoubleArray.h"
#include "vtkDataArray.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkCellType.h"
#include "vtkCellArray.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkUnstructuredGridAlgorithm.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h"
#include "vtkObjectFactory.h"
#include "vtkDataSetAttributes.h"

#include "vtksys/ios/sstream"
using vtksys_ios::ostringstream;

#include "vtkQuadratureSchemeDefinition.h"
#include "vtkQuadraturePointsUtilities.hxx"

vtkCxxRevisionMacro(vtkQuadraturePointsGenerator, "1.15");
vtkStandardNewMacro(vtkQuadraturePointsGenerator);

//-----------------------------------------------------------------------------
vtkQuadraturePointsGenerator::vtkQuadraturePointsGenerator()
{
  this->SetNumberOfInputPorts(1);
  this->SetNumberOfOutputPorts(1);
}

//-----------------------------------------------------------------------------
vtkQuadraturePointsGenerator::~vtkQuadraturePointsGenerator()
{
}

//-----------------------------------------------------------------------------
int vtkQuadraturePointsGenerator::FillInputPortInformation(int vtkNotUsed(port),
    vtkInformation *info)
{
  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkUnstructuredGrid");
  return 1;
}

//-----------------------------------------------------------------------------
int vtkQuadraturePointsGenerator::RequestData(vtkInformation *,
    vtkInformationVector **input, vtkInformationVector *output)
{
  vtkDataObject *tmpDataObj;
  // Get the input.
  tmpDataObj = input[0]->GetInformationObject(0)->Get(
      vtkDataObject::DATA_OBJECT());
  vtkUnstructuredGrid *usgIn = vtkUnstructuredGrid::SafeDownCast(tmpDataObj);
  // Get the output.
  tmpDataObj = output->GetInformationObject(0)->Get(
      vtkDataObject::DATA_OBJECT());
  vtkPolyData *pdOut = vtkPolyData::SafeDownCast(tmpDataObj);

  // Quick sanity check.
  if (usgIn == NULL || pdOut == NULL || usgIn->GetNumberOfCells() == 0
      || usgIn->GetNumberOfPoints() == 0 || usgIn->GetCellData() == NULL
      || usgIn->GetCellData()->GetNumberOfArrays() == 0)
    {
    vtkDebugMacro("Filter data has not been configured correctly. Aborting.");
    return 1;
    }

  // Generate points for the selected data array.
  this->Generate(usgIn, vtkIdTypeArray::SafeDownCast(
      this->GetInputArrayToProcess(0, input)), pdOut);

  return 1;
}

int vtkQuadraturePointsGenerator::GenerateField(vtkUnstructuredGrid *usgIn,
    vtkDataArray* data, vtkIdTypeArray* offsets, vtkPolyData* pdOut)
{
  vtkInformation *info = offsets->GetInformation();
  vtkInformationQuadratureSchemeDefinitionVectorKey *key =
      vtkQuadratureSchemeDefinition::DICTIONARY();
  if (!key->Has(info))
    {
    vtkDebugMacro("Dictionary is not present in array " << offsets->GetName() << " " << offsets << " Aborting." );
    return 0;
    }
  int dictSize = key->Size(info);
  vtkQuadratureSchemeDefinition **dict =
      new vtkQuadratureSchemeDefinition *[dictSize];
  key->GetRange(info, dict, 0, 0, dictSize);

  vtkIdType nVerts = pdOut->GetNumberOfPoints();

  vtkIdType cellId;
  vtkIdType ncell = usgIn->GetNumberOfCells();
  int cellType;
  // first lopp through all cells to check if a shallow copyy is possible
  bool shallowok = true;
  vtkIdType previous = -1;

  for (cellId = 0; cellId < ncell; cellId++)
    {
    vtkIdType offset = offsets->GetValue(cellId);
    if (offset != previous + 1)
      {
      shallowok = false;
      break;
      }
    cellType = usgIn->GetCellType(cellId);

    previous = offset + dict[cellType]->GetNumberOfQuadraturePoints();
    }
  if (previous + 1 != nVerts)
    shallowok = false;

  if (shallowok)
    {
    // ok, all the original cells are here, we can shallow copy the array
    // from input to output
    pdOut->GetPointData()->AddArray(data);
    }
  else
    {
    // in this case, we have to duplicate the valid tuples
    vtkDataArray *V_out = data->NewInstance();
    V_out->SetName(data->GetName());
    V_out->SetNumberOfComponents(data->GetNumberOfComponents());
    for (cellId = 0; cellId < ncell; cellId++)
      {
      vtkIdType offset = offsets->GetValue(cellId);
      cellType = usgIn->GetCellType(cellId);
      // a simple check to see if a scheme really exists for this cell type.
      // should not happen if the cell type has not been modified.
      if (dict[cellType] == NULL)
        continue;
      int np = dict[cellType]->GetNumberOfQuadraturePoints();
      for (int id = 0; id < np; id++)
        {
        V_out->InsertNextTuple(offset + id, data);
        }
      }
    V_out->Squeeze();
    pdOut->GetPointData()->AddArray(V_out);
    V_out->Delete();
    }

  delete[] dict;
  return 1;
}

//-----------------------------------------------------------------------------
int vtkQuadraturePointsGenerator::Generate(vtkUnstructuredGrid *usgIn,
    vtkIdTypeArray* offsets, vtkPolyData *pdOut)
{
  // First create the points, then grab the data from FieldData, and set it
  // as our point data.
  if (usgIn == NULL || offsets == NULL || pdOut == NULL)
    {
    vtkDebugMacro("vtkQuadraturePointsGenerator::Generate no correctly configured : offsets = " << offsets);
    return 0;
    }

  const char* offsetName = offsets->GetName();

  if (offsetName == NULL)
    {
    vtkDebugMacro("offset array has no name, Skipping");
    return 1;
    }

  // get the dictionnary
  vtkInformation *info = offsets->GetInformation();
  vtkInformationQuadratureSchemeDefinitionVectorKey *key =
      vtkQuadratureSchemeDefinition::DICTIONARY();
  if (!key->Has(info))
    {
    vtkDebugMacro("Dictionary is not present in array " << offsets->GetName() << " Aborting." );
    return 0;
    }
  int dictSize = key->Size(info);
  vtkQuadratureSchemeDefinition **dict =
      new vtkQuadratureSchemeDefinition *[dictSize];
  key->GetRange(info, dict, 0, 0, dictSize);

  // Grab the point set.
  vtkDataArray *X = usgIn->GetPoints()->GetData();
  int X_type = X->GetDataType();

  // Create the result array.
  vtkDoubleArray *qPts = vtkDoubleArray::New();
  vtkIdType nCells = usgIn->GetNumberOfCells();
  qPts->Allocate(3* nCells ); // Expect at least one point per cell
  qPts->SetNumberOfComponents(3);

  // For all cells interpolate.
  switch (X_type)
    {
    case VTK_DOUBLE:
      {
      vtkDoubleArray *X_d = static_cast<vtkDoubleArray *> (X);
      double *pX_d = X_d->GetPointer(0);
      if (!Interpolate(usgIn, nCells, pX_d, 3, dict, qPts, 0))
        {
        vtkDebugMacro("Failed to interpolate cell vertices "
            "to quadrature points. Aborting.");
        delete[] dict;
        return 0;
        }
      break;
      }
    case VTK_FLOAT:
      {
      vtkFloatArray *X_f = static_cast<vtkFloatArray *> (X);
      float *pX_f = X_f->GetPointer(0);
      if (!Interpolate(usgIn, nCells, pX_f, 3, dict, qPts, 0))
        {
        vtkDebugMacro("Failed to interpolate cell vertices "
            "to quadrature points. Aborting.");
        delete[] dict;
        return 0;
        }
      break;
      }
    }
  delete[] dict;

  // Add the interpolated quadrature points to the output
  vtkIdType nVerts = qPts->GetNumberOfTuples();
  vtkPoints *p = vtkPoints::New();
  p->SetDataTypeToDouble();
  p->SetData(qPts);
  qPts->Delete();
  pdOut->SetPoints(p);
  p->Delete();
  // Generate vertices at the quadrature points
  vtkIdTypeArray *va = vtkIdTypeArray::New();
  va->SetNumberOfTuples(2* nVerts );
  vtkIdType *verts = va->GetPointer(0);
  for (int i = 0; i < nVerts; ++i)
    {
    verts[0] = 1;
    verts[1] = i;
    verts += 2;
    }
  vtkCellArray *cells = vtkCellArray::New();
  cells->SetCells(static_cast<vtkIdType> (nVerts), va);
  pdOut->SetVerts(cells);
  cells->Delete();
  va->Delete();

  // then loop over all fields to map the field array to the points
  for (int i = 0; i < usgIn->GetFieldData()->GetNumberOfArrays(); i++)
    {
    vtkDataArray* array = usgIn->GetFieldData()->GetArray(i);
    if (array == NULL)
      continue;

    const char* arrayOffsetName = array->GetInformation()->Get(
        vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME());
    if (arrayOffsetName == NULL)
      {
      vtkDebugMacro("array " << array->GetName() << " has no offset array name, Skipping");
      continue;
      }

    if (strcmp(offsetName, arrayOffsetName) != 0)
      {
      vtkDebugMacro("array " << array->GetName() << " has another offset array : " << arrayOffsetName << ", Skipping");
      continue;
      }

    this->GenerateField(usgIn, array, offsets, pdOut);
    }

  return 1;
}

//-----------------------------------------------------------------------------
void vtkQuadraturePointsGenerator::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
<commit_msg>BUG: Added support for Component Names to vtkQuadraturePointsGenerator.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkQuadraturePointsGenerator.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

#include "vtkQuadraturePointsGenerator.h"

#include "vtkUnstructuredGrid.h"
#include "vtkPolyData.h"
#include "vtkPoints.h"
#include "vtkType.h"
#include "vtkDoubleArray.h"
#include "vtkDataArray.h"
#include "vtkPointData.h"
#include "vtkCellData.h"
#include "vtkCellType.h"
#include "vtkCellArray.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkUnstructuredGridAlgorithm.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkInformationQuadratureSchemeDefinitionVectorKey.h"
#include "vtkObjectFactory.h"
#include "vtkDataSetAttributes.h"

#include "vtksys/ios/sstream"
using vtksys_ios::ostringstream;

#include "vtkQuadratureSchemeDefinition.h"
#include "vtkQuadraturePointsUtilities.hxx"

vtkCxxRevisionMacro(vtkQuadraturePointsGenerator, "1.16");
vtkStandardNewMacro(vtkQuadraturePointsGenerator);

//-----------------------------------------------------------------------------
vtkQuadraturePointsGenerator::vtkQuadraturePointsGenerator()
{
  this->SetNumberOfInputPorts(1);
  this->SetNumberOfOutputPorts(1);
}

//-----------------------------------------------------------------------------
vtkQuadraturePointsGenerator::~vtkQuadraturePointsGenerator()
{
}

//-----------------------------------------------------------------------------
int vtkQuadraturePointsGenerator::FillInputPortInformation(int vtkNotUsed(port),
    vtkInformation *info)
{
  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkUnstructuredGrid");
  return 1;
}

//-----------------------------------------------------------------------------
int vtkQuadraturePointsGenerator::RequestData(vtkInformation *,
    vtkInformationVector **input, vtkInformationVector *output)
{
  vtkDataObject *tmpDataObj;
  // Get the input.
  tmpDataObj = input[0]->GetInformationObject(0)->Get(
      vtkDataObject::DATA_OBJECT());
  vtkUnstructuredGrid *usgIn = vtkUnstructuredGrid::SafeDownCast(tmpDataObj);
  // Get the output.
  tmpDataObj = output->GetInformationObject(0)->Get(
      vtkDataObject::DATA_OBJECT());
  vtkPolyData *pdOut = vtkPolyData::SafeDownCast(tmpDataObj);

  // Quick sanity check.
  if (usgIn == NULL || pdOut == NULL || usgIn->GetNumberOfCells() == 0
      || usgIn->GetNumberOfPoints() == 0 || usgIn->GetCellData() == NULL
      || usgIn->GetCellData()->GetNumberOfArrays() == 0)
    {
    vtkDebugMacro("Filter data has not been configured correctly. Aborting.");
    return 1;
    }

  // Generate points for the selected data array.
  this->Generate(usgIn, vtkIdTypeArray::SafeDownCast(
      this->GetInputArrayToProcess(0, input)), pdOut);

  return 1;
}

int vtkQuadraturePointsGenerator::GenerateField(vtkUnstructuredGrid *usgIn,
    vtkDataArray* data, vtkIdTypeArray* offsets, vtkPolyData* pdOut)
{
  vtkInformation *info = offsets->GetInformation();
  vtkInformationQuadratureSchemeDefinitionVectorKey *key =
      vtkQuadratureSchemeDefinition::DICTIONARY();
  if (!key->Has(info))
    {
    vtkDebugMacro("Dictionary is not present in array " << offsets->GetName() << " " << offsets << " Aborting." );
    return 0;
    }
  int dictSize = key->Size(info);
  vtkQuadratureSchemeDefinition **dict =
      new vtkQuadratureSchemeDefinition *[dictSize];
  key->GetRange(info, dict, 0, 0, dictSize);

  vtkIdType nVerts = pdOut->GetNumberOfPoints();

  vtkIdType cellId;
  vtkIdType ncell = usgIn->GetNumberOfCells();
  int cellType;
  // first lopp through all cells to check if a shallow copyy is possible
  bool shallowok = true;
  vtkIdType previous = -1;

  for (cellId = 0; cellId < ncell; cellId++)
    {
    vtkIdType offset = offsets->GetValue(cellId);
    if (offset != previous + 1)
      {
      shallowok = false;
      break;
      }
    cellType = usgIn->GetCellType(cellId);

    previous = offset + dict[cellType]->GetNumberOfQuadraturePoints();
    }
  if (previous + 1 != nVerts)
    shallowok = false;

  if (shallowok)
    {
    // ok, all the original cells are here, we can shallow copy the array
    // from input to output
    pdOut->GetPointData()->AddArray(data);
    }
  else
    {
    // in this case, we have to duplicate the valid tuples
    vtkDataArray *V_out = data->NewInstance();
    V_out->SetName(data->GetName());
    V_out->SetNumberOfComponents(data->GetNumberOfComponents());
    V_out->CopyComponentNames( data );
    for (cellId = 0; cellId < ncell; cellId++)
      {
      vtkIdType offset = offsets->GetValue(cellId);
      cellType = usgIn->GetCellType(cellId);
      // a simple check to see if a scheme really exists for this cell type.
      // should not happen if the cell type has not been modified.
      if (dict[cellType] == NULL)
        continue;
      int np = dict[cellType]->GetNumberOfQuadraturePoints();
      for (int id = 0; id < np; id++)
        {
        V_out->InsertNextTuple(offset + id, data);
        }
      }
    V_out->Squeeze();
    pdOut->GetPointData()->AddArray(V_out);
    V_out->Delete();
    }

  delete[] dict;
  return 1;
}

//-----------------------------------------------------------------------------
int vtkQuadraturePointsGenerator::Generate(vtkUnstructuredGrid *usgIn,
    vtkIdTypeArray* offsets, vtkPolyData *pdOut)
{
  // First create the points, then grab the data from FieldData, and set it
  // as our point data.
  if (usgIn == NULL || offsets == NULL || pdOut == NULL)
    {
    vtkDebugMacro("vtkQuadraturePointsGenerator::Generate no correctly configured : offsets = " << offsets);
    return 0;
    }

  const char* offsetName = offsets->GetName();

  if (offsetName == NULL)
    {
    vtkDebugMacro("offset array has no name, Skipping");
    return 1;
    }

  // get the dictionnary
  vtkInformation *info = offsets->GetInformation();
  vtkInformationQuadratureSchemeDefinitionVectorKey *key =
      vtkQuadratureSchemeDefinition::DICTIONARY();
  if (!key->Has(info))
    {
    vtkDebugMacro("Dictionary is not present in array " << offsets->GetName() << " Aborting." );
    return 0;
    }
  int dictSize = key->Size(info);
  vtkQuadratureSchemeDefinition **dict =
      new vtkQuadratureSchemeDefinition *[dictSize];
  key->GetRange(info, dict, 0, 0, dictSize);

  // Grab the point set.
  vtkDataArray *X = usgIn->GetPoints()->GetData();
  int X_type = X->GetDataType();

  // Create the result array.
  vtkDoubleArray *qPts = vtkDoubleArray::New();
  vtkIdType nCells = usgIn->GetNumberOfCells();
  qPts->Allocate(3* nCells ); // Expect at least one point per cell
  qPts->SetNumberOfComponents(3);

  // For all cells interpolate.
  switch (X_type)
    {
    case VTK_DOUBLE:
      {
      vtkDoubleArray *X_d = static_cast<vtkDoubleArray *> (X);
      double *pX_d = X_d->GetPointer(0);
      if (!Interpolate(usgIn, nCells, pX_d, 3, dict, qPts, 0))
        {
        vtkDebugMacro("Failed to interpolate cell vertices "
            "to quadrature points. Aborting.");
        delete[] dict;
        return 0;
        }
      break;
      }
    case VTK_FLOAT:
      {
      vtkFloatArray *X_f = static_cast<vtkFloatArray *> (X);
      float *pX_f = X_f->GetPointer(0);
      if (!Interpolate(usgIn, nCells, pX_f, 3, dict, qPts, 0))
        {
        vtkDebugMacro("Failed to interpolate cell vertices "
            "to quadrature points. Aborting.");
        delete[] dict;
        return 0;
        }
      break;
      }
    }
  delete[] dict;

  // Add the interpolated quadrature points to the output
  vtkIdType nVerts = qPts->GetNumberOfTuples();
  vtkPoints *p = vtkPoints::New();
  p->SetDataTypeToDouble();
  p->SetData(qPts);
  qPts->Delete();
  pdOut->SetPoints(p);
  p->Delete();
  // Generate vertices at the quadrature points
  vtkIdTypeArray *va = vtkIdTypeArray::New();
  va->SetNumberOfTuples(2* nVerts );
  vtkIdType *verts = va->GetPointer(0);
  for (int i = 0; i < nVerts; ++i)
    {
    verts[0] = 1;
    verts[1] = i;
    verts += 2;
    }
  vtkCellArray *cells = vtkCellArray::New();
  cells->SetCells(static_cast<vtkIdType> (nVerts), va);
  pdOut->SetVerts(cells);
  cells->Delete();
  va->Delete();

  // then loop over all fields to map the field array to the points
  for (int i = 0; i < usgIn->GetFieldData()->GetNumberOfArrays(); i++)
    {
    vtkDataArray* array = usgIn->GetFieldData()->GetArray(i);
    if (array == NULL)
      continue;

    const char* arrayOffsetName = array->GetInformation()->Get(
        vtkQuadratureSchemeDefinition::QUADRATURE_OFFSET_ARRAY_NAME());
    if (arrayOffsetName == NULL)
      {
      vtkDebugMacro("array " << array->GetName() << " has no offset array name, Skipping");
      continue;
      }

    if (strcmp(offsetName, arrayOffsetName) != 0)
      {
      vtkDebugMacro("array " << array->GetName() << " has another offset array : " << arrayOffsetName << ", Skipping");
      continue;
      }

    this->GenerateField(usgIn, array, offsets, pdOut);
    }

  return 1;
}

//-----------------------------------------------------------------------------
void vtkQuadraturePointsGenerator::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
<|endoftext|>


<commit_before>// evaluate.cpp -- evaluate energies from a Database

#include "database.h"
#include "structure.h"
#include "optimizer.h"
#include "coin/IpIpoptApplication.hpp"
#include "coin/IpSolveStatistics.hpp"
#include "opt_Gibbs.h"
#include <iostream>
#include <fstream>

using namespace Ipopt;

void evaluate(const Database &DB, const evalconditions &conditions) {
	Phase_Collection phase_col;
	// TODO: temporary code for suspending all phases but FCC and liquid
	for (auto i = DB.get_phase_iterator(); i != DB.get_phase_iterator_end(); ++i) {
		if (i->first == "FCC_A1" || i->first == "LIQUID") {
			phase_col[i->first] = i->second;
		}
	}

	const Phase_Collection::const_iterator phase_iter = phase_col.cbegin();
	const Phase_Collection::const_iterator phase_end = phase_col.cend();

	// TODO: check validity of conditions

	// Create an instance of your nlp...
	SmartPtr<TNLP> mynlp = new GibbsOpt(phase_iter, phase_end, conditions);

	// Create an instance of the IpoptApplication
	//
	// We are using the factory, since this allows us to compile this
	// example with an Ipopt Windows DLL
	SmartPtr<IpoptApplication> app = IpoptApplicationFactory();

	app->Options()->SetStringValue("derivative_test","first-order");
	app->Options()->SetStringValue("hessian_approximation","limited-memory");
	app->Options()->SetIntegerValue("print_level",12);
	app->Options()->SetStringValue("derivative_test_print_all","yes");

	// Initialize the IpoptApplication and process the options
	ApplicationReturnStatus status;
	status = app->Initialize();
	if (status != Solve_Succeeded) {
		std::cout << std::endl << std::endl << "*** Error during initialization!" << std::endl;
		return;
	}

	status = app->OptimizeTNLP(mynlp);

	if (status == Solve_Succeeded) {
		// Retrieve some statistics about the solve
		Index iter_count = app->Statistics()->IterationCount();
		std::cout << std::endl << std::endl << "*** The problem solved in " << iter_count << " iterations!" << std::endl;

		Number final_obj = app->Statistics()->FinalObjective();
		std::cout << std::endl << std::endl << "*** The final value of the objective function is " << final_obj << '.' << std::endl;
	}
}<commit_msg>Disabled Ipopt debug printing.<commit_after>// evaluate.cpp -- evaluate energies from a Database

#include "database.h"
#include "structure.h"
#include "optimizer.h"
#include "coin/IpIpoptApplication.hpp"
#include "coin/IpSolveStatistics.hpp"
#include "opt_Gibbs.h"
#include <iostream>
#include <fstream>

using namespace Ipopt;

void evaluate(const Database &DB, const evalconditions &conditions) {
	Phase_Collection phase_col;
	// TODO: temporary code for suspending all phases but FCC and liquid
	for (auto i = DB.get_phase_iterator(); i != DB.get_phase_iterator_end(); ++i) {
		if (i->first == "FCC_A1" || i->first == "LIQUID") {
			phase_col[i->first] = i->second;
		}
	}

	const Phase_Collection::const_iterator phase_iter = phase_col.cbegin();
	const Phase_Collection::const_iterator phase_end = phase_col.cend();

	// TODO: check validity of conditions

	// Create an instance of your nlp...
	SmartPtr<TNLP> mynlp = new GibbsOpt(phase_iter, phase_end, conditions);

	// Create an instance of the IpoptApplication
	//
	// We are using the factory, since this allows us to compile this
	// example with an Ipopt Windows DLL
	SmartPtr<IpoptApplication> app = IpoptApplicationFactory();

	app->Options()->SetStringValue("derivative_test","first-order");
	app->Options()->SetStringValue("hessian_approximation","limited-memory");
	//app->Options()->SetIntegerValue("print_level",12);
	app->Options()->SetStringValue("derivative_test_print_all","yes");

	// Initialize the IpoptApplication and process the options
	ApplicationReturnStatus status;
	status = app->Initialize();
	if (status != Solve_Succeeded) {
		std::cout << std::endl << std::endl << "*** Error during initialization!" << std::endl;
		return;
	}

	status = app->OptimizeTNLP(mynlp);

	if (status == Solve_Succeeded) {
		// Retrieve some statistics about the solve
		Index iter_count = app->Statistics()->IterationCount();
		std::cout << std::endl << std::endl << "*** The problem solved in " << iter_count << " iterations!" << std::endl;

		Number final_obj = app->Statistics()->FinalObjective();
		std::cout << std::endl << std::endl << "*** The final value of the objective function is " << final_obj << '.' << std::endl;
	}
}<|endoftext|>


<commit_before>#ifndef CAFFE_MOLGRID_DATA_LAYER_HPP_
#define CAFFE_MOLGRID_DATA_LAYER_HPP_

#include <string>
#include <utility>
#include <vector>

#include <boost/array.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/unordered_map.hpp>
#include <boost/math/quaternion.hpp>
#include <boost/multi_array/multi_array_ref.hpp>
#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/proto/caffe.pb.h"

#include "gnina/src/lib/atom_constants.h"
#include "gnina/src/lib/gridmaker.h"

namespace caffe {

/**
 * @brief Provides data to the Net from n-dimension  files of raw floating point data.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class MolGridDataLayer : public BaseDataLayer<Dtype> {
 public:
  explicit MolGridDataLayer(const LayerParameter& param)
      : BaseDataLayer<Dtype>(param), actives_pos_(0),
        decoys_pos_(0), all_pos_(0), num_rotations(0), current_rotation(0),
        example_size(0),balanced(false),inmem(false),
				resolution(0.5), dimension(23.5), radiusmultiple(1.5), randtranslate(0),
				binary(false), randrotate(false), dim(0), numgridpoints(0),
				numReceptorTypes(0),numLigandTypes(0), gpu_alloc_size(0),
				gpu_gridatoms(NULL), gpu_gridwhich(NULL) {}
  virtual ~MolGridDataLayer();
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  virtual inline const char* type() const { return "NDimData"; }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int ExactNumTopBlobs() const { return 2; }

  virtual inline void resetRotation() { current_rotation = 0; }

  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  //set in memory buffer
  template<typename Atom>
  void setReceptor(const vector<Atom>& receptor)
  {
    //make this a template mostly so I don't have to pull in gnina atom class
    mem_rec.atoms.clear();
    mem_rec.whichGrid.clear();

    //receptor atoms
    for(unsigned i = 0, n = receptor.size(); i < n; i++)
    {
      const Atom& a = receptor[i];
      smt t = a.sm;
      float4 ainfo;
      ainfo.x = a.coords[0];
      ainfo.y = a.coords[1];
      ainfo.z = a.coords[2];
      ainfo.w = xs_radius(t);
      mem_rec.atoms.push_back(ainfo);
      mem_rec.whichGrid.push_back(rmap[t]);
    }
  }

  //set in memory buffer
  template<typename Atom, typename Vec3>
  void setLigand(const vector<Atom>& ligand, const vector<Vec3>& coords)
  {
    //ligand atoms, grid positions offset and coordinates are specified separately
    vec center(0,0,0);
    unsigned acnt = 0;
    for(unsigned i = 0, n = ligand.size(); i < n; i++)
    {
      smt t = ligand[i].sm;
      if(lmap[t] >= 0)
      {
        const Vec3& coord = coords[i];
        float4 ainfo;
        ainfo.x = coord[0];
        ainfo.y = coord[1];
        ainfo.z = coord[2];
        ainfo.w = xs_radius(t);
        mem_lig.atoms.push_back(ainfo);
        mem_lig.whichGrid.push_back(lmap[t]+numReceptorTypes);
        center += coord;
	acnt++;
      }
    }
    center /= acnt; //not ligand.size() because of hydrogens

    mem_lig.center = center;
  }

 protected:

  typedef GridMaker::quaternion quaternion;
  typedef typename boost::multi_array_ref<Dtype, 4>  Grids;

  struct example
	{
  	string receptor;
  	string ligand;
  	Dtype label;

  	example(): label(0) {}
  	example(Dtype l, const string& r, const string& lig): receptor(r), ligand(lig), label(l) {}
	};

  virtual void Shuffle();

  vector<example> actives_;
  vector<example> decoys_;
  vector<example> all_;
  string root_folder;
  int actives_pos_, decoys_pos_, all_pos_;
  unsigned num_rotations;
  unsigned current_rotation;
  unsigned example_size; //channels*numgridpoints
  vector<int> top_shape;
  bool balanced;
  bool inmem;
  vector<Dtype> labels;

  //grid stuff
  GridMaker gmaker;
  double resolution;
  double dimension;
  double radiusmultiple; //extra to consider past vdw radius
  double randtranslate;
  bool binary; //produce binary occupancies
  bool randrotate;

  unsigned dim; //grid points on one side
  unsigned numgridpoints; //dim*dim*dim

  vector<int> rmap; //map atom types to position in grid vectors
  vector<int> lmap;
  unsigned numReceptorTypes;
  unsigned numLigandTypes;

  unsigned gpu_alloc_size;
  float4 *gpu_gridatoms;
  short *gpu_gridwhich;

  void allocateGPUMem(unsigned sz);

  struct mol_info {
    vector<float4> atoms;
    vector<short> whichGrid; //separate for better memory layout on gpu
    vec center; //precalculate centroid, includes any random translation
    boost::array< pair<float, float>, 3> dims;

    mol_info() { center[0] = center[1] = center[2] = 0;}

    void append(const mol_info& a)
    {
      atoms.insert(atoms.end(), a.atoms.begin(), a.atoms.end());
      whichGrid.insert(whichGrid.end(), a.whichGrid.begin(), a.whichGrid.end());
    }
  };

  boost::unordered_map<string, mol_info> molcache;
  mol_info mem_rec; //molecular data set programmatically with setMemory
  mol_info mem_lig; //molecular data set programmatically with setMemory

  quaternion axial_quaternion();
  void set_mol_info(const string& file, const vector<int>& atommap, unsigned atomoffset, mol_info& minfo);
  void set_grid_ex(Dtype *grid, const example& ex, bool gpu);
  void set_grid_minfo(Dtype *grid, const mol_info& recatoms, const mol_info& ligatoms, bool gpu);

  void forward(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top, bool gpu);
};

}  // namespace caffe

#endif  // CAFFE_MOLGRID_DATA_LAYER_HPP_
<commit_msg>bugfix layer name<commit_after>#ifndef CAFFE_MOLGRID_DATA_LAYER_HPP_
#define CAFFE_MOLGRID_DATA_LAYER_HPP_

#include <string>
#include <utility>
#include <vector>

#include <boost/array.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/unordered_map.hpp>
#include <boost/math/quaternion.hpp>
#include <boost/multi_array/multi_array_ref.hpp>
#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/proto/caffe.pb.h"

#include "gnina/src/lib/atom_constants.h"
#include "gnina/src/lib/gridmaker.h"

namespace caffe {

/**
 * @brief Provides data to the Net from n-dimension  files of raw floating point data.
 *
 * TODO(dox): thorough documentation for Forward and proto params.
 */
template <typename Dtype>
class MolGridDataLayer : public BaseDataLayer<Dtype> {
 public:
  explicit MolGridDataLayer(const LayerParameter& param)
      : BaseDataLayer<Dtype>(param), actives_pos_(0),
        decoys_pos_(0), all_pos_(0), num_rotations(0), current_rotation(0),
        example_size(0),balanced(false),inmem(false),
				resolution(0.5), dimension(23.5), radiusmultiple(1.5), randtranslate(0),
				binary(false), randrotate(false), dim(0), numgridpoints(0),
				numReceptorTypes(0),numLigandTypes(0), gpu_alloc_size(0),
				gpu_gridatoms(NULL), gpu_gridwhich(NULL) {}
  virtual ~MolGridDataLayer();
  virtual void DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  virtual inline const char* type() const { return "MolGridData"; }
  virtual inline int ExactNumBottomBlobs() const { return 0; }
  virtual inline int ExactNumTopBlobs() const { return 2; }

  virtual inline void resetRotation() { current_rotation = 0; }

  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  //set in memory buffer
  template<typename Atom>
  void setReceptor(const vector<Atom>& receptor)
  {
    //make this a template mostly so I don't have to pull in gnina atom class
    mem_rec.atoms.clear();
    mem_rec.whichGrid.clear();

    //receptor atoms
    for(unsigned i = 0, n = receptor.size(); i < n; i++)
    {
      const Atom& a = receptor[i];
      smt t = a.sm;
      float4 ainfo;
      ainfo.x = a.coords[0];
      ainfo.y = a.coords[1];
      ainfo.z = a.coords[2];
      ainfo.w = xs_radius(t);
      mem_rec.atoms.push_back(ainfo);
      mem_rec.whichGrid.push_back(rmap[t]);
    }
  }

  //set in memory buffer
  template<typename Atom, typename Vec3>
  void setLigand(const vector<Atom>& ligand, const vector<Vec3>& coords)
  {
    //ligand atoms, grid positions offset and coordinates are specified separately
    vec center(0,0,0);
    unsigned acnt = 0;
    for(unsigned i = 0, n = ligand.size(); i < n; i++)
    {
      smt t = ligand[i].sm;
      if(lmap[t] >= 0)
      {
        const Vec3& coord = coords[i];
        float4 ainfo;
        ainfo.x = coord[0];
        ainfo.y = coord[1];
        ainfo.z = coord[2];
        ainfo.w = xs_radius(t);
        mem_lig.atoms.push_back(ainfo);
        mem_lig.whichGrid.push_back(lmap[t]+numReceptorTypes);
        center += coord;
	acnt++;
      }
    }
    center /= acnt; //not ligand.size() because of hydrogens

    mem_lig.center = center;
  }

 protected:

  typedef GridMaker::quaternion quaternion;
  typedef typename boost::multi_array_ref<Dtype, 4>  Grids;

  struct example
	{
  	string receptor;
  	string ligand;
  	Dtype label;

  	example(): label(0) {}
  	example(Dtype l, const string& r, const string& lig): receptor(r), ligand(lig), label(l) {}
	};

  virtual void Shuffle();

  vector<example> actives_;
  vector<example> decoys_;
  vector<example> all_;
  string root_folder;
  int actives_pos_, decoys_pos_, all_pos_;
  unsigned num_rotations;
  unsigned current_rotation;
  unsigned example_size; //channels*numgridpoints
  vector<int> top_shape;
  bool balanced;
  bool inmem;
  vector<Dtype> labels;

  //grid stuff
  GridMaker gmaker;
  double resolution;
  double dimension;
  double radiusmultiple; //extra to consider past vdw radius
  double randtranslate;
  bool binary; //produce binary occupancies
  bool randrotate;

  unsigned dim; //grid points on one side
  unsigned numgridpoints; //dim*dim*dim

  vector<int> rmap; //map atom types to position in grid vectors
  vector<int> lmap;
  unsigned numReceptorTypes;
  unsigned numLigandTypes;

  unsigned gpu_alloc_size;
  float4 *gpu_gridatoms;
  short *gpu_gridwhich;

  void allocateGPUMem(unsigned sz);

  struct mol_info {
    vector<float4> atoms;
    vector<short> whichGrid; //separate for better memory layout on gpu
    vec center; //precalculate centroid, includes any random translation
    boost::array< pair<float, float>, 3> dims;

    mol_info() { center[0] = center[1] = center[2] = 0;}

    void append(const mol_info& a)
    {
      atoms.insert(atoms.end(), a.atoms.begin(), a.atoms.end());
      whichGrid.insert(whichGrid.end(), a.whichGrid.begin(), a.whichGrid.end());
    }
  };

  boost::unordered_map<string, mol_info> molcache;
  mol_info mem_rec; //molecular data set programmatically with setMemory
  mol_info mem_lig; //molecular data set programmatically with setMemory

  quaternion axial_quaternion();
  void set_mol_info(const string& file, const vector<int>& atommap, unsigned atomoffset, mol_info& minfo);
  void set_grid_ex(Dtype *grid, const example& ex, bool gpu);
  void set_grid_minfo(Dtype *grid, const mol_info& recatoms, const mol_info& ligatoms, bool gpu);

  void forward(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top, bool gpu);
};

}  // namespace caffe

#endif  // CAFFE_MOLGRID_DATA_LAYER_HPP_
<|endoftext|>


<commit_before>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * All rights reserved.                                                   *
 *                                                                        *
 * Primary Authors: Markus Fasel                                          *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
#include "AliHLTEMCALSTURawDigitMaker.h"
#include "AliCaloConstants.h"
#include "AliCaloRawAnalyzerFactory.h"
#include "AliCaloRawAnalyzerFakeALTRO.h"
#include "AliCaloRawStreamV3.h"
#include "AliDAQ.h"
#include "AliEMCALTriggerSTUDCSConfig.h"
#include "AliEMCALTriggerData.h"
#include "AliEMCALTriggerRawDigit.h"
#include "AliEMCALTriggerSTURawStream.h"
#include "AliHLTEMCALGeometry.h"
#include "AliRawEquipmentHeader.h"
#include "AliRawEvent.h"
#include "AliRawReader.h"
#include "AliRawVEquipment.h"

ClassImp(AliHLTEMCALSTURawDigitMaker)

AliHLTEMCALSTURawDigitMaker::AliHLTEMCALSTURawDigitMaker() :
TObject(),
AliHLTLogging(),
fkGeometryPtr(NULL),
fDCSConfigSTU(NULL),
fTriggerData(NULL),
fNRawDigits(0)
{
  fDCSConfigSTU = new AliEMCALTriggerSTUDCSConfig;
  fTriggerData = new AliEMCALTriggerData;
  for (Int_t i=0; i<fgkNRawDigits; i++) fRawDigitIndex[i] = -1;
}

AliHLTEMCALSTURawDigitMaker::~AliHLTEMCALSTURawDigitMaker() {
  if(fDCSConfigSTU) delete fDCSConfigSTU;
  if(fTriggerData) delete fTriggerData;
}

void AliHLTEMCALSTURawDigitMaker::ProcessSTUStream(AliEMCALTriggerSTURawStream *stustream, Int_t detector){

  HLTDebug("Start post processing the raw digit maker");
  Int_t idx;

  AliHLTCaloTriggerRawDigitDataStruct *hltdig(NULL);

  if (stustream && stustream->ReadPayLoad()) {
    fTriggerData->SetL1DataDecoded(1);

    for (int i = 0; i < 2; i++) {
      fTriggerData->SetL1GammaThreshold(i, stustream->GetL1GammaThreshold(i));
      fTriggerData->SetL1JetThreshold(  i, stustream->GetL1JetThreshold(i)  );
    }

    Int_t v0[2] = { static_cast<Int_t>(stustream->GetV0A()),  static_cast<Int_t>(stustream->GetV0C())};

    // Modify DCS config from STU payload content
    for(Int_t i = 0; i < 3; i++){
      for(Int_t j = 0; j < 2; j++){
        fDCSConfigSTU->SetG(i, j, stustream->GetG(i, j));
        fDCSConfigSTU->SetJ(i, j, stustream->GetJ(i, j));
      }
    }
    fDCSConfigSTU->SetRawData(stustream->GetRawData());
    fDCSConfigSTU->SetRegion(stustream->GetRegionEnable());
    fDCSConfigSTU->SetFw(stustream->GetFwVersion());

    fTriggerData->SetL1FrameMask(stustream->GetFrameReceived());
    fTriggerData->SetL1V0(v0);
    Int_t type[15] =
    {
      static_cast<Int_t>(stustream->GetG(0, 0)),
      static_cast<Int_t>(stustream->GetG(1, 0)),
      static_cast<Int_t>(stustream->GetG(2, 0)),
      static_cast<Int_t>(stustream->GetJ(0, 0)),
      static_cast<Int_t>(stustream->GetJ(1, 0)),
      static_cast<Int_t>(stustream->GetJ(2, 0)),
      static_cast<Int_t>(stustream->GetG(0, 1)),
      static_cast<Int_t>(stustream->GetG(1, 1)),
      static_cast<Int_t>(stustream->GetG(2, 1)),
      static_cast<Int_t>(stustream->GetJ(0, 1)),
      static_cast<Int_t>(stustream->GetJ(1, 1)),
      static_cast<Int_t>(stustream->GetJ(2, 1)),
      static_cast<Int_t>(stustream->GetRawData()),
      static_cast<Int_t>(stustream->GetRegionEnable()),
      static_cast<Int_t>(stustream->GetFwVersion())
    };
    fTriggerData->SetL1TriggerType(type);

    fTriggerData->SetL1RawData(stustream->GetRawData());

    Int_t iTRU, jTRU, x, y;

    TVector2 sizeL1gsubr, sizeL1gpatch, sizeL1jsubr, sizeL1jpatch;
    fDCSConfigSTU->GetSegmentation(sizeL1gsubr, sizeL1gpatch, sizeL1jsubr, sizeL1jpatch);

    if (stustream->GetRawData()) {
      HLTDebug("| STU => TRU raw data are there!\n");

      //Int_t nTRU = fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU();
      Int_t nTRU = detector == 0 ? 32 : 14;
      for (Int_t i = 0; i < nTRU; i++) {
        iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(i, detector);

        UInt_t adc[96]; for (Int_t j = 0; j < 96; j++) adc[j] = 0;

        stustream->GetADC(i, adc);

        for (Int_t j = 0; j < 96; j++) {
          if (adc[j] <= 0) continue;
          HLTDebug("| STU => TRU# %2d raw data: ADC# %2d: %d\n", iTRU, j, adc[j]);
          fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromTRU(iTRU, j, idx);
          SetL1TimeSum(GetRawDigit(idx), adc[j]);
        }
      }
    }

    // List of patches in EMCal coordinate system

    for (Int_t i = 0; i < stustream->GetNL0GammaPatch(); i++) {
      stustream->GetL0GammaPatch(i, iTRU, x);

      //if(iTRU >= 32) iTRU -= 32;
      iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(iTRU, detector);

      const Int_t sizePatchL0 = 4;

      HLTDebug("| STU => Found L0 patch id: %2d in TRU# %2d\n", x, iTRU);

      Int_t idFastOR[4];
      for (Int_t j = 0; j < 4; j++) idFastOR[j] = -1;

      if (fkGeometryPtr->GetGeometryPtr()->GetFastORIndexFromL0Index(iTRU, x, idFastOR, sizePatchL0)) {
        idx = idFastOR[1];

        Int_t px, py;
        if (fkGeometryPtr->GetGeometryPtr()->GetPositionInEMCALFromAbsFastORIndex(idx, px, py)){
          HLTDebug("| STU => Add L0 patch at (%2d , %2d)\n", px, py);
          SetTriggerBit(GetRawDigit(idx), kL0, 1);
        }
      }
    }

    Int_t vx, vy, lphi;
    for (int ithr = 0; ithr < 2; ithr++) {
      for (Int_t i = 0; i < stustream->GetNL1GammaPatch(ithr); i++) {
        if (stustream->GetL1GammaPatch(i, ithr, iTRU, x, y)) { // col (0..23), row (0..3)

          if (fkGeometryPtr->GetGeometryPtr()->GetTriggerMappingVersion() == 1) {
            // Run 1
            iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(iTRU, detector);

            HLTDebug("| STU => Found L1 gamma patch at (%2d , %2d) in TRU# %2d\n", x, y, iTRU);

            vx = 23 - x;
            vy = y + 4 * int(iTRU / 2); // Position in EMCal frame

            if (iTRU % 2) vx += 24; // C side

            vx = vx - int(sizeL1gsubr.X()) * int(sizeL1gpatch.X()) + 1;
            lphi = 64;
            if (vx >= 0 && vy < lphi) {
              if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(vx, vy, idx)) {
            	HLTDebug("| STU => Add L1 gamma [%d] patch at (%2d , %2d)\n", ithr, vx, vy, index);
            	SetTriggerBit(GetRawDigit(idx), kL1GammaHigh + ithr, 1);
              }
            }
          } else {
            // Run 2
            fkGeometryPtr->GetGeometryPtr()->GetTRUFromSTU(iTRU, x, y, jTRU, vx, vy, detector);
            fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInTRU(jTRU, vx, vy, idx);
            SetTriggerBit(GetRawDigit(idx), kL1GammaHigh + ithr, 1);
          }
        }
      }

      for (Int_t i = 0; i < stustream->GetNL1JetPatch(ithr); i++) {
        if (stustream->GetL1JetPatch(i, ithr, x, y)) { // col (0,15), row (0,11)
          HLTDebug("| STU => Found L1 jet [%d] patch at (%2d , %2d)\n", ithr, x, y);

          if (fkGeometryPtr->GetGeometryPtr()->GetTriggerMappingVersion() == 1) {
            vx = 11 - y - int(sizeL1jpatch.X()) + 1;
            vy = 15 - x - int(sizeL1jpatch.Y()) + 1;
          }
          else {
            vx = y;
            vy = x;
          }
          vx *= int(sizeL1jsubr.X());
          vy *= int(sizeL1jsubr.Y());

          if (vx >= 0 && vy >= 0) {
            if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(vx, vy, idx)) {
              HLTDebug("| STU => Add L1 jet patch at (%2d , %2d)\n", vx, vy);
              SetTriggerBit(GetRawDigit(idx), kL1JetHigh + ithr, 1);
            }
          }
        }
      }
    }

    if (detector == 1) {
      UInt_t sregion[36] = {0};
      stustream->GetPHOSSubregion(sregion);
      for (int isr=0;isr<36;isr++) {
        if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPHOSSubregion(isr, idx)) {
          SetL1SubRegion(GetRawDigit(idx), sregion[isr]);
        }
      }
    }
  }

  /*
  for(int idig = 0; idig < fNRawDigits; idig++){
    PrintRawDigit(fRawDigitBuffer[idig]);
  }
  */
}

Int_t AliHLTEMCALSTURawDigitMaker::WriteRawDigitsBuffer(AliHLTCaloTriggerRawDigitDataStruct *bufferptr, AliHLTUInt32_t &availableSize) const {
  Int_t outputsize = 0;
  for(Int_t idig = 0; idig < fNRawDigits; idig++){
	if(availableSize < sizeof(AliHLTCaloTriggerRawDigitDataStruct)){
		HLTWarning("Buffer exceeded after %d digits", idig);
		break;
	}
	if (fRawDigitBuffer[idig].fID < 0 || fRawDigitBuffer[idig].fID >= fgkNRawDigits)
	{
		HLTWarning("Invalid TRU Index in Output %d", fRawDigitBuffer[idig].fID);
		continue;
	}
    *bufferptr = fRawDigitBuffer[idig];
    bufferptr++;
    outputsize += sizeof(AliHLTCaloTriggerRawDigitDataStruct);
    availableSize -= sizeof(AliHLTCaloTriggerRawDigitDataStruct);
  }
  return outputsize;
}

void AliHLTEMCALSTURawDigitMaker::Reset() {
  for (Int_t i = 0; i < fgkNRawDigits; i++) fRawDigitIndex[i] = -1;
  fNRawDigits = 0;
  fTriggerData->Reset();
}

AliHLTCaloTriggerRawDigitDataStruct &AliHLTEMCALSTURawDigitMaker::GetRawDigit(Int_t index){
  if (index < 0){
    HLTWarning("Invalid STU Index %d", index);
    AliHLTCaloTriggerRawDigitDataStruct &dig = fRawDigitBuffer[fgkNRawDigits - 1];
    InitializeRawDigit(dig);
    return dig;
  }
  if(fRawDigitIndex[index] >= 0){
    return fRawDigitBuffer[fRawDigitIndex[index]];
  }

  fRawDigitIndex[index] = fNRawDigits;
  AliHLTCaloTriggerRawDigitDataStruct &dig = fRawDigitBuffer[fNRawDigits];
  InitializeRawDigit(dig);
  SetRawDigitID(dig, index);
  fNRawDigits++;
  return dig;
}
<commit_msg>fix number of args to HLTDebug<commit_after>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * All rights reserved.                                                   *
 *                                                                        *
 * Primary Authors: Markus Fasel                                          *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
#include "AliHLTEMCALSTURawDigitMaker.h"
#include "AliCaloConstants.h"
#include "AliCaloRawAnalyzerFactory.h"
#include "AliCaloRawAnalyzerFakeALTRO.h"
#include "AliCaloRawStreamV3.h"
#include "AliDAQ.h"
#include "AliEMCALTriggerSTUDCSConfig.h"
#include "AliEMCALTriggerData.h"
#include "AliEMCALTriggerRawDigit.h"
#include "AliEMCALTriggerSTURawStream.h"
#include "AliHLTEMCALGeometry.h"
#include "AliRawEquipmentHeader.h"
#include "AliRawEvent.h"
#include "AliRawReader.h"
#include "AliRawVEquipment.h"

ClassImp(AliHLTEMCALSTURawDigitMaker)

AliHLTEMCALSTURawDigitMaker::AliHLTEMCALSTURawDigitMaker() :
TObject(),
AliHLTLogging(),
fkGeometryPtr(NULL),
fDCSConfigSTU(NULL),
fTriggerData(NULL),
fNRawDigits(0)
{
  fDCSConfigSTU = new AliEMCALTriggerSTUDCSConfig;
  fTriggerData = new AliEMCALTriggerData;
  for (Int_t i=0; i<fgkNRawDigits; i++) fRawDigitIndex[i] = -1;
}

AliHLTEMCALSTURawDigitMaker::~AliHLTEMCALSTURawDigitMaker() {
  if(fDCSConfigSTU) delete fDCSConfigSTU;
  if(fTriggerData) delete fTriggerData;
}

void AliHLTEMCALSTURawDigitMaker::ProcessSTUStream(AliEMCALTriggerSTURawStream *stustream, Int_t detector){

  HLTDebug("Start post processing the raw digit maker");
  Int_t idx;

  AliHLTCaloTriggerRawDigitDataStruct *hltdig(NULL);

  if (stustream && stustream->ReadPayLoad()) {
    fTriggerData->SetL1DataDecoded(1);

    for (int i = 0; i < 2; i++) {
      fTriggerData->SetL1GammaThreshold(i, stustream->GetL1GammaThreshold(i));
      fTriggerData->SetL1JetThreshold(  i, stustream->GetL1JetThreshold(i)  );
    }

    Int_t v0[2] = { static_cast<Int_t>(stustream->GetV0A()),  static_cast<Int_t>(stustream->GetV0C())};

    // Modify DCS config from STU payload content
    for(Int_t i = 0; i < 3; i++){
      for(Int_t j = 0; j < 2; j++){
        fDCSConfigSTU->SetG(i, j, stustream->GetG(i, j));
        fDCSConfigSTU->SetJ(i, j, stustream->GetJ(i, j));
      }
    }
    fDCSConfigSTU->SetRawData(stustream->GetRawData());
    fDCSConfigSTU->SetRegion(stustream->GetRegionEnable());
    fDCSConfigSTU->SetFw(stustream->GetFwVersion());

    fTriggerData->SetL1FrameMask(stustream->GetFrameReceived());
    fTriggerData->SetL1V0(v0);
    Int_t type[15] =
    {
      static_cast<Int_t>(stustream->GetG(0, 0)),
      static_cast<Int_t>(stustream->GetG(1, 0)),
      static_cast<Int_t>(stustream->GetG(2, 0)),
      static_cast<Int_t>(stustream->GetJ(0, 0)),
      static_cast<Int_t>(stustream->GetJ(1, 0)),
      static_cast<Int_t>(stustream->GetJ(2, 0)),
      static_cast<Int_t>(stustream->GetG(0, 1)),
      static_cast<Int_t>(stustream->GetG(1, 1)),
      static_cast<Int_t>(stustream->GetG(2, 1)),
      static_cast<Int_t>(stustream->GetJ(0, 1)),
      static_cast<Int_t>(stustream->GetJ(1, 1)),
      static_cast<Int_t>(stustream->GetJ(2, 1)),
      static_cast<Int_t>(stustream->GetRawData()),
      static_cast<Int_t>(stustream->GetRegionEnable()),
      static_cast<Int_t>(stustream->GetFwVersion())
    };
    fTriggerData->SetL1TriggerType(type);

    fTriggerData->SetL1RawData(stustream->GetRawData());

    Int_t iTRU, jTRU, x, y;

    TVector2 sizeL1gsubr, sizeL1gpatch, sizeL1jsubr, sizeL1jpatch;
    fDCSConfigSTU->GetSegmentation(sizeL1gsubr, sizeL1gpatch, sizeL1jsubr, sizeL1jpatch);

    if (stustream->GetRawData()) {
      HLTDebug("| STU => TRU raw data are there!\n");

      //Int_t nTRU = fkGeometryPtr->GetGeometryPtr()->GetNTotalTRU();
      Int_t nTRU = detector == 0 ? 32 : 14;
      for (Int_t i = 0; i < nTRU; i++) {
        iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(i, detector);

        UInt_t adc[96]; for (Int_t j = 0; j < 96; j++) adc[j] = 0;

        stustream->GetADC(i, adc);

        for (Int_t j = 0; j < 96; j++) {
          if (adc[j] <= 0) continue;
          HLTDebug("| STU => TRU# %2d raw data: ADC# %2d: %d\n", iTRU, j, adc[j]);
          fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromTRU(iTRU, j, idx);
          SetL1TimeSum(GetRawDigit(idx), adc[j]);
        }
      }
    }

    // List of patches in EMCal coordinate system

    for (Int_t i = 0; i < stustream->GetNL0GammaPatch(); i++) {
      stustream->GetL0GammaPatch(i, iTRU, x);

      //if(iTRU >= 32) iTRU -= 32;
      iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(iTRU, detector);

      const Int_t sizePatchL0 = 4;

      HLTDebug("| STU => Found L0 patch id: %2d in TRU# %2d\n", x, iTRU);

      Int_t idFastOR[4];
      for (Int_t j = 0; j < 4; j++) idFastOR[j] = -1;

      if (fkGeometryPtr->GetGeometryPtr()->GetFastORIndexFromL0Index(iTRU, x, idFastOR, sizePatchL0)) {
        idx = idFastOR[1];

        Int_t px, py;
        if (fkGeometryPtr->GetGeometryPtr()->GetPositionInEMCALFromAbsFastORIndex(idx, px, py)){
          HLTDebug("| STU => Add L0 patch at (%2d , %2d)\n", px, py);
          SetTriggerBit(GetRawDigit(idx), kL0, 1);
        }
      }
    }

    Int_t vx, vy, lphi;
    for (int ithr = 0; ithr < 2; ithr++) {
      for (Int_t i = 0; i < stustream->GetNL1GammaPatch(ithr); i++) {
        if (stustream->GetL1GammaPatch(i, ithr, iTRU, x, y)) { // col (0..23), row (0..3)

          if (fkGeometryPtr->GetGeometryPtr()->GetTriggerMappingVersion() == 1) {
            // Run 1
            iTRU = fkGeometryPtr->GetGeometryPtr()->GetTRUIndexFromSTUIndex(iTRU, detector);

            HLTDebug("| STU => Found L1 gamma patch at (%2d , %2d) in TRU# %2d\n", x, y, iTRU);

            vx = 23 - x;
            vy = y + 4 * int(iTRU / 2); // Position in EMCal frame

            if (iTRU % 2) vx += 24; // C side

            vx = vx - int(sizeL1gsubr.X()) * int(sizeL1gpatch.X()) + 1;
            lphi = 64;
            if (vx >= 0 && vy < lphi) {
              if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(vx, vy, idx)) {
                HLTDebug("| STU => Add L1 gamma [%d] patch at (%2d , %2d)\n", ithr, vx, vy);
                SetTriggerBit(GetRawDigit(idx), kL1GammaHigh + ithr, 1);
              }
            }
          } else {
            // Run 2
            fkGeometryPtr->GetGeometryPtr()->GetTRUFromSTU(iTRU, x, y, jTRU, vx, vy, detector);
            fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInTRU(jTRU, vx, vy, idx);
            SetTriggerBit(GetRawDigit(idx), kL1GammaHigh + ithr, 1);
          }
        }
      }

      for (Int_t i = 0; i < stustream->GetNL1JetPatch(ithr); i++) {
        if (stustream->GetL1JetPatch(i, ithr, x, y)) { // col (0,15), row (0,11)
          HLTDebug("| STU => Found L1 jet [%d] patch at (%2d , %2d)\n", ithr, x, y);

          if (fkGeometryPtr->GetGeometryPtr()->GetTriggerMappingVersion() == 1) {
            vx = 11 - y - int(sizeL1jpatch.X()) + 1;
            vy = 15 - x - int(sizeL1jpatch.Y()) + 1;
          }
          else {
            vx = y;
            vy = x;
          }
          vx *= int(sizeL1jsubr.X());
          vy *= int(sizeL1jsubr.Y());

          if (vx >= 0 && vy >= 0) {
            if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPositionInEMCAL(vx, vy, idx)) {
              HLTDebug("| STU => Add L1 jet patch at (%2d , %2d)\n", vx, vy);
              SetTriggerBit(GetRawDigit(idx), kL1JetHigh + ithr, 1);
            }
          }
        }
      }
    }

    if (detector == 1) {
      UInt_t sregion[36] = {0};
      stustream->GetPHOSSubregion(sregion);
      for (int isr=0;isr<36;isr++) {
        if (fkGeometryPtr->GetGeometryPtr()->GetAbsFastORIndexFromPHOSSubregion(isr, idx)) {
          SetL1SubRegion(GetRawDigit(idx), sregion[isr]);
        }
      }
    }
  }

  /*
  for(int idig = 0; idig < fNRawDigits; idig++){
    PrintRawDigit(fRawDigitBuffer[idig]);
  }
  */
}

Int_t AliHLTEMCALSTURawDigitMaker::WriteRawDigitsBuffer(AliHLTCaloTriggerRawDigitDataStruct *bufferptr, AliHLTUInt32_t &availableSize) const {
  Int_t outputsize = 0;
  for(Int_t idig = 0; idig < fNRawDigits; idig++){
	if(availableSize < sizeof(AliHLTCaloTriggerRawDigitDataStruct)){
		HLTWarning("Buffer exceeded after %d digits", idig);
		break;
	}
	if (fRawDigitBuffer[idig].fID < 0 || fRawDigitBuffer[idig].fID >= fgkNRawDigits)
	{
		HLTWarning("Invalid TRU Index in Output %d", fRawDigitBuffer[idig].fID);
		continue;
	}
    *bufferptr = fRawDigitBuffer[idig];
    bufferptr++;
    outputsize += sizeof(AliHLTCaloTriggerRawDigitDataStruct);
    availableSize -= sizeof(AliHLTCaloTriggerRawDigitDataStruct);
  }
  return outputsize;
}

void AliHLTEMCALSTURawDigitMaker::Reset() {
  for (Int_t i = 0; i < fgkNRawDigits; i++) fRawDigitIndex[i] = -1;
  fNRawDigits = 0;
  fTriggerData->Reset();
}

AliHLTCaloTriggerRawDigitDataStruct &AliHLTEMCALSTURawDigitMaker::GetRawDigit(Int_t index){
  if (index < 0){
    HLTWarning("Invalid STU Index %d", index);
    AliHLTCaloTriggerRawDigitDataStruct &dig = fRawDigitBuffer[fgkNRawDigits - 1];
    InitializeRawDigit(dig);
    return dig;
  }
  if(fRawDigitIndex[index] >= 0){
    return fRawDigitBuffer[fRawDigitIndex[index]];
  }

  fRawDigitIndex[index] = fNRawDigits;
  AliHLTCaloTriggerRawDigitDataStruct &dig = fRawDigitBuffer[fNRawDigits];
  InitializeRawDigit(dig);
  SetRawDigitID(dig, index);
  fNRawDigits++;
  return dig;
}
<|endoftext|>


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

#include "itkObjectnessMeasureImageFilter.h"
#include "itkHessianImageFilter.h"
#include "itkHessianToObjectnessMeasureImageFilter.h"
#include "itkProgressAccumulator.h"

namespace itk
{

template< typename TInputImage, typename TOutputImage >
ObjectnessMeasureImageFilter< TInputImage,TOutputImage >
::ObjectnessMeasureImageFilter() :
  m_Alpha( 0.5 ),
  m_Beta( 0.5 ),
  m_Gamma( 5.0 ),
  m_ObjectDimension( 1 ),
  m_BrightObject( true ),
  m_ScaleObjectnessMeasure( true )
{
}

  template< typename TInputImage, typename TOutputImage >
  ObjectnessMeasureImageFilter< TInputImage,TOutputImage >
  ::~ObjectnessMeasureImageFilter()
  {
}

    template< typename TInputImage, typename TOutputImage >
    void
    ObjectnessMeasureImageFilter< TInputImage,TOutputImage >
    ::EnlargeOutputRequestedRegion(DataObject *output) ITK_OVERRIDE
    {
output->SetRequestedRegionToLargestPossibleRegion();
}

      template< typename TInputImage, typename TOutputImage >
      void
      ObjectnessMeasureImageFilter< TInputImage,TOutputImage >
      ::GenerateData() ITK_OVERRIDE
      {
// Create a process accumulator for tracking the progress of this minipipeline
ProgressAccumulator::Pointer progress = ProgressAccumulator::New();
progress->SetMiniPipelineFilter( this );

typename InputImageType::Pointer localInput = InputImageType::New();
localInput->Graft( this->GetInput() );

  typename InputImageType::Pointer localInput = InputImageType::New();
  localInput->Graft( this->GetInput() );

  typedef HessianImageFilter<InputImageType>          HessianFilterType;
  typedef typename HessianFilterType::OutputImageType HessianImageType;

  typename HessianFilterType::Pointer hessianFilter = HessianFilterType::New();

  hessianFilter->SetInput( localInput );

typedef HessianToObjectnessMeasureImageFilter< HessianImageType, OutputImageType > ObjectnessFilterType;

typename ObjectnessFilterType::Pointer objectnessFilter = ObjectnessFilterType::New();

objectnessFilter->SetInput( hessianFilter->GetOutput() );

objectnessFilter->SetAlpha( m_Alpha );
objectnessFilter->SetBeta( m_Beta );
objectnessFilter->SetGamma( m_Gamma );
objectnessFilter->SetScaleObjectnessMeasure( m_ScaleObjectnessMeasure );
objectnessFilter->SetObjectDimension( m_ObjectDimension );
objectnessFilter->SetBrightObject( m_BrightObject);

progress->RegisterInternalFilter( hessianFilter, 0.5f );
progress->RegisterInternalFilter( objectnessFilter, 0.5f );

objectnessFilter->GraftOutput( this->GetOutput() );
objectnessFilter->Update();
this->GraftOutput(objectnessFilter->GetOutput());
}

        template< typename TInputImage, typename TOutputImage >
        void
        ObjectnessMeasureImageFilter< TInputImage,TOutputImage >
        ::PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE
        {
Superclass::PrintSelf(os, indent);

os << indent << "Alpha: " << m_Alpha << std::endl;
os << indent << "Beta: " << m_Beta << std::endl;
os << indent << "Gamma: " << m_Gamma << std::endl;
os << indent << "ScaleObjectnessMeasure: " << m_ScaleObjectnessMeasure << std::endl;
os << indent << "ObjectDimension: " << m_ObjectDimension << std::endl;
os << indent << "BrightObject: " << m_BrightObject << std::endl;
}

                                                      }
#endif // itkObjectnessMeasureImageFilter_hxx
<commit_msg>fix indenting style in Objectness filter.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#ifndef itkObjectnessMeasureImageFilter_hxx
#define itkObjectnessMeasureImageFilter_hxx

#include "itkObjectnessMeasureImageFilter.h"
#include "itkHessianImageFilter.h"
#include "itkHessianToObjectnessMeasureImageFilter.h"
#include "itkProgressAccumulator.h"

namespace itk
{

template< typename TInputImage, typename TOutputImage >
ObjectnessMeasureImageFilter< TInputImage,TOutputImage >
::ObjectnessMeasureImageFilter() :
  m_Alpha( 0.5 ),
  m_Beta( 0.5 ),
  m_Gamma( 5.0 ),
  m_ObjectDimension( 1 ),
  m_BrightObject( true ),
  m_ScaleObjectnessMeasure( true )
{
}

template< typename TInputImage, typename TOutputImage >
ObjectnessMeasureImageFilter< TInputImage,TOutputImage >
::~ObjectnessMeasureImageFilter()
{
}

template< typename TInputImage, typename TOutputImage >
void
ObjectnessMeasureImageFilter< TInputImage,TOutputImage >
::EnlargeOutputRequestedRegion(DataObject *output) ITK_OVERRIDE
{
  output->SetRequestedRegionToLargestPossibleRegion();
}

template< typename TInputImage, typename TOutputImage >
void
ObjectnessMeasureImageFilter< TInputImage,TOutputImage >
::GenerateData()
{
// Create a process accumulator for tracking the progress of this minipipeline
  ProgressAccumulator::Pointer progress = ProgressAccumulator::New();
  progress->SetMiniPipelineFilter( this );

  typename InputImageType::Pointer localInput = InputImageType::New();
  localInput->Graft( this->GetInput() );

  typedef HessianImageFilter<InputImageType>          HessianFilterType;
  typedef typename HessianFilterType::OutputImageType HessianImageType;

  typename HessianFilterType::Pointer hessianFilter = HessianFilterType::New();

  hessianFilter->SetInput( localInput );

  typedef HessianToObjectnessMeasureImageFilter< HessianImageType, OutputImageType > ObjectnessFilterType;

  typename ObjectnessFilterType::Pointer objectnessFilter = ObjectnessFilterType::New();

  objectnessFilter->SetInput( hessianFilter->GetOutput() );

  objectnessFilter->SetAlpha( m_Alpha );
  objectnessFilter->SetBeta( m_Beta );
  objectnessFilter->SetGamma( m_Gamma );
  objectnessFilter->SetScaleObjectnessMeasure( m_ScaleObjectnessMeasure );
  objectnessFilter->SetObjectDimension( m_ObjectDimension );
  objectnessFilter->SetBrightObject( m_BrightObject);

  progress->RegisterInternalFilter( hessianFilter, 0.5f );
  progress->RegisterInternalFilter( objectnessFilter, 0.5f );

  objectnessFilter->GraftOutput( this->GetOutput() );
  objectnessFilter->Update();
  this->GraftOutput(objectnessFilter->GetOutput());
}

template< typename TInputImage, typename TOutputImage >
void
ObjectnessMeasureImageFilter< TInputImage,TOutputImage >
::PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Alpha: " << m_Alpha << std::endl;
  os << indent << "Beta: " << m_Beta << std::endl;
  os << indent << "Gamma: " << m_Gamma << std::endl;
  os << indent << "ScaleObjectnessMeasure: " << m_ScaleObjectnessMeasure << std::endl;
  os << indent << "ObjectDimension: " << m_ObjectDimension << std::endl;
  os << indent << "BrightObject: " << m_BrightObject << std::endl;
}

}
#endif // itkObjectnessMeasureImageFilter_hxx
<|endoftext|>


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

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

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

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

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

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

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

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

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

=========================================================================*/
#include "vtkOpenGLVolumeTextureMapper2D.h"
#include "vtkMatrix4x4.h"
#include "vtkVolume.h"
#include "vtkTimerLog.h"
#ifndef VTK_IMPLEMENT_MESA_CXX
#include <GL/gl.h>
#endif
#include "vtkObjectFactory.h"

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

vtkOpenGLVolumeTextureMapper2D::vtkOpenGLVolumeTextureMapper2D()
{
}

vtkOpenGLVolumeTextureMapper2D::~vtkOpenGLVolumeTextureMapper2D()
{
}

void vtkOpenGLVolumeTextureMapper2D::Render(vtkRenderer *ren, vtkVolume *vol)
{
  vtkMatrix4x4       *matrix = vtkMatrix4x4::New();
  vtkTimerLog        *timer;
  vtkPlaneCollection *clipPlanes;
  vtkPlane           *plane;
  int                i, numClipPlanes;
  double             planeEquation[4];

  timer = vtkTimerLog::New();
  timer->StartTimer();

  // Let the superclass take care of some initialization
  this->vtkVolumeTextureMapper2D::InitializeRender( ren, vol );

  // build transformation
  vol->GetMatrix(matrix);
  matrix->Transpose();

  // insert model transformation
  glMatrixMode( GL_MODELVIEW );
  glPushMatrix();
  glMultMatrixd(matrix->Element[0]);

  // Turn lighting off - the polygon textures already have illumination
  glDisable( GL_LIGHTING );

  // Turn texturing on so that we can draw the textured polygons
  glEnable( GL_TEXTURE_2D );

  // Turn blending on so that the translucent geometry of the polygons can
  // be blended with other geoemtry (non-intersecting only)
  glEnable( GL_BLEND );

#ifdef GL_VERSION_1_1
  GLuint tempIndex;
  glGenTextures(1, &tempIndex);
  glBindTexture(GL_TEXTURE_2D, tempIndex);
#endif

  glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

  glColor3f( 1.0, 1.0, 1.0 );

  // Use the OpenGL clip planes
  clipPlanes = this->ClippingPlanes;
  if ( clipPlanes )
    {
    numClipPlanes = clipPlanes->GetNumberOfItems();
    if (numClipPlanes > 6)
      {
      vtkErrorMacro(<< "OpenGL guarantees only 6 additional clipping planes");
      }

    for (i = 0; i < numClipPlanes; i++)
      {
      glEnable((GLenum)(GL_CLIP_PLANE0+i));

      plane = (vtkPlane *)clipPlanes->GetItemAsObject(i);

      planeEquation[0] = plane->GetNormal()[0];
      planeEquation[1] = plane->GetNormal()[1];
      planeEquation[2] = plane->GetNormal()[2];
      planeEquation[3] = -(planeEquation[0]*plane->GetOrigin()[0]+
			   planeEquation[1]*plane->GetOrigin()[1]+
			   planeEquation[2]*plane->GetOrigin()[2]);
      glClipPlane((GLenum)(GL_CLIP_PLANE0+i),planeEquation);
      }
    }

  this->GenerateTexturesAndRenderQuads();

  // pop transformation matrix
  glMatrixMode( GL_MODELVIEW );
  glPopMatrix();

  matrix->Delete();

  glDisable( GL_BLEND );
  glDisable( GL_TEXTURE_2D );

#ifdef GL_VERSION_1_1
  glFlush();
  glDeleteTextures(1, &tempIndex);
#endif

  // Turn lighting back on
  glEnable( GL_LIGHTING );

  if ( clipPlanes )
    {
    for (i = 0; i < numClipPlanes; i++)
      {
      glDisable((GLenum)(GL_CLIP_PLANE0+i));
      }
    }

  timer->StopTimer();

  this->TimeToDraw = (float)timer->GetElapsedTime();

  // If the timer is not accurate enough, set it to a small
  // time so that it is not zero
  if ( this->TimeToDraw == 0.0 )
    {
    this->TimeToDraw = 0.0001;
    }
  timer->Delete();
}

void vtkOpenGLVolumeTextureMapper2D::RenderQuads( int numQuads,
                                                  float *v,
                                                  float *t,
                                                  unsigned char *texture,
                                                  int size[2])
{
#ifdef GL_VERSION_1_1
  glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, size[0], size[1],
		0, GL_RGBA, GL_UNSIGNED_BYTE, texture );
#else
  glTexImage2D( GL_TEXTURE_2D, 0, 4, size[0], size[1],
		0, GL_RGBA, GL_UNSIGNED_BYTE, texture );
#endif

  glBegin( GL_QUADS );

  float *tptr = t, *vptr = v;

  for ( int i = 0; i < numQuads*4; i++ )
    {
    glTexCoord2fv( tptr );
    glVertex3fv(   vptr );

    tptr += 2;
    vptr += 3;
    }

  glEnd();
}

// Print the vtkOpenGLVolumeTextureMapper2D
void vtkOpenGLVolumeTextureMapper2D::PrintSelf(ostream& os, vtkIndent indent)
{
  this->vtkVolumeTextureMapper::PrintSelf(os,indent);
}

<commit_msg>ERR: PrintSelf skipped a level when printing superclass<commit_after>/*=========================================================================

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

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

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

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

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

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

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

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

=========================================================================*/
#include "vtkOpenGLVolumeTextureMapper2D.h"
#include "vtkMatrix4x4.h"
#include "vtkVolume.h"
#include "vtkTimerLog.h"
#ifndef VTK_IMPLEMENT_MESA_CXX
#include <GL/gl.h>
#endif
#include "vtkObjectFactory.h"

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

vtkOpenGLVolumeTextureMapper2D::vtkOpenGLVolumeTextureMapper2D()
{
}

vtkOpenGLVolumeTextureMapper2D::~vtkOpenGLVolumeTextureMapper2D()
{
}

void vtkOpenGLVolumeTextureMapper2D::Render(vtkRenderer *ren, vtkVolume *vol)
{
  vtkMatrix4x4       *matrix = vtkMatrix4x4::New();
  vtkTimerLog        *timer;
  vtkPlaneCollection *clipPlanes;
  vtkPlane           *plane;
  int                i, numClipPlanes;
  double             planeEquation[4];

  timer = vtkTimerLog::New();
  timer->StartTimer();

  // Let the superclass take care of some initialization
  this->vtkVolumeTextureMapper2D::InitializeRender( ren, vol );

  // build transformation
  vol->GetMatrix(matrix);
  matrix->Transpose();

  // insert model transformation
  glMatrixMode( GL_MODELVIEW );
  glPushMatrix();
  glMultMatrixd(matrix->Element[0]);

  // Turn lighting off - the polygon textures already have illumination
  glDisable( GL_LIGHTING );

  // Turn texturing on so that we can draw the textured polygons
  glEnable( GL_TEXTURE_2D );

  // Turn blending on so that the translucent geometry of the polygons can
  // be blended with other geoemtry (non-intersecting only)
  glEnable( GL_BLEND );

#ifdef GL_VERSION_1_1
  GLuint tempIndex;
  glGenTextures(1, &tempIndex);
  glBindTexture(GL_TEXTURE_2D, tempIndex);
#endif

  glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

  glColor3f( 1.0, 1.0, 1.0 );

  // Use the OpenGL clip planes
  clipPlanes = this->ClippingPlanes;
  if ( clipPlanes )
    {
    numClipPlanes = clipPlanes->GetNumberOfItems();
    if (numClipPlanes > 6)
      {
      vtkErrorMacro(<< "OpenGL guarantees only 6 additional clipping planes");
      }

    for (i = 0; i < numClipPlanes; i++)
      {
      glEnable((GLenum)(GL_CLIP_PLANE0+i));

      plane = (vtkPlane *)clipPlanes->GetItemAsObject(i);

      planeEquation[0] = plane->GetNormal()[0];
      planeEquation[1] = plane->GetNormal()[1];
      planeEquation[2] = plane->GetNormal()[2];
      planeEquation[3] = -(planeEquation[0]*plane->GetOrigin()[0]+
			   planeEquation[1]*plane->GetOrigin()[1]+
			   planeEquation[2]*plane->GetOrigin()[2]);
      glClipPlane((GLenum)(GL_CLIP_PLANE0+i),planeEquation);
      }
    }

  this->GenerateTexturesAndRenderQuads();

  // pop transformation matrix
  glMatrixMode( GL_MODELVIEW );
  glPopMatrix();

  matrix->Delete();

  glDisable( GL_BLEND );
  glDisable( GL_TEXTURE_2D );

#ifdef GL_VERSION_1_1
  glFlush();
  glDeleteTextures(1, &tempIndex);
#endif

  // Turn lighting back on
  glEnable( GL_LIGHTING );

  if ( clipPlanes )
    {
    for (i = 0; i < numClipPlanes; i++)
      {
      glDisable((GLenum)(GL_CLIP_PLANE0+i));
      }
    }

  timer->StopTimer();

  this->TimeToDraw = (float)timer->GetElapsedTime();

  // If the timer is not accurate enough, set it to a small
  // time so that it is not zero
  if ( this->TimeToDraw == 0.0 )
    {
    this->TimeToDraw = 0.0001;
    }
  timer->Delete();
}

void vtkOpenGLVolumeTextureMapper2D::RenderQuads( int numQuads,
                                                  float *v,
                                                  float *t,
                                                  unsigned char *texture,
                                                  int size[2])
{
#ifdef GL_VERSION_1_1
  glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, size[0], size[1],
		0, GL_RGBA, GL_UNSIGNED_BYTE, texture );
#else
  glTexImage2D( GL_TEXTURE_2D, 0, 4, size[0], size[1],
		0, GL_RGBA, GL_UNSIGNED_BYTE, texture );
#endif

  glBegin( GL_QUADS );

  float *tptr = t, *vptr = v;

  for ( int i = 0; i < numQuads*4; i++ )
    {
    glTexCoord2fv( tptr );
    glVertex3fv(   vptr );

    tptr += 2;
    vptr += 3;
    }

  glEnd();
}

// Print the vtkOpenGLVolumeTextureMapper2D
void vtkOpenGLVolumeTextureMapper2D::PrintSelf(ostream& os, vtkIndent indent)
{
  this->vtkVolumeTextureMapper2D::PrintSelf(os,indent);
}

<|endoftext|>