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

  Program:   Visualization Library
  Module:    STLRead.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include <ctype.h>
#include "STLRead.hh"
#include "ByteSwap.hh"

#define ASCII 0
#define BINARY 1

void vlSTLReader::Execute()
{
  FILE *fp;
  vlFloatPoints *newPts;
  vlCellArray *newPolys;
//
// Initialize
//
  this->Initialize();

  if ((fp = fopen(this->Filename, "r")) == NULL)
    {
    vlErrorMacro(<< "File " << this->Filename << " not found");
    return;
    }

  newPts = new vlFloatPoints(5000,10000);
  newPolys = new vlCellArray(10000,20000);

//
// Depending upon file type, read differently
//
  if ( this->GetSTLFileType(fp) == ASCII )
    {
    if ( this->ReadASCIISTL(fp,newPts,newPolys) ) return;
    }
  else
    {
    if ( this->ReadBinarySTL(fp,newPts,newPolys) ) return;
    }

  vlDebugMacro(<< "Read " << newPts->GetNumberOfPoints() << " points");
  vlDebugMacro(<< "Read " << newPolys->GetNumberOfCells() << " triangles");
//
// Since we sized the dynamic arrays arbitrarily to begin with
// need to resize them to fit data
//
  newPts->Squeeze();
  newPolys->Squeeze();
//
// Update ourselves
//
  this->SetPoints(newPts);
  this->SetPolys(newPolys);
}

int vlSTLReader::ReadBinarySTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys)
{
  int i, numTris, pts[3];
  unsigned long   ulint;
  unsigned short  ibuff2;
  char    header[81];
  vlByteSwap swap;
  typedef struct  {float  n[3], v1[3], v2[3], v3[3];} facet_t;
  facet_t facet;

  vlDebugMacro(<< " Reading BINARY STL file");
//
//  File is read to obtain raw information as well as bounding box
//
  fread (header, 1, 80, fp);
  fread (&ulint, 1, 4, fp);
  swap.Swap4 (&ulint);
//
// Many .stl files contain bogus count.  Hence we will ignore and read
//   until end of file.
//
  if ( (numTris = (int) ulint) <= 0 )
    {
    vlDebugMacro(<< "Bad binary count (" << numTris << ")");
    }

  for ( i=0; fread(&facet,48,1,fp) > 0; i++ )
    {
    fread(&ibuff2,2,1,fp); /* read extra junk */

    swap.Swap4 (facet.n);
    swap.Swap4 (facet.n+1);
    swap.Swap4 (facet.n+2);

    swap.Swap4 (facet.v1);
    swap.Swap4 (facet.v1+1);
    swap.Swap4 (facet.v1+2);
    pts[0] = newPts->InsertNextPoint(facet.v1);

    swap.Swap4 (facet.v2);
    swap.Swap4 (facet.v2+1);
    swap.Swap4 (facet.v2+2);
    pts[1] = newPts->InsertNextPoint(facet.v2);

    swap.Swap4 (facet.v3);
    swap.Swap4 (facet.v3+1);
    swap.Swap4 (facet.v3+2);
    pts[2] = newPts->InsertNextPoint(facet.v3);

    newPolys->InsertNextCell(3,pts);

    if ( (i % 5000) == 0 && i != 0 )
      vlDebugMacro(<< "triangle# " << i);
    }

  return 0;
}

int vlSTLReader::ReadASCIISTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys)
{
  char line[256];
  float x[3];
  int pts[3];

  vlDebugMacro(<< " Reading ASCII STL file");
//
//  Ingest header and junk to get to first vertex
//
  fgets (line, 255, fp);
/*
 *  Go into loop, reading  facet normal and vertices
 */
  while (fscanf(fp,"%*s %*s %f %f %f\n", x, x+1, x+2)!=EOF)
    {
    fgets (line, 255, fp);
    fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
    pts[0] = newPts->InsertNextPoint(x);
    fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
    pts[1] = newPts->InsertNextPoint(x);
    fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
    pts[2] = newPts->InsertNextPoint(x);
    fgets (line, 255, fp); /* end loop */
    fgets (line, 255, fp); /* end facet */

    newPolys->InsertNextCell(3,pts);

    if ( (newPolys->GetNumberOfCells() % 5000) == 0 )
      vlDebugMacro(<< "triangle# " << newPolys->GetNumberOfCells());
    }

  return 0;
}

int vlSTLReader::GetSTLFileType(FILE *fp)
{
  char header[256];
  int type, i;
//
//  Read a little from the file to figure what type it is.
//
  fgets (header, 255, fp); /* first line is always ascii */
  fgets (header, 18, fp);
  for (i=0, type=ASCII; i<17 && type == ASCII; i++) // don't test \0
    if ( ! isprint(header[i]) )
      type = BINARY;
//
// Reset file for reading
//
  rewind (fp);
  return type;
}

void vlSTLReader::PrintSelf(ostream& os, vlIndent indent)
{
  if (this->ShouldIPrint(vlSTLReader::GetClassName()))
    {
    vlPolySource::PrintSelf(os,indent);

    os << indent << "Filename: " << this->Filename << "\n";
    }
}
<commit_msg>now closes the file<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    STLRead.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include <ctype.h>
#include "STLRead.hh"
#include "ByteSwap.hh"

#define ASCII 0
#define BINARY 1

void vlSTLReader::Execute()
{
  FILE *fp;
  vlFloatPoints *newPts;
  vlCellArray *newPolys;
//
// Initialize
//
  this->Initialize();

  if ((fp = fopen(this->Filename, "r")) == NULL)
    {
    vlErrorMacro(<< "File " << this->Filename << " not found");
    return;
    }

  newPts = new vlFloatPoints(5000,10000);
  newPolys = new vlCellArray(10000,20000);

//
// Depending upon file type, read differently
//
  if ( this->GetSTLFileType(fp) == ASCII )
    {
    if ( this->ReadASCIISTL(fp,newPts,newPolys) ) return;
    }
  else
    {
    if ( this->ReadBinarySTL(fp,newPts,newPolys) ) return;
    }

  vlDebugMacro(<< "Read " << newPts->GetNumberOfPoints() << " points");
  vlDebugMacro(<< "Read " << newPolys->GetNumberOfCells() << " triangles");

  fclose(fp);
//
// Since we sized the dynamic arrays arbitrarily to begin with
// need to resize them to fit data
//
  newPts->Squeeze();
  newPolys->Squeeze();
//
// Update ourselves
//
  this->SetPoints(newPts);
  this->SetPolys(newPolys);
}

int vlSTLReader::ReadBinarySTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys)
{
  int i, numTris, pts[3];
  unsigned long   ulint;
  unsigned short  ibuff2;
  char    header[81];
  vlByteSwap swap;
  typedef struct  {float  n[3], v1[3], v2[3], v3[3];} facet_t;
  facet_t facet;

  vlDebugMacro(<< " Reading BINARY STL file");
//
//  File is read to obtain raw information as well as bounding box
//
  fread (header, 1, 80, fp);
  fread (&ulint, 1, 4, fp);
  swap.Swap4 (&ulint);
//
// Many .stl files contain bogus count.  Hence we will ignore and read
//   until end of file.
//
  if ( (numTris = (int) ulint) <= 0 )
    {
    vlDebugMacro(<< "Bad binary count (" << numTris << ")");
    }

  for ( i=0; fread(&facet,48,1,fp) > 0; i++ )
    {
    fread(&ibuff2,2,1,fp); /* read extra junk */

    swap.Swap4 (facet.n);
    swap.Swap4 (facet.n+1);
    swap.Swap4 (facet.n+2);

    swap.Swap4 (facet.v1);
    swap.Swap4 (facet.v1+1);
    swap.Swap4 (facet.v1+2);
    pts[0] = newPts->InsertNextPoint(facet.v1);

    swap.Swap4 (facet.v2);
    swap.Swap4 (facet.v2+1);
    swap.Swap4 (facet.v2+2);
    pts[1] = newPts->InsertNextPoint(facet.v2);

    swap.Swap4 (facet.v3);
    swap.Swap4 (facet.v3+1);
    swap.Swap4 (facet.v3+2);
    pts[2] = newPts->InsertNextPoint(facet.v3);

    newPolys->InsertNextCell(3,pts);

    if ( (i % 5000) == 0 && i != 0 )
      vlDebugMacro(<< "triangle# " << i);
    }

  return 0;
}

int vlSTLReader::ReadASCIISTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys)
{
  char line[256];
  float x[3];
  int pts[3];

  vlDebugMacro(<< " Reading ASCII STL file");
//
//  Ingest header and junk to get to first vertex
//
  fgets (line, 255, fp);
/*
 *  Go into loop, reading  facet normal and vertices
 */
  while (fscanf(fp,"%*s %*s %f %f %f\n", x, x+1, x+2)!=EOF)
    {
    fgets (line, 255, fp);
    fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
    pts[0] = newPts->InsertNextPoint(x);
    fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
    pts[1] = newPts->InsertNextPoint(x);
    fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
    pts[2] = newPts->InsertNextPoint(x);
    fgets (line, 255, fp); /* end loop */
    fgets (line, 255, fp); /* end facet */

    newPolys->InsertNextCell(3,pts);

    if ( (newPolys->GetNumberOfCells() % 5000) == 0 )
      vlDebugMacro(<< "triangle# " << newPolys->GetNumberOfCells());
    }

  return 0;
}

int vlSTLReader::GetSTLFileType(FILE *fp)
{
  char header[256];
  int type, i;
//
//  Read a little from the file to figure what type it is.
//
  fgets (header, 255, fp); /* first line is always ascii */
  fgets (header, 18, fp);
  for (i=0, type=ASCII; i<17 && type == ASCII; i++) // don't test \0
    if ( ! isprint(header[i]) )
      type = BINARY;
//
// Reset file for reading
//
  rewind (fp);
  return type;
}

void vlSTLReader::PrintSelf(ostream& os, vlIndent indent)
{
  if (this->ShouldIPrint(vlSTLReader::GetClassName()))
    {
    vlPolySource::PrintSelf(os,indent);

    os << indent << "Filename: " << this->Filename << "\n";
    }
}
<|endoftext|>


<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.31
Copyright (C) 2018  GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "EnsemblePreprocessor.h"
#include "System.h"

#include "CalculateEnergy.h"
#include "EwaldCached.h"
#include "Ewald.h"
#include "NoEwald.h"
#include "EnergyTypes.h"
#include "Setup.h"               //For source of setup data.
#include "ConfigSetup.h"         //For types directly read from config. file
#include "StaticVals.h"
#include "Molecules.h"           //For indexing molecules.
#include "MoveConst.h"           //For array of move objects.
#include "MoveBase.h"            //For move bases....
#include "MoleculeTransfer.h"
#include "IntraSwap.h"
#include "MultiParticle.h"
#include "Regrowth.h"

System::System(StaticVals& statics) :
  statV(statics),
#ifdef VARIABLE_VOLUME
  boxDimRef(*BoxDim(statics.isOrthogonal)),
#else
  boxDimRef(*statics.GetBoxDim()),
#endif
#ifdef VARIABLE_PARTICLE_NUMBER
  molLookupRef(molLookup),
#else
  molLookupRef(statics.molLookup),
#endif
  prng(molLookupRef),
  coordinates(boxDimRef, com, molLookupRef, prng, statics.mol),
  com(boxDimRef, coordinates, molLookupRef, statics.mol),
  moveSettings(boxDimRef), cellList(statics.mol, boxDimRef),
  calcEnergy(statics, *this)
{
  calcEwald = NULL;
}

System::~System()
{
#ifdef VARIABLE_VOLUME
  if (boxDimensions != NULL)
    delete boxDimensions;
#endif
  if (calcEwald != NULL)
    delete calcEwald;
  delete moves[mv::DISPLACE];
  delete moves[mv::ROTATE];
  delete moves[mv::INTRA_SWAP];
  delete moves[mv::REGROWTH];
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
  delete moves[mv::VOL_TRANSFER];
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
  delete moves[mv::MOL_TRANSFER];
#endif
}

void System::Init(Setup const& set)
{
  prng.Init(set.prng.prngMaker.prng);
#ifdef VARIABLE_VOLUME
  boxDimensions->Init(set.config.in.restart,
                      set.config.sys.volume, set.pdb.cryst,
                      statV.forcefield.rCut,
                      statV.forcefield.rCutSq);
#endif
#ifdef VARIABLE_PARTICLE_NUMBER
  molLookup.Init(statV.mol, set.pdb.atoms);
#endif
  moveSettings.Init(statV, set.pdb.remarks);
  //Note... the following calls use box iterators, so must come after
  //the molecule lookup initialization, in case we're in a constant
  //particle/molecule ensemble, e.g. NVT
  coordinates.InitFromPDB(set.pdb.atoms);
  com.CalcCOM();
  // Allocate space for atom forces
  atomForceRef.Init(set.pdb.atoms.beta.size());
  molForceRef.Init(com.Count());
  // Allocate space for reciprocate force
  atomForceRecRef.Init(set.pdb.atoms.beta.size());
  molForceRecRef.Init(com.Count());
  cellList.SetCutoff(statV.forcefield.rCut);
  cellList.GridAll(boxDimRef, coordinates, molLookupRef);

  //check if we have to use cached version of ewlad or not.
  bool ewald = set.config.sys.elect.ewald;
  bool cached = set.config.sys.elect.cache;

#ifdef GOMC_CUDA
  if(ewald)
    calcEwald = new Ewald(statV, *this);
  else
    calcEwald = new NoEwald(statV, *this);
#else
  if (ewald && cached)
    calcEwald = new EwaldCached(statV, *this);
  else if (ewald && !cached)
    calcEwald = new Ewald(statV, *this);
  else
    calcEwald = new NoEwald(statV, *this);
#endif

  calcEnergy.Init(*this);
  calcEwald->Init();
  potential = calcEnergy.SystemTotal();
  InitMoves();
  for(uint m = 0; m < mv::MOVE_KINDS_TOTAL; m++)
    moveTime[m] = 0.0;
}

void System::InitMoves()
{
  moves[mv::DISPLACE] = new Translate(*this, statV);
  moves[mv::MULTIPARTICLE] = new MultiParticle(*this, statV);
  moves[mv::ROTATE] = new Rotate(*this, statV);
  moves[mv::INTRA_SWAP] = new IntraSwap(*this, statV);
  moves[mv::REGROWTH] = new Regrowth(*this, statV);
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
  moves[mv::VOL_TRANSFER] = new VolumeTransfer(*this, statV);
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
  moves[mv::MOL_TRANSFER] = new MoleculeTransfer(*this, statV);
#endif
}

void System::RecalculateTrajectory(Setup &set, uint frameNum)
{
  set.pdb.Init(set.config.in.restart, set.config.in.files.pdb.name, frameNum);
  statV.InitOver(set, *this);
#ifdef VARIABLE_PARTICLE_NUMBER
  molLookup.Init(statV.mol, set.pdb.atoms);
#endif
  coordinates.InitFromPDB(set.pdb.atoms);
  com.CalcCOM();
  cellList.GridAll(boxDimRef, coordinates, molLookupRef);
  calcEnergy.Init(*this);
  calcEwald->Init();
  potential = calcEnergy.SystemTotal();
}

void System::ChooseAndRunMove(const uint step)
{
  double draw = 0;
  uint majKind = 0;
  PickMove(majKind, draw);
  time.SetStart();
  RunMove(majKind, draw, step);
  time.SetStop();
  moveTime[majKind] += time.GetTimDiff();
}
void System::PickMove(uint & kind, double & draw)
{
  prng.PickArbDist(kind, draw, statV.movePerc, statV.totalPerc,
                   mv::MOVE_KINDS_TOTAL);
}

void System::RunMove(uint majKind, double draw, const uint step)
{
  //return now if move targets molecule and there's none in that box.
  uint rejectState = SetParams(majKind, draw);
  //If single atom, redo move as displacement
  if (rejectState == mv::fail_state::ROTATE_ON_SINGLE_ATOM) {
    majKind = mv::DISPLACE;
    Translate * disp = static_cast<Translate *>(moves[mv::DISPLACE]);
    Rotate * rot = static_cast<Rotate *>(moves[mv::ROTATE]);
    rejectState = disp->ReplaceRot(*rot);
  }
  if (rejectState == mv::fail_state::NO_FAIL)
    rejectState = Transform(majKind);
  if (rejectState == mv::fail_state::NO_FAIL)
    CalcEn(majKind);
  Accept(majKind, rejectState, step);
}

uint System::SetParams(const uint kind, const double draw)
{
  return moves[kind]->Prep(draw, statV.movePerc[kind]);
}

uint System::Transform(const uint kind)
{
  return moves[kind]->Transform();
}

void System::CalcEn(const uint kind)
{
  moves[kind]->CalcEn();
}

void System::Accept(const uint kind, const uint rejectState, const uint step)
{
  moves[kind]->Accept(rejectState, step);
}

void System::PrintTime()
{
  //std::cout << "MC moves Execution time:\n";
  printf("%-30s %10.4f sec.\n", "Displacement:", moveTime[mv::DISPLACE]);
  printf("%-30s %10.4f sec.\n", "Rotation:", moveTime[mv::ROTATE]);
  printf("%-30s %10.4f sec.\n", "Intra-Swap:", moveTime[mv::INTRA_SWAP]);
  printf("%-30s %10.4f sec.\n", "Regrowth:", moveTime[mv::REGROWTH]);

#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
  printf("%-30s %10.4f sec.\n", "Molecule-Transfer:",
         moveTime[mv::MOL_TRANSFER]);
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
  printf("%-30s %10.4f sec.\n", "Volume-Transfer:", moveTime[mv::VOL_TRANSFER]);
#endif
}
<commit_msg>Added MultiParticle time print at the end of the simulation<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.31
Copyright (C) 2018  GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "EnsemblePreprocessor.h"
#include "System.h"

#include "CalculateEnergy.h"
#include "EwaldCached.h"
#include "Ewald.h"
#include "NoEwald.h"
#include "EnergyTypes.h"
#include "Setup.h"               //For source of setup data.
#include "ConfigSetup.h"         //For types directly read from config. file
#include "StaticVals.h"
#include "Molecules.h"           //For indexing molecules.
#include "MoveConst.h"           //For array of move objects.
#include "MoveBase.h"            //For move bases....
#include "MoleculeTransfer.h"
#include "IntraSwap.h"
#include "MultiParticle.h"
#include "Regrowth.h"

System::System(StaticVals& statics) :
  statV(statics),
#ifdef VARIABLE_VOLUME
  boxDimRef(*BoxDim(statics.isOrthogonal)),
#else
  boxDimRef(*statics.GetBoxDim()),
#endif
#ifdef VARIABLE_PARTICLE_NUMBER
  molLookupRef(molLookup),
#else
  molLookupRef(statics.molLookup),
#endif
  prng(molLookupRef),
  coordinates(boxDimRef, com, molLookupRef, prng, statics.mol),
  com(boxDimRef, coordinates, molLookupRef, statics.mol),
  moveSettings(boxDimRef), cellList(statics.mol, boxDimRef),
  calcEnergy(statics, *this)
{
  calcEwald = NULL;
}

System::~System()
{
#ifdef VARIABLE_VOLUME
  if (boxDimensions != NULL)
    delete boxDimensions;
#endif
  if (calcEwald != NULL)
    delete calcEwald;
  delete moves[mv::DISPLACE];
  delete moves[mv::ROTATE];
  delete moves[mv::INTRA_SWAP];
  delete moves[mv::REGROWTH];
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
  delete moves[mv::VOL_TRANSFER];
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
  delete moves[mv::MOL_TRANSFER];
#endif
}

void System::Init(Setup const& set)
{
  prng.Init(set.prng.prngMaker.prng);
#ifdef VARIABLE_VOLUME
  boxDimensions->Init(set.config.in.restart,
                      set.config.sys.volume, set.pdb.cryst,
                      statV.forcefield.rCut,
                      statV.forcefield.rCutSq);
#endif
#ifdef VARIABLE_PARTICLE_NUMBER
  molLookup.Init(statV.mol, set.pdb.atoms);
#endif
  moveSettings.Init(statV, set.pdb.remarks);
  //Note... the following calls use box iterators, so must come after
  //the molecule lookup initialization, in case we're in a constant
  //particle/molecule ensemble, e.g. NVT
  coordinates.InitFromPDB(set.pdb.atoms);
  com.CalcCOM();
  // Allocate space for atom forces
  atomForceRef.Init(set.pdb.atoms.beta.size());
  molForceRef.Init(com.Count());
  // Allocate space for reciprocate force
  atomForceRecRef.Init(set.pdb.atoms.beta.size());
  molForceRecRef.Init(com.Count());
  cellList.SetCutoff(statV.forcefield.rCut);
  cellList.GridAll(boxDimRef, coordinates, molLookupRef);

  //check if we have to use cached version of ewlad or not.
  bool ewald = set.config.sys.elect.ewald;
  bool cached = set.config.sys.elect.cache;

#ifdef GOMC_CUDA
  if(ewald)
    calcEwald = new Ewald(statV, *this);
  else
    calcEwald = new NoEwald(statV, *this);
#else
  if (ewald && cached)
    calcEwald = new EwaldCached(statV, *this);
  else if (ewald && !cached)
    calcEwald = new Ewald(statV, *this);
  else
    calcEwald = new NoEwald(statV, *this);
#endif

  calcEnergy.Init(*this);
  calcEwald->Init();
  potential = calcEnergy.SystemTotal();
  InitMoves();
  for(uint m = 0; m < mv::MOVE_KINDS_TOTAL; m++)
    moveTime[m] = 0.0;
}

void System::InitMoves()
{
  moves[mv::DISPLACE] = new Translate(*this, statV);
  moves[mv::MULTIPARTICLE] = new MultiParticle(*this, statV);
  moves[mv::ROTATE] = new Rotate(*this, statV);
  moves[mv::INTRA_SWAP] = new IntraSwap(*this, statV);
  moves[mv::REGROWTH] = new Regrowth(*this, statV);
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
  moves[mv::VOL_TRANSFER] = new VolumeTransfer(*this, statV);
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
  moves[mv::MOL_TRANSFER] = new MoleculeTransfer(*this, statV);
#endif
}

void System::RecalculateTrajectory(Setup &set, uint frameNum)
{
  set.pdb.Init(set.config.in.restart, set.config.in.files.pdb.name, frameNum);
  statV.InitOver(set, *this);
#ifdef VARIABLE_PARTICLE_NUMBER
  molLookup.Init(statV.mol, set.pdb.atoms);
#endif
  coordinates.InitFromPDB(set.pdb.atoms);
  com.CalcCOM();
  cellList.GridAll(boxDimRef, coordinates, molLookupRef);
  calcEnergy.Init(*this);
  calcEwald->Init();
  potential = calcEnergy.SystemTotal();
}

void System::ChooseAndRunMove(const uint step)
{
  double draw = 0;
  uint majKind = 0;
  PickMove(majKind, draw);
  time.SetStart();
  RunMove(majKind, draw, step);
  time.SetStop();
  moveTime[majKind] += time.GetTimDiff();
}
void System::PickMove(uint & kind, double & draw)
{
  prng.PickArbDist(kind, draw, statV.movePerc, statV.totalPerc,
                   mv::MOVE_KINDS_TOTAL);
}

void System::RunMove(uint majKind, double draw, const uint step)
{
  //return now if move targets molecule and there's none in that box.
  uint rejectState = SetParams(majKind, draw);
  //If single atom, redo move as displacement
  if (rejectState == mv::fail_state::ROTATE_ON_SINGLE_ATOM) {
    majKind = mv::DISPLACE;
    Translate * disp = static_cast<Translate *>(moves[mv::DISPLACE]);
    Rotate * rot = static_cast<Rotate *>(moves[mv::ROTATE]);
    rejectState = disp->ReplaceRot(*rot);
  }
  if (rejectState == mv::fail_state::NO_FAIL)
    rejectState = Transform(majKind);
  if (rejectState == mv::fail_state::NO_FAIL)
    CalcEn(majKind);
  Accept(majKind, rejectState, step);
}

uint System::SetParams(const uint kind, const double draw)
{
  return moves[kind]->Prep(draw, statV.movePerc[kind]);
}

uint System::Transform(const uint kind)
{
  return moves[kind]->Transform();
}

void System::CalcEn(const uint kind)
{
  moves[kind]->CalcEn();
}

void System::Accept(const uint kind, const uint rejectState, const uint step)
{
  moves[kind]->Accept(rejectState, step);
}

void System::PrintTime()
{
  //std::cout << "MC moves Execution time:\n";
  printf("%-30s %10.4f sec.\n", "Displacement:", moveTime[mv::DISPLACE]);
  printf("%-30s %10.4f sec.\n", "Rotation:", moveTime[mv::ROTATE]);
  printf("%-30s %10.4f sec.\n", "Intra-Swap:", moveTime[mv::INTRA_SWAP]);
  printf("%-30s %10.4f sec.\n", "Regrowth:", moveTime[mv::REGROWTH]);
  printf("%-30s %10.4f sec.\n", "MultiParticle:", moveTime[mv::MULTIPARTICLE]);

#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
  printf("%-30s %10.4f sec.\n", "Molecule-Transfer:",
         moveTime[mv::MOL_TRANSFER]);
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
  printf("%-30s %10.4f sec.\n", "Volume-Transfer:", moveTime[mv::VOL_TRANSFER]);
#endif
}
<|endoftext|>


<commit_before>#include "config.h"
#include "Window.h"
#include "Global.h"
#include "Input.h"
#include "Egl.h"
#include <GL/gl.h>

Window::Window(int width, int height)
		: Rectangle(0, 0, width, height)
		, running(true)
		, fullscreen(false) {
	display = new Display;
	global = new Global(display->get_registry());
	display->roundtrip();
	input = new Input(this, global->seat);
	surface = global->compositor->create_surface();
	shellsurface = global->shell->get_shell_surface(surface);
	static const struct wl_shell_surface_listener shell_surface_listener = {
		Window::HandlePing,
		Window::HandleConfigure,
		Window::HandlePopupDone
	};
	shellsurface->add_listener((const struct wl_listener *)&shell_surface_listener, this);
	shellsurface->set_title("cairo-wayland-cpp");
	shellsurface->set_toplevel();
	egl = new Egl(display->cobj);
	eglwindow = egl->CreateWindow(surface->cobj, width, height);

	// Create a pixmap font from a TrueType file.
	font = new FTGLTextureFont("/usr/share/fonts/TTF/DejaVuSans.ttf");
	// If something went wrong, bail out.
	if(font->Error())
		throw "Could no load font";
	// Set the font size and render a small text.
	font->FaceSize(14);
}

Window::~Window() {
	delete eglwindow;
	delete egl;
	delete shellsurface;
	delete surface;
	delete input;
	delete global;
	delete display;
}

void Window::HandlePing(void *data,
					struct wl_shell_surface *shell_surface,
					uint32_t serial){
	Window *window = static_cast<Window *>(data);
	window->shellsurface->pong(serial);
}

void Window::HandleConfigure(void *data,
					struct wl_shell_surface *shell_surface,
					uint32_t edges,
					int32_t width,
					int32_t height){
	Window *window = static_cast<Window *>(data);
	window->Resize(width, height);
}

void Window::HandlePopupDone(void *data,
					struct wl_shell_surface *shell_surface){
	//Window *window = static_cast<Window *>(data);
}

void Window::Fullscreen(bool value){
	if(fullscreen == value)
		return;
	fullscreen = value;
	if (value){
		shellsurface->set_fullscreen(ShellSurface::FULLSCREEN_METHOD_DEFAULT,0,NULL);
		display->dispatch(); /* get configure event and update window size */
	} else {
		shellsurface->set_toplevel();
		Resize(oldwidth, oldheight);
	}
}

void Window::Resize(int w, int h){
	if(SetSize(w, h)){
		eglwindow->Resize(w, h);
		glViewport(0, 0, w, h);
	}
}

void Window::run(){
	float ratio;
	int width, height;
	char str[10];
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
	while(running) {
		display->dispatch();
		GetSize(&width, &height); /* after configure event */
		ratio = width / (float) height;
		glViewport(0, 0, width, height);

		glEnable(GL_DEPTH_TEST);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(0.0f, width,
					0.0f, height,
					-10000.0f, 10000.0f);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		glTranslatef(0.0f, (height - font->Ascender()) * 1.0f, 0.0f);
		glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
		sprintf(str,"%.1f fps", eglwindow->fps);
		font->Render(str);

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
		glMatrixMode(GL_MODELVIEW);

		glLoadIdentity();
		glRotatef((input->pointer_x / width) * 360.0f, 0.f, 1.f, 0.f);
		glRotatef((input->pointer_y / height) * 360.0f, 1.f, 0.f, 0.f);

		//Multi-colored side - FRONT
		glBegin(GL_POLYGON);
			glColor3f( 1.0, 0.0, 0.0 ); glVertex3f(  0.5, -0.5, -0.5 ); // P1 is red
			glColor3f( 0.0, 1.0, 0.0 ); glVertex3f(  0.5,  0.5, -0.5 ); // P2 is green
			glColor3f( 0.0, 0.0, 1.0 ); glVertex3f( -0.5,  0.5, -0.5 ); // P3 is blue
			glColor3f( 1.0, 0.0, 1.0 ); glVertex3f( -0.5, -0.5, -0.5 ); // P4 is purple
		glEnd();

		// White side - BACK
		glBegin(GL_POLYGON);
			glColor3f(   1.0,  1.0, 1.0 );
			glVertex3f(  0.5, -0.5, 0.5 );
			glVertex3f(  0.5,  0.5, 0.5 );
			glVertex3f( -0.5,  0.5, 0.5 );
			glVertex3f( -0.5, -0.5, 0.5 );
		glEnd();

		// Purple side - RIGHT
		glBegin(GL_POLYGON);
			glColor3f(  1.0,  0.0,  1.0 );
			glVertex3f( 0.5, -0.5, -0.5 );
			glVertex3f( 0.5,  0.5, -0.5 );
			glVertex3f( 0.5,  0.5,  0.5 );
			glVertex3f( 0.5, -0.5,  0.5 );
		glEnd();

		// Green side - LEFT
		glBegin(GL_POLYGON);
			glColor3f(   0.0,  1.0,  0.0 );
			glVertex3f( -0.5, -0.5,  0.5 );
			glVertex3f( -0.5,  0.5,  0.5 );
			glVertex3f( -0.5,  0.5, -0.5 );
			glVertex3f( -0.5, -0.5, -0.5 );
		glEnd();

		// Blue side - TOP
		glBegin(GL_POLYGON);
			glColor3f(   0.0,  0.0,  1.0 );
			glVertex3f(  0.5,  0.5,  0.5 );
			glVertex3f(  0.5,  0.5, -0.5 );
			glVertex3f( -0.5,  0.5, -0.5 );
			glVertex3f( -0.5,  0.5,  0.5 );
		glEnd();

		// Red side - BOTTOM
		glBegin(GL_POLYGON);
			glColor3f(   1.0,  0.0,  0.0 );
			glVertex3f(  0.5, -0.5, -0.5 );
			glVertex3f(  0.5, -0.5,  0.5 );
			glVertex3f( -0.5, -0.5,  0.5 );
			glVertex3f( -0.5, -0.5, -0.5 );
		glEnd();
		eglwindow->SwapBuffers();
	}
}
<commit_msg>cleanup memory for font object<commit_after>#include "config.h"
#include "Window.h"
#include "Global.h"
#include "Input.h"
#include "Egl.h"
#include <GL/gl.h>

Window::Window(int width, int height)
		: Rectangle(0, 0, width, height)
		, running(true)
		, fullscreen(false) {
	display = new Display;
	global = new Global(display->get_registry());
	display->roundtrip();
	input = new Input(this, global->seat);
	surface = global->compositor->create_surface();
	shellsurface = global->shell->get_shell_surface(surface);
	static const struct wl_shell_surface_listener shell_surface_listener = {
		Window::HandlePing,
		Window::HandleConfigure,
		Window::HandlePopupDone
	};
	shellsurface->add_listener((const struct wl_listener *)&shell_surface_listener, this);
	shellsurface->set_title("cairo-wayland-cpp");
	shellsurface->set_toplevel();
	egl = new Egl(display->cobj);
	eglwindow = egl->CreateWindow(surface->cobj, width, height);

	font = new FTGLTextureFont("/usr/share/fonts/TTF/DejaVuSans.ttf");
	if(font->Error())
		throw "Could no load font";
	font->FaceSize(14);
}

Window::~Window() {
	delete font;
	delete eglwindow;
	delete egl;
	delete shellsurface;
	delete surface;
	delete input;
	delete global;
	delete display;
}

void Window::HandlePing(void *data,
					struct wl_shell_surface *shell_surface,
					uint32_t serial){
	Window *window = static_cast<Window *>(data);
	window->shellsurface->pong(serial);
}

void Window::HandleConfigure(void *data,
					struct wl_shell_surface *shell_surface,
					uint32_t edges,
					int32_t width,
					int32_t height){
	Window *window = static_cast<Window *>(data);
	window->Resize(width, height);
}

void Window::HandlePopupDone(void *data,
					struct wl_shell_surface *shell_surface){
	//Window *window = static_cast<Window *>(data);
}

void Window::Fullscreen(bool value){
	if(fullscreen == value)
		return;
	fullscreen = value;
	if (value){
		shellsurface->set_fullscreen(ShellSurface::FULLSCREEN_METHOD_DEFAULT,0,NULL);
		display->dispatch(); /* get configure event and update window size */
	} else {
		shellsurface->set_toplevel();
		Resize(oldwidth, oldheight);
	}
}

void Window::Resize(int w, int h){
	if(SetSize(w, h)){
		eglwindow->Resize(w, h);
		glViewport(0, 0, w, h);
	}
}

void Window::run(){
	float ratio;
	int width, height;
	char str[10];
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
	while(running) {
		display->dispatch();
		GetSize(&width, &height); /* after configure event */
		ratio = width / (float) height;
		glViewport(0, 0, width, height);

		glEnable(GL_DEPTH_TEST);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(0.0f, width,
					0.0f, height,
					-10000.0f, 10000.0f);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		glTranslatef(0.0f, (height - font->Ascender()) * 1.0f, 0.0f);
		glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
		sprintf(str,"%.1f fps", eglwindow->fps);
		font->Render(str);

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
		glMatrixMode(GL_MODELVIEW);

		glLoadIdentity();
		glRotatef((input->pointer_x / width) * 360.0f, 0.f, 1.f, 0.f);
		glRotatef((input->pointer_y / height) * 360.0f, 1.f, 0.f, 0.f);

		//Multi-colored side - FRONT
		glBegin(GL_POLYGON);
			glColor3f( 1.0, 0.0, 0.0 ); glVertex3f(  0.5, -0.5, -0.5 ); // P1 is red
			glColor3f( 0.0, 1.0, 0.0 ); glVertex3f(  0.5,  0.5, -0.5 ); // P2 is green
			glColor3f( 0.0, 0.0, 1.0 ); glVertex3f( -0.5,  0.5, -0.5 ); // P3 is blue
			glColor3f( 1.0, 0.0, 1.0 ); glVertex3f( -0.5, -0.5, -0.5 ); // P4 is purple
		glEnd();

		// White side - BACK
		glBegin(GL_POLYGON);
			glColor3f(   1.0,  1.0, 1.0 );
			glVertex3f(  0.5, -0.5, 0.5 );
			glVertex3f(  0.5,  0.5, 0.5 );
			glVertex3f( -0.5,  0.5, 0.5 );
			glVertex3f( -0.5, -0.5, 0.5 );
		glEnd();

		// Purple side - RIGHT
		glBegin(GL_POLYGON);
			glColor3f(  1.0,  0.0,  1.0 );
			glVertex3f( 0.5, -0.5, -0.5 );
			glVertex3f( 0.5,  0.5, -0.5 );
			glVertex3f( 0.5,  0.5,  0.5 );
			glVertex3f( 0.5, -0.5,  0.5 );
		glEnd();

		// Green side - LEFT
		glBegin(GL_POLYGON);
			glColor3f(   0.0,  1.0,  0.0 );
			glVertex3f( -0.5, -0.5,  0.5 );
			glVertex3f( -0.5,  0.5,  0.5 );
			glVertex3f( -0.5,  0.5, -0.5 );
			glVertex3f( -0.5, -0.5, -0.5 );
		glEnd();

		// Blue side - TOP
		glBegin(GL_POLYGON);
			glColor3f(   0.0,  0.0,  1.0 );
			glVertex3f(  0.5,  0.5,  0.5 );
			glVertex3f(  0.5,  0.5, -0.5 );
			glVertex3f( -0.5,  0.5, -0.5 );
			glVertex3f( -0.5,  0.5,  0.5 );
		glEnd();

		// Red side - BOTTOM
		glBegin(GL_POLYGON);
			glColor3f(   1.0,  0.0,  0.0 );
			glVertex3f(  0.5, -0.5, -0.5 );
			glVertex3f(  0.5, -0.5,  0.5 );
			glVertex3f( -0.5, -0.5,  0.5 );
			glVertex3f( -0.5, -0.5, -0.5 );
		glEnd();
		eglwindow->SwapBuffers();
	}
}
<|endoftext|>


<commit_before>#include <stdexcept>
#include "ClassFile.h"
#include "OutputStream.h"

namespace
{
void writeUnsigned(OutputStream* fp, int n, uint32_t val)
{
  uint8_t buf[16];

  for(int i = n; i >= 0; --i)
    buf[i] = (val >> (8 * (n - i - 1))) & 0xff;

  fp->write(buf, n);
}

void writeWord(OutputStream* fp, uint16_t val)
{
  writeUnsigned(fp, 2, val);
}

struct Writer
{
  Writer(ClassFile const& c) : m_class(c)
  {
  }

  ClassFile const& m_class;

  void write(OutputStream* fp)
  {
    writeHeader(fp);
    writeConstPool(fp);
    writeFlagAndClass(fp);
    writeInterface(fp);
    writeField(fp);
    writeMethod(fp);
    writeAttr(fp);
  }

  void writeHeader(OutputStream* fp)
  {
    writeUnsigned(fp, 4, 0xCAFEBABE);
    writeWord(fp, m_class.minor_version);
    writeWord(fp, m_class.major_version);
  }

  void writeConstPool(OutputStream* fp)
  {
    writeWord(fp, m_class.const_pool_count);

    for(size_t i = 1; i < m_class.const_pool_count; ++i)   // no use index 0
    {
      writeUnsigned(fp, 1, (int)m_class.const_pool[i].tag);

      writeConstPoolContents(m_class.const_pool[i], fp);

      // those are take two entries
      if(m_class.const_pool[i].tag == CONSTANT::Long
         || m_class.const_pool[i].tag == CONSTANT::Double)
        ++i;
    }
  }

  void writeConstPoolContents(const ConstPoolInfo& info, OutputStream* fp)
  {
    switch(info.tag)
    {
    case CONSTANT::Fieldref:
    case CONSTANT::Methodref:
    case CONSTANT::InterfaceMethodref:
      writeWord(fp, info.class_index);
      writeWord(fp, info.name_and_type_index);
      break;
    case CONSTANT::InvokeDynamic:
      fp->write(info.info, 2);
      fp->write(&info.info[2], 2);
      break;
    case CONSTANT::NameAndType:
      writeWord(fp, info.name_index);
      writeWord(fp, info.descriptor_index);
      break;
    case CONSTANT::Class:
      writeWord(fp, info.name_index);
      break;
    case CONSTANT::String:
    case CONSTANT::MethodType:
      fp->write(info.info, 2);
      break;
    case CONSTANT::Integer:
    case CONSTANT::Float:
      fp->write(info.info, 4);
      break;
    case CONSTANT::Long:
    case CONSTANT::Double:
      fp->write(info.info, 4);
      fp->write(&info.info[4], 4);
      break;
    case CONSTANT::Utf8:
      {
        auto const len = info.utf8.size();
        writeWord(fp, len);
        fp->write((uint8_t*)info.utf8.data(), len);
      }
      break;
    case CONSTANT::MethodHandle:
      fp->write(info.info, 1);
      fp->write(&info.info[1], 2);
      break;
    default:
      throw runtime_error("unsupported constant pool tag");
    }
  }

  void writeFlagAndClass(OutputStream* fp)
  {
    writeWord(fp, m_class.access_flags);
    writeWord(fp, m_class.this_class);
    writeWord(fp, m_class.super_class);
  }

  void writeInterface(OutputStream* fp)
  {
    writeWord(fp, m_class.interfaces.size());

    for(auto& itf : m_class.interfaces)
      writeWord(fp, itf);
  }

  void writeField(OutputStream* fp)
  {
    writeWord(fp, m_class.fields.size());

    for(auto& field : m_class.fields)
    {
      writeWord(fp, field.access_flags);
      writeWord(fp, field.name_index);
      writeWord(fp, field.descriptor_index);
      writeWord(fp, field.attrs_count);

      writeAttrInner(field.attrs, field.attrs_count, fp);
    }
  }

  void writeMethod(OutputStream* fp)
  {
    writeWord(fp, m_class.methods.size());

    for(auto& method : m_class.methods)
    {
      writeWord(fp, method.access_flags);
      writeWord(fp, method.name_index);
      writeWord(fp, method.descriptor_index);
      writeWord(fp, method.attrs_count);

      writeAttrInner(method.attrs, method.attrs_count, fp);
    }
  }

  void writeAttr(OutputStream* fp)
  {
    writeWord(fp, m_class.attrs_count);
    writeAttrInner(m_class.attrs, m_class.attrs_count, fp);
  }

  void writeAttrInner(const vector<AttrInfo>& attributes, size_t num, OutputStream* fp)
  {
    for(auto& attr : attributes)
    {
      writeWord(fp, attr.attr_name_index);
      writeUnsigned(fp, 4, attr.attr_len);

      for(auto& inf : attr.info)
        fp->write(&inf, 1);
    }
  }
};
}

// module entry point
void writeClass(OutputStream* fp, ClassFile const& class_)
{
  Writer p(class_);
  p.write(fp);
}

<commit_msg>Dead code elimination<commit_after>#include <stdexcept>
#include "ClassFile.h"
#include "OutputStream.h"

namespace
{
void writeUnsigned(OutputStream* fp, int n, uint32_t val)
{
  uint8_t buf[16];

  for(int i = n; i >= 0; --i)
    buf[i] = (val >> (8 * (n - i - 1))) & 0xff;

  fp->write(buf, n);
}

void writeWord(OutputStream* fp, uint16_t val)
{
  writeUnsigned(fp, 2, val);
}

struct Writer
{
  Writer(ClassFile const& c) : m_class(c)
  {
  }

  ClassFile const& m_class;

  void write(OutputStream* fp)
  {
    writeHeader(fp);
    writeConstPool(fp);
    writeFlagAndClass(fp);
    writeInterface(fp);
    writeField(fp);
    writeMethod(fp);
    writeAttr(fp);
  }

  void writeHeader(OutputStream* fp)
  {
    writeUnsigned(fp, 4, 0xCAFEBABE);
    writeWord(fp, m_class.minor_version);
    writeWord(fp, m_class.major_version);
  }

  void writeConstPool(OutputStream* fp)
  {
    writeWord(fp, m_class.const_pool_count);

    for(size_t i = 1; i < m_class.const_pool_count; ++i)   // no use index 0
    {
      writeUnsigned(fp, 1, (int)m_class.const_pool[i].tag);

      writeConstPoolContents(m_class.const_pool[i], fp);

      // those are take two entries
      if(m_class.const_pool[i].tag == CONSTANT::Long
         || m_class.const_pool[i].tag == CONSTANT::Double)
        ++i;
    }
  }

  void writeConstPoolContents(const ConstPoolInfo& info, OutputStream* fp)
  {
    switch(info.tag)
    {
    case CONSTANT::Fieldref:
    case CONSTANT::Methodref:
    case CONSTANT::InterfaceMethodref:
      writeWord(fp, info.class_index);
      writeWord(fp, info.name_and_type_index);
      break;
    case CONSTANT::InvokeDynamic:
      fp->write(info.info, 2);
      fp->write(&info.info[2], 2);
      break;
    case CONSTANT::NameAndType:
      writeWord(fp, info.name_index);
      writeWord(fp, info.descriptor_index);
      break;
    case CONSTANT::Class:
      writeWord(fp, info.name_index);
      break;
    case CONSTANT::String:
    case CONSTANT::MethodType:
      fp->write(info.info, 2);
      break;
    case CONSTANT::Integer:
    case CONSTANT::Float:
      fp->write(info.info, 4);
      break;
    case CONSTANT::Long:
    case CONSTANT::Double:
      fp->write(info.info, 4);
      fp->write(&info.info[4], 4);
      break;
    case CONSTANT::Utf8:
      {
        auto const len = info.utf8.size();
        writeWord(fp, len);
        fp->write((uint8_t*)info.utf8.data(), len);
      }
      break;
    case CONSTANT::MethodHandle:
      fp->write(info.info, 1);
      fp->write(&info.info[1], 2);
      break;
    default:
      throw runtime_error("unsupported constant pool tag");
    }
  }

  void writeFlagAndClass(OutputStream* fp)
  {
    writeWord(fp, m_class.access_flags);
    writeWord(fp, m_class.this_class);
    writeWord(fp, m_class.super_class);
  }

  void writeInterface(OutputStream* fp)
  {
    writeWord(fp, m_class.interfaces.size());

    for(auto& itf : m_class.interfaces)
      writeWord(fp, itf);
  }

  void writeField(OutputStream* fp)
  {
    writeWord(fp, m_class.fields.size());

    for(auto& field : m_class.fields)
    {
      writeWord(fp, field.access_flags);
      writeWord(fp, field.name_index);
      writeWord(fp, field.descriptor_index);
      writeWord(fp, field.attrs_count);

      writeAttrInner(field.attrs, fp);
    }
  }

  void writeMethod(OutputStream* fp)
  {
    writeWord(fp, m_class.methods.size());

    for(auto& method : m_class.methods)
    {
      writeWord(fp, method.access_flags);
      writeWord(fp, method.name_index);
      writeWord(fp, method.descriptor_index);
      writeWord(fp, method.attrs_count);

      writeAttrInner(method.attrs, fp);
    }
  }

  void writeAttr(OutputStream* fp)
  {
    writeWord(fp, m_class.attrs_count);
    writeAttrInner(m_class.attrs, fp);
  }

  void writeAttrInner(const vector<AttrInfo>& attributes, OutputStream* fp)
  {
    for(auto& attr : attributes)
    {
      writeWord(fp, attr.attr_name_index);
      writeUnsigned(fp, 4, attr.attr_len);

      for(auto& inf : attr.info)
        fp->write(&inf, 1);
    }
  }
};
}

// module entry point
void writeClass(OutputStream* fp, ClassFile const& class_)
{
  Writer p(class_);
  p.write(fp);
}

<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <addrdb.h>

#include <addrman.h>
#include <chainparams.h>
#include <clientversion.h>
#include <cstdint>
#include <hash.h>
#include <logging/timer.h>
#include <random.h>
#include <streams.h>
#include <tinyformat.h>
#include <util/system.h>

namespace {

template <typename Stream, typename Data>
bool SerializeDB(Stream& stream, const Data& data)
{
    // Write and commit header, data
    try {
        CHashWriter hasher(SER_DISK, CLIENT_VERSION);
        stream << Params().MessageStart() << data;
        hasher << Params().MessageStart() << data;
        stream << hasher.GetHash();
    } catch (const std::exception& e) {
        return error("%s: Serialize or I/O error - %s", __func__, e.what());
    }

    return true;
}

template <typename Data>
bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data)
{
    // Generate random temporary filename
    uint16_t randv = 0;
    GetRandBytes((unsigned char*)&randv, sizeof(randv));
    std::string tmpfn = strprintf("%s.%04x", prefix, randv);

    // open temp output file, and associate with CAutoFile
    fs::path pathTmp = gArgs.GetDataDirNet() / tmpfn;
    FILE *file = fsbridge::fopen(pathTmp, "wb");
    CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
    if (fileout.IsNull()) {
        fileout.fclose();
        remove(pathTmp);
        return error("%s: Failed to open file %s", __func__, pathTmp.string());
    }

    // Serialize
    if (!SerializeDB(fileout, data)) {
        fileout.fclose();
        remove(pathTmp);
        return false;
    }
    if (!FileCommit(fileout.Get())) {
        fileout.fclose();
        remove(pathTmp);
        return error("%s: Failed to flush file %s", __func__, pathTmp.string());
    }
    fileout.fclose();

    // replace existing file, if any, with new file
    if (!RenameOver(pathTmp, path)) {
        remove(pathTmp);
        return error("%s: Rename-into-place failed", __func__);
    }

    return true;
}

template <typename Stream, typename Data>
bool DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
{
    try {
        CHashVerifier<Stream> verifier(&stream);
        // de-serialize file header (network specific magic number) and ..
        unsigned char pchMsgTmp[4];
        verifier >> pchMsgTmp;
        // ... verify the network matches ours
        if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
            return error("%s: Invalid network magic number", __func__);

        // de-serialize data
        verifier >> data;

        // verify checksum
        if (fCheckSum) {
            uint256 hashTmp;
            stream >> hashTmp;
            if (hashTmp != verifier.GetHash()) {
                return error("%s: Checksum mismatch, data corrupted", __func__);
            }
        }
    }
    catch (const std::exception& e) {
        return error("%s: Deserialize or I/O error - %s", __func__, e.what());
    }

    return true;
}

template <typename Data>
bool DeserializeFileDB(const fs::path& path, Data& data)
{
    // open input file, and associate with CAutoFile
    FILE* file = fsbridge::fopen(path, "rb");
    CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
    if (filein.IsNull()) {
        LogPrintf("Missing or invalid file %s\n", path.string());
        return false;
    }
    return DeserializeDB(filein, data);
}
} // namespace

CBanDB::CBanDB(fs::path ban_list_path) : m_ban_list_path(std::move(ban_list_path))
{
}

bool CBanDB::Write(const banmap_t& banSet)
{
    return SerializeFileDB("banlist", m_ban_list_path, banSet);
}

bool CBanDB::Read(banmap_t& banSet)
{
    return DeserializeFileDB(m_ban_list_path, banSet);
}

CAddrDB::CAddrDB()
{
    pathAddr = gArgs.GetDataDirNet() / "peers.dat";
}

bool CAddrDB::Write(const CAddrMan& addr)
{
    return SerializeFileDB("peers", pathAddr, addr);
}

bool CAddrDB::Read(CAddrMan& addr)
{
    return DeserializeFileDB(pathAddr, addr);
}

bool CAddrDB::Read(CAddrMan& addr, CDataStream& ssPeers)
{
    bool ret = DeserializeDB(ssPeers, addr, false);
    if (!ret) {
        // Ensure addrman is left in a clean state
        addr.Clear();
    }
    return ret;
}

void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors)
{
    LOG_TIME_SECONDS(strprintf("Flush %d outbound block-relay-only peer addresses to anchors.dat", anchors.size()));
    SerializeFileDB("anchors", anchors_db_path, anchors);
}

std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path)
{
    std::vector<CAddress> anchors;
    if (DeserializeFileDB(anchors_db_path, anchors)) {
        LogPrintf("Loaded %i addresses from %s\n", anchors.size(), anchors_db_path.filename());
    } else {
        anchors.clear();
    }

    fs::remove(anchors_db_path);
    return anchors;
}
<commit_msg>Use addrv2 serialization in anchors.dat<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <addrdb.h>

#include <addrman.h>
#include <chainparams.h>
#include <clientversion.h>
#include <cstdint>
#include <hash.h>
#include <logging/timer.h>
#include <random.h>
#include <streams.h>
#include <tinyformat.h>
#include <util/system.h>

namespace {

template <typename Stream, typename Data>
bool SerializeDB(Stream& stream, const Data& data)
{
    // Write and commit header, data
    try {
        CHashWriter hasher(stream.GetType(), stream.GetVersion());
        stream << Params().MessageStart() << data;
        hasher << Params().MessageStart() << data;
        stream << hasher.GetHash();
    } catch (const std::exception& e) {
        return error("%s: Serialize or I/O error - %s", __func__, e.what());
    }

    return true;
}

template <typename Data>
bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data, int version)
{
    // Generate random temporary filename
    uint16_t randv = 0;
    GetRandBytes((unsigned char*)&randv, sizeof(randv));
    std::string tmpfn = strprintf("%s.%04x", prefix, randv);

    // open temp output file, and associate with CAutoFile
    fs::path pathTmp = gArgs.GetDataDirNet() / tmpfn;
    FILE *file = fsbridge::fopen(pathTmp, "wb");
    CAutoFile fileout(file, SER_DISK, version);
    if (fileout.IsNull()) {
        fileout.fclose();
        remove(pathTmp);
        return error("%s: Failed to open file %s", __func__, pathTmp.string());
    }

    // Serialize
    if (!SerializeDB(fileout, data)) {
        fileout.fclose();
        remove(pathTmp);
        return false;
    }
    if (!FileCommit(fileout.Get())) {
        fileout.fclose();
        remove(pathTmp);
        return error("%s: Failed to flush file %s", __func__, pathTmp.string());
    }
    fileout.fclose();

    // replace existing file, if any, with new file
    if (!RenameOver(pathTmp, path)) {
        remove(pathTmp);
        return error("%s: Rename-into-place failed", __func__);
    }

    return true;
}

template <typename Stream, typename Data>
bool DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
{
    try {
        CHashVerifier<Stream> verifier(&stream);
        // de-serialize file header (network specific magic number) and ..
        unsigned char pchMsgTmp[4];
        verifier >> pchMsgTmp;
        // ... verify the network matches ours
        if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
            return error("%s: Invalid network magic number", __func__);

        // de-serialize data
        verifier >> data;

        // verify checksum
        if (fCheckSum) {
            uint256 hashTmp;
            stream >> hashTmp;
            if (hashTmp != verifier.GetHash()) {
                return error("%s: Checksum mismatch, data corrupted", __func__);
            }
        }
    }
    catch (const std::exception& e) {
        return error("%s: Deserialize or I/O error - %s", __func__, e.what());
    }

    return true;
}

template <typename Data>
bool DeserializeFileDB(const fs::path& path, Data& data, int version)
{
    // open input file, and associate with CAutoFile
    FILE* file = fsbridge::fopen(path, "rb");
    CAutoFile filein(file, SER_DISK, version);
    if (filein.IsNull()) {
        LogPrintf("Missing or invalid file %s\n", path.string());
        return false;
    }
    return DeserializeDB(filein, data);
}
} // namespace

CBanDB::CBanDB(fs::path ban_list_path) : m_ban_list_path(std::move(ban_list_path))
{
}

bool CBanDB::Write(const banmap_t& banSet)
{
    return SerializeFileDB("banlist", m_ban_list_path, banSet, CLIENT_VERSION);
}

bool CBanDB::Read(banmap_t& banSet)
{
    return DeserializeFileDB(m_ban_list_path, banSet, CLIENT_VERSION);
}

CAddrDB::CAddrDB()
{
    pathAddr = gArgs.GetDataDirNet() / "peers.dat";
}

bool CAddrDB::Write(const CAddrMan& addr)
{
    return SerializeFileDB("peers", pathAddr, addr, CLIENT_VERSION);
}

bool CAddrDB::Read(CAddrMan& addr)
{
    return DeserializeFileDB(pathAddr, addr, CLIENT_VERSION);
}

bool CAddrDB::Read(CAddrMan& addr, CDataStream& ssPeers)
{
    bool ret = DeserializeDB(ssPeers, addr, false);
    if (!ret) {
        // Ensure addrman is left in a clean state
        addr.Clear();
    }
    return ret;
}

void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors)
{
    LOG_TIME_SECONDS(strprintf("Flush %d outbound block-relay-only peer addresses to anchors.dat", anchors.size()));
    SerializeFileDB("anchors", anchors_db_path, anchors, CLIENT_VERSION | ADDRV2_FORMAT);
}

std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path)
{
    std::vector<CAddress> anchors;
    if (DeserializeFileDB(anchors_db_path, anchors, CLIENT_VERSION | ADDRV2_FORMAT)) {
        LogPrintf("Loaded %i addresses from %s\n", anchors.size(), anchors_db_path.filename());
    } else {
        anchors.clear();
    }

    fs::remove(anchors_db_path);
    return anchors;
}
<|endoftext|>


<commit_before>/*
 *  beagle.cpp
 *  BEAGLE
 *
 * @author Andrew Rambaut
 * @author Marc Suchard
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <list>
#include <vector>

#include "beagle.h"
#include "BeagleImpl.h"

#ifdef CUDA
	#include "CUDA/BeagleCUDAImpl.h"
#endif
#include "CPU/BeagleCPUImpl.h"

BeagleImpl **instances = NULL;
int instanceCount = 0;

std::list<BeagleImplFactory*> implFactory;

ResourceList* getResourceList() {
	return null;
}

int createInstance(
				int bufferCount,
				int tipCount,
				int stateCount,
				int patternCount,
				int eigenDecompositionCount,
				int matrixCount,
				int* resourceList,
				int resourceCount,
				int preferenceFlags,
				int requirementFlags )
{
	// Set-up a list of implementation factories in trial-order
	if (implFactory.size() == 0) {
#ifdef CUDA
		implFactory.push_back(new BeagleCUDAImplFactory());
#endif
		implFactory.push_back(new BeagleCPUImplFactory());
	}

	// Try each implementation
    for(std::list<BeagleImplFactory*>::iterator factory = implFactory.begin();
		factory != implFactory.end(); factory++) {
    	fprintf(stderr,"BEAGLE bootstrap: %s - ",(*factory)->getName());

    	BeagleImpl* beagle = (*factory)->createImpl(
    		bufferCount,
    		tipCount,
    		stateCount,
    		patternCount,
    		eigenDecompositionCount,
    		matrixCount);

    	if (beagle != NULL) {
    		fprintf(stderr,"Success\n");
    		int instance = instanceCount;
    	    instanceCount++;
    	    instances = (BeagleImpl **)realloc(instances, sizeof(BeagleImpl *) * instanceCount);
    	    instances[instance] = beagle;
    	    return instance;
    	}
    	fprintf(stderr,"Failed\n");
    }

    // No implementations found or appropriate
    return ERROR;
}

void initializeInstance(
						int *instance,
						int instanceCount,
						InstanceDetails* returnInfo)
{
	// TODO: Actual creation of instances should wait until here
}

void finalize(int *instance, int instanceCount)
{
	for (int i = 0; i < instanceCount; i++)
	    instances[instance]->finalize();
}

int setPartials(
                    int* instance,
                    int instanceCount,
					int bufferIndex,
					const double* inPartials)
{
	for (int i = 0; i < instanceCount; i++)
	    instances[instance]->setTipPartials(bufferIndex, inPartials);

	return 0;
}

int getPartials(int* instance, int bufferIndex, double *outPartials)
{
	for (int i = 0; i < instanceCount; i++)
	    instances[instance]->getPartials(bufferIndex, outPartials);

	return 0;
}

int setTipStates(
                  int* instance,
                  int instanceCount,
				  int tipIndex,
				  const int* inStates)
{
	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setTipStates(tipIndex, inStates);

	return 0;
}

int setStateFrequencies(int* instance,
                         int instanceCount,
                         const double* inStateFrequencies)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->setStateFrequencies(inStateFrequencies);
	return 0;
}

int setEigenDecomposition(
                           int* instance,
                           int instanceCount,
						   int eigenIndex,
						   const double** inEigenVectors,
						   const double** inInverseEigenVectors,
						   const double* inEigenValues)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setEigenDecomposition(eigenIndex, inEigenVectors, inInverseEigenVectors, inEigenValues);
	return 0;
}

int setTransitionMatrix(	int* instance,
                			int matrixIndex,
                			const double* inMatrix)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setTransitionMatrix(matrixIndex, inMatrix);
	return 0;
}

int updateTransitionMatrices(
                                            int* instance,
                                            int instanceCount,
                                            int eigenIndex,
                                            const int* probabilityIndices,
                                            const int* firstDerivativeIndices,
                                            const int* secondDervativeIndices,
                                            const double* edgeLengths,
                                            int count)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->updateTransitionMatrices(eigenIndex, probabilityIndices, firstDerivativeIndices, secondDervativeIndices, edgeLengths, count);
	return 0;
}

int updatePartials(
                       int* instance,
                       int instanceCount,
					   int* operations,
					   int operationCount,
					   int rescale)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->calculatePartials(operations, operationCount, rescale);
	return 0;
}

int calculateRootLogLikelihoods(
                             int* instance,
                             int instanceCount,
		                     const int* bufferIndices,
		                     int count,
		                     const double* weights,
		                     const double** stateFrequencies,
			                 double* outLogLikelihoods)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->calculateLogLikelihoods(bufferIndices, count, weights, stateFrequencies, outLogLikelihoods);
	return 0;
}

int calculateEdgeLogLikelihoods(
							 int* instance,
							 int instanceCount,
		                     const int* parentBufferIndices,
		                     const int* childBufferIndices,
		                     const int* probabilityIndices,
		                     const int* firstDerivativeIndices,
		                     const int* secondDerivativeIndices,
		                     int count,
		                     const double* weights,
		                     const double** stateFrequencies,
		                     double* outLogLikelihoods,
			                 double* outFirstDerivatives,
			                 double* outSecondDerivatives)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->calculateEdgeLogLikelihoods(
   											parentBufferIndices,
   											childBufferIndices,
   											probabilityIndices,
   											firstDerivativeIndices,
   											secondDerivativeIndices,
											count,
											weights,
											stateFrequencies,
											outLogLikelihoods,
											outFirstDerivatives,
											outSecondDerivatives);
	return 0;
}

<commit_msg>finalize updated<commit_after>/*
 *  beagle.cpp
 *  BEAGLE
 *
 * @author Andrew Rambaut
 * @author Marc Suchard
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <list>
#include <vector>

#include "beagle.h"
#include "BeagleImpl.h"

#ifdef CUDA
	#include "CUDA/BeagleCUDAImpl.h"
#endif
#include "CPU/BeagleCPUImpl.h"

BeagleImpl **instances = NULL;
int instanceCount = 0;

std::list<BeagleImplFactory*> implFactory;

ResourceList* getResourceList() {
	return null;
}

int createInstance(
				int bufferCount,
				int tipCount,
				int stateCount,
				int patternCount,
				int eigenDecompositionCount,
				int matrixCount,
				int* resourceList,
				int resourceCount,
				int preferenceFlags,
				int requirementFlags )
{
	// Set-up a list of implementation factories in trial-order
	if (implFactory.size() == 0) {
#ifdef CUDA
		implFactory.push_back(new BeagleCUDAImplFactory());
#endif
		implFactory.push_back(new BeagleCPUImplFactory());
	}

	// Try each implementation
    for(std::list<BeagleImplFactory*>::iterator factory = implFactory.begin();
		factory != implFactory.end(); factory++) {
    	fprintf(stderr,"BEAGLE bootstrap: %s - ",(*factory)->getName());

    	BeagleImpl* beagle = (*factory)->createImpl(
    		bufferCount,
    		tipCount,
    		stateCount,
    		patternCount,
    		eigenDecompositionCount,
    		matrixCount);

    	if (beagle != NULL) {
    		fprintf(stderr,"Success\n");
    		int instance = instanceCount;
    	    instanceCount++;
    	    instances = (BeagleImpl **)realloc(instances, sizeof(BeagleImpl *) * instanceCount);
    	    instances[instance] = beagle;
    	    return instance;
    	}
    	fprintf(stderr,"Failed\n");
    }

    // No implementations found or appropriate
    return ERROR;
}

void initializeInstance(
						int *instance,
						int instanceCount,
						InstanceDetails* returnInfo)
{
}

void finalize(int *instance, int instanceCount)
{
	for (int i = 0; i < instanceCount; i++) {
	    delete instances[instance];
    	instances[instance] = 0L;
	}
}

int setPartials(
                    int* instance,
                    int instanceCount,
					int bufferIndex,
					const double* inPartials)
{
	for (int i = 0; i < instanceCount; i++)
	    instances[instance]->setTipPartials(bufferIndex, inPartials);

	return 0;
}

int getPartials(int* instance, int bufferIndex, double *outPartials)
{
	for (int i = 0; i < instanceCount; i++)
	    instances[instance]->getPartials(bufferIndex, outPartials);

	return 0;
}

int setTipStates(
                  int* instance,
                  int instanceCount,
				  int tipIndex,
				  const int* inStates)
{
	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setTipStates(tipIndex, inStates);

	return 0;
}

int setStateFrequencies(int* instance,
                         int instanceCount,
                         const double* inStateFrequencies)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->setStateFrequencies(inStateFrequencies);
	return 0;
}

int setEigenDecomposition(
                           int* instance,
                           int instanceCount,
						   int eigenIndex,
						   const double** inEigenVectors,
						   const double** inInverseEigenVectors,
						   const double* inEigenValues)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setEigenDecomposition(eigenIndex, inEigenVectors, inInverseEigenVectors, inEigenValues);
	return 0;
}

int setTransitionMatrix(	int* instance,
                			int matrixIndex,
                			const double* inMatrix)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->setTransitionMatrix(matrixIndex, inMatrix);
	return 0;
}

int updateTransitionMatrices(
                                            int* instance,
                                            int instanceCount,
                                            int eigenIndex,
                                            const int* probabilityIndices,
                                            const int* firstDerivativeIndices,
                                            const int* secondDervativeIndices,
                                            const double* edgeLengths,
                                            int count)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->updateTransitionMatrices(eigenIndex, probabilityIndices, firstDerivativeIndices, secondDervativeIndices, edgeLengths, count);
	return 0;
}

int updatePartials(
                       int* instance,
                       int instanceCount,
					   int* operations,
					   int operationCount,
					   int rescale)
{
 	for (int i = 0; i < instanceCount; i++)
  		instances[instance]->calculatePartials(operations, operationCount, rescale);
	return 0;
}

int calculateRootLogLikelihoods(
                             int* instance,
                             int instanceCount,
		                     const int* bufferIndices,
		                     int count,
		                     const double* weights,
		                     const double** stateFrequencies,
			                 double* outLogLikelihoods)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->calculateLogLikelihoods(bufferIndices, count, weights, stateFrequencies, outLogLikelihoods);
	return 0;
}

int calculateEdgeLogLikelihoods(
							 int* instance,
							 int instanceCount,
		                     const int* parentBufferIndices,
		                     const int* childBufferIndices,
		                     const int* probabilityIndices,
		                     const int* firstDerivativeIndices,
		                     const int* secondDerivativeIndices,
		                     int count,
		                     const double* weights,
		                     const double** stateFrequencies,
		                     double* outLogLikelihoods,
			                 double* outFirstDerivatives,
			                 double* outSecondDerivatives)
{
 	for (int i = 0; i < instanceCount; i++)
   		instances[instance]->calculateEdgeLogLikelihoods(
   											parentBufferIndices,
   											childBufferIndices,
   											probabilityIndices,
   											firstDerivativeIndices,
   											secondDerivativeIndices,
											count,
											weights,
											stateFrequencies,
											outLogLikelihoods,
											outFirstDerivatives,
											outSecondDerivatives);
	return 0;
}

<|endoftext|>


<commit_before>#include "broker.hpp"
#include "message.hpp"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <unordered_map>

namespace {

bool revStrEquals(const std::string& str1, const std::string& str2) { //compare strings in reverse
    if(str1.length() != str2.length()) return false;
    for(int i = str1.length() - 1; i >= 0; --i)
        if(str1[i] != str2[i]) return false;
    return true;
}

bool equalOrPlus(const std::string& pat, const std::string& top) {
    return pat == "+" || revStrEquals(pat, top);
}
} //anonymous namespace

class Subscription {
public:

    Subscription(MqttSubscriber& subscriber, MqttSubscribe::Topic topic,
                 std::vector<std::string> topicParts):
        _subscriber(subscriber),
        _part(std::move(topicParts[topicParts.size() - 1])),
        _topic(std::move(topic.topic)),
        _qos(topic.qos) {
    }

    void newMessage(std::string topic, std::vector<ubyte> payload) {
        _subscriber.newMessage(topic, payload);
    }

    bool isSubscriber(const MqttSubscriber& subscriber) const {
        return &_subscriber == &subscriber;
    }

    bool isSubscription(const MqttSubscriber& subscriber,
                        std::vector<std::string> topics) const {
        return isSubscriber(subscriber) && isTopic(topics);
    }

    bool isTopic(std::vector<std::string> topics) const {
        return std::find(topics.cbegin(), topics.cend(), _topic) == topics.cend();
    }

private:
    MqttSubscriber& _subscriber;
    std::string _part;
    std::string _topic;
    ubyte _qos;
};

struct SubscriptionTree {
public:
    // void addSubscription(Subscription* s, std::vector<std::string> parts) {
    //     assert(parts.size());
    //     if(_useCache) _cache.clear(); //invalidate cache
    //     addSubscriptionImpl(s, parts, null, _nodes);
    // }

    // void addSubscriptionImpl(Subscription s, const(string)[] parts,
    //                          Node* parent, ref Node*[string] nodes) {
    //     auto part = parts[0];
    //     parts = parts[1 .. $];
    //     auto node = addOrFindNode(part, parent, nodes);
    //     if(parts.empty) {
    //         node.leaves ~= s;
    //     } else {
    //         addSubscriptionImpl(s, parts, node, node.branches);
    //     }
    // }

//     void removeSubscription(MqttSubscriber subscriber, ref Node*[string] nodes) {
//         if(_useCache) _cache = _cache.init; //invalidate cache
//         auto newnodes = nodes.dup;
//         foreach(n; newnodes) {
//             if(n.leaves) {
//                 n.leaves = std.algorithm.remove!(l => l.isSubscriber(subscriber))(n.leaves);
//                 if(n.leaves.empty && !n.branches.length) {
//                     removeNode(n.parent, n);
//                 }
//             } else {
//                 removeSubscription(subscriber, n.branches);
//             }
//         }
//     }

//     void removeSubscription(MqttSubscriber subscriber, in string[] topic, ref Node*[string] nodes) {
//         if(_useCache) _cache = _cache.init; //invalidate cache
//         auto newnodes = nodes.dup;
//         foreach(n; newnodes) {
//             if(n.leaves) {
//                 n.leaves = std.algorithm.remove!(l => l.isSubscription(subscriber, topic))(n.leaves);
//                 if(n.leaves.empty && !n.branches.length) {
//                     removeNode(n.parent, n);
//                 }
//             } else {
//                 removeSubscription(subscriber, topic, n.branches);
//             }
//         }
//     }

//     void removeNode(Node* parent, Node* child) {
//         if(parent) {
//             parent.branches.remove(child.part);
//         } else {
//             _nodes.remove(child.part);
//         }
//         if(parent && !parent.branches.length && parent.leaves.empty)
//             removeNode(parent.parent, parent);
//     }

//     void publish(in string topic, string[] topParts, in const(ubyte)[] payload) {
//         publish(topic, topParts, payload, _nodes);
//     }

//     void publish(in string topic, string[] topParts, in const(ubyte)[] payload,
//                  Node*[string] nodes) {
//         //check the cache first
//         if(_useCache && topic in _cache) {
//             foreach(s; _cache[topic]) s.newMessage(topic, payload);
//             return;
//         }

//         //not in the cache or not using the cache, do it the hard way
//         foreach(part; [topParts[0], "#", "+"]) {
//             if(part in nodes) {
//                 if(topParts.length == 1 && "#" in nodes[part].branches) {
//                     //So that "finance/#" matches finance
//                     publishLeaves(topic, payload, topParts, nodes[part].branches["#"].leaves);
//                 }
//                 publishLeaves(topic, payload, topParts, nodes[part].leaves);
//                 if(topParts.length > 1) {
//                     publish(topic, topParts[1..$], payload, nodes[part].branches);
//                 }
//             }
//         }
//     }

//     void publishLeaves(in string topic, in const(ubyte)[] payload,
//                        in string[] topParts,
//                        Subscription[] subscriptions) {
//         foreach(sub; subscriptions) {
//             if(topParts.length == 1 &&
//                equalOrPlus(sub._part, topParts[0])) {
//                 publishLeaf(sub, topic, payload);
//             }
//             else if(sub._part == "#") {
//                 publishLeaf(sub, topic, payload);
//             }
//         }
//     }

//     void publishLeaf(Subscription sub, in string topic, in const(ubyte)[] payload) {
//         sub.newMessage(topic, payload);
//         if(_useCache) _cache[topic] ~= sub;
//     }

    void useCache(bool u) { _useCache = u; }

private:
    struct Node {
        Node(std::string pt, Node* pr):part(pt), parent(pr) {}
        std::string part;
        Node* parent;
        std::unordered_map<std::string, Node*> branches;
        std::vector<Subscription> leaves;
    };

    bool _useCache;
    std::unordered_map<std::string, Subscription*> _cache;
    std::unordered_map<std::string, Node*> _nodes;

    Node* addOrFindNode(std::string part, Node* parent,
                        std::unordered_map<std::string, Node*> nodes) {
        if(nodes.count(part) && part == nodes[part]->part) {
            return nodes[part];
        }
        auto node = new Node(part, parent);
        nodes[part] = node;
        return node;
    }
};

class MqttBroker {
public:

    void subscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) {
        std::vector<MqttSubscribe::Topic> newTopics;
        std::transform(topics.cbegin(), topics.cend(), std::back_inserter(newTopics),
                       [](std::string t) { return MqttSubscribe::Topic(t, 0); });
        subscribe(subscriber, newTopics);
    }

    void subscribe(MqttSubscriber& subscriber, std::vector<MqttSubscribe::Topic> topics) {
        (void)subscriber;
        for(const auto& t: topics) {
            std::vector<std::string> parts;
            boost::split(parts, t.topic, boost::is_any_of("/"));
            //_subscriptions.addSubscription(Subscription(subscriber, t, parts), parts);
        }
    }

    // void unsubscribe(MqttSubscriber& subscriber) {
    //     _subscriptions.removeSubscription(subscriber, _subscriptions._nodes);
    // }

    // void unsubscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) {
    //     _subscriptions.removeSubscription(subscriber, topics, _subscriptions._nodes);
    // }

    // void publish(std::string topic, std::vector<ubyte> payload) {
    //     auto topParts = array(splitter(topic, "/"));
    //     publish(topic, topParts, payload);
    // }

    void useCache(bool u) { _subscriptions.useCache(u); }

private:

    SubscriptionTree _subscriptions;

    // void publish(std::string topic, std::vector<std::string> topParts,
    //              std::vector<ubyte> payload) {
    //     _subscriptions.publish(topic, topParts, payload);
    // }
};
<commit_msg>Uncommented addSubscriptionImpl<commit_after>#include "broker.hpp"
#include "message.hpp"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <unordered_map>

namespace {

bool revStrEquals(const std::string& str1, const std::string& str2) { //compare strings in reverse
    if(str1.length() != str2.length()) return false;
    for(int i = str1.length() - 1; i >= 0; --i)
        if(str1[i] != str2[i]) return false;
    return true;
}

bool equalOrPlus(const std::string& pat, const std::string& top) {
    return pat == "+" || revStrEquals(pat, top);
}
} //anonymous namespace

class Subscription {
public:

    Subscription(MqttSubscriber& subscriber, MqttSubscribe::Topic topic,
                 std::vector<std::string> topicParts):
        _subscriber(subscriber),
        _part(std::move(topicParts[topicParts.size() - 1])),
        _topic(std::move(topic.topic)),
        _qos(topic.qos) {
    }

    void newMessage(std::string topic, std::vector<ubyte> payload) {
        _subscriber.newMessage(topic, payload);
    }

    bool isSubscriber(const MqttSubscriber& subscriber) const {
        return &_subscriber == &subscriber;
    }

    bool isSubscription(const MqttSubscriber& subscriber,
                        std::vector<std::string> topics) const {
        return isSubscriber(subscriber) && isTopic(topics);
    }

    bool isTopic(std::vector<std::string> topics) const {
        return std::find(topics.cbegin(), topics.cend(), _topic) == topics.cend();
    }

private:
    MqttSubscriber& _subscriber;
    std::string _part;
    std::string _topic;
    ubyte _qos;
};

struct SubscriptionTree {
public:
    // void addSubscription(Subscription* s, std::vector<std::string> parts) {
    //     assert(parts.size());
    //     if(_useCache) _cache.clear(); //invalidate cache
    //     addSubscriptionImpl(s, parts, null, _nodes);
    // }

//     void removeSubscription(MqttSubscriber subscriber, ref Node*[string] nodes) {
//         if(_useCache) _cache = _cache.init; //invalidate cache
//         auto newnodes = nodes.dup;
//         foreach(n; newnodes) {
//             if(n.leaves) {
//                 n.leaves = std.algorithm.remove!(l => l.isSubscriber(subscriber))(n.leaves);
//                 if(n.leaves.empty && !n.branches.length) {
//                     removeNode(n.parent, n);
//                 }
//             } else {
//                 removeSubscription(subscriber, n.branches);
//             }
//         }
//     }

//     void removeSubscription(MqttSubscriber subscriber, in string[] topic, ref Node*[string] nodes) {
//         if(_useCache) _cache = _cache.init; //invalidate cache
//         auto newnodes = nodes.dup;
//         foreach(n; newnodes) {
//             if(n.leaves) {
//                 n.leaves = std.algorithm.remove!(l => l.isSubscription(subscriber, topic))(n.leaves);
//                 if(n.leaves.empty && !n.branches.length) {
//                     removeNode(n.parent, n);
//                 }
//             } else {
//                 removeSubscription(subscriber, topic, n.branches);
//             }
//         }
//     }

//     void removeNode(Node* parent, Node* child) {
//         if(parent) {
//             parent.branches.remove(child.part);
//         } else {
//             _nodes.remove(child.part);
//         }
//         if(parent && !parent.branches.length && parent.leaves.empty)
//             removeNode(parent.parent, parent);
//     }

//     void publish(in string topic, string[] topParts, in const(ubyte)[] payload) {
//         publish(topic, topParts, payload, _nodes);
//     }

//     void publish(in string topic, string[] topParts, in const(ubyte)[] payload,
//                  Node*[string] nodes) {
//         //check the cache first
//         if(_useCache && topic in _cache) {
//             foreach(s; _cache[topic]) s.newMessage(topic, payload);
//             return;
//         }

//         //not in the cache or not using the cache, do it the hard way
//         foreach(part; [topParts[0], "#", "+"]) {
//             if(part in nodes) {
//                 if(topParts.length == 1 && "#" in nodes[part].branches) {
//                     //So that "finance/#" matches finance
//                     publishLeaves(topic, payload, topParts, nodes[part].branches["#"].leaves);
//                 }
//                 publishLeaves(topic, payload, topParts, nodes[part].leaves);
//                 if(topParts.length > 1) {
//                     publish(topic, topParts[1..$], payload, nodes[part].branches);
//                 }
//             }
//         }
//     }

//     void publishLeaves(in string topic, in const(ubyte)[] payload,
//                        in string[] topParts,
//                        Subscription[] subscriptions) {
//         foreach(sub; subscriptions) {
//             if(topParts.length == 1 &&
//                equalOrPlus(sub._part, topParts[0])) {
//                 publishLeaf(sub, topic, payload);
//             }
//             else if(sub._part == "#") {
//                 publishLeaf(sub, topic, payload);
//             }
//         }
//     }

//     void publishLeaf(Subscription sub, in string topic, in const(ubyte)[] payload) {
//         sub.newMessage(topic, payload);
//         if(_useCache) _cache[topic] ~= sub;
//     }

    void useCache(bool u) { _useCache = u; }

private:
    struct Node {
        Node(std::string pt, Node* pr):part(pt), parent(pr) {}
        std::string part;
        Node* parent;
        std::unordered_map<std::string, Node*> branches;
        std::vector<Subscription*> leaves;
    };

    bool _useCache;
    std::unordered_map<std::string, Subscription*> _cache;
    std::unordered_map<std::string, Node*> _nodes;

    void addSubscriptionImpl(Subscription* s,
                             std::deque<std::string> parts,
                             Node* parent,
                             std::unordered_map<std::string, Node*> nodes) {
        auto part = parts.front();
        parts.pop_front();
        auto node = addOrFindNode(part, parent, nodes);
        if(!parts.size()) {
            node->leaves.emplace_back(s);
        } else {
            addSubscriptionImpl(s, parts, node, node->branches);
        }
    }

    Node* addOrFindNode(std::string part, Node* parent,
                        std::unordered_map<std::string, Node*> nodes) {
        if(nodes.count(part) && part == nodes[part]->part) {
            return nodes[part];
        }
        auto node = new Node(part, parent);
        nodes[part] = node;
        return node;
    }
};

class MqttBroker {
public:

    void subscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) {
        std::vector<MqttSubscribe::Topic> newTopics;
        std::transform(topics.cbegin(), topics.cend(), std::back_inserter(newTopics),
                       [](std::string t) { return MqttSubscribe::Topic(t, 0); });
        subscribe(subscriber, newTopics);
    }

    void subscribe(MqttSubscriber& subscriber, std::vector<MqttSubscribe::Topic> topics) {
        (void)subscriber;
        for(const auto& t: topics) {
            std::vector<std::string> parts;
            boost::split(parts, t.topic, boost::is_any_of("/"));
            //_subscriptions.addSubscription(Subscription(subscriber, t, parts), parts);
        }
    }

    // void unsubscribe(MqttSubscriber& subscriber) {
    //     _subscriptions.removeSubscription(subscriber, _subscriptions._nodes);
    // }

    // void unsubscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) {
    //     _subscriptions.removeSubscription(subscriber, topics, _subscriptions._nodes);
    // }

    // void publish(std::string topic, std::vector<ubyte> payload) {
    //     auto topParts = array(splitter(topic, "/"));
    //     publish(topic, topParts, payload);
    // }

    void useCache(bool u) { _subscriptions.useCache(u); }

private:

    SubscriptionTree _subscriptions;

    // void publish(std::string topic, std::vector<std::string> topParts,
    //              std::vector<ubyte> payload) {
    //     _subscriptions.publish(topic, topParts, payload);
    // }
};
<|endoftext|>


<commit_before>// $Id$

/*
Copyright (c) 2007-2010, Trustees of The Leland Stanford Junior University
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 Stanford University 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.
*/

#ifndef _BUFFER_HPP_
#define _BUFFER_HPP_

#include <vector>

#include "vc.hpp"
#include "flit.hpp"
#include "outputset.hpp"
#include "routefunc.hpp"
#include "config_utils.hpp"

class Buffer : public Module {

  int _vc_size;
  int _shared_count;
  int _shared_size;
  bool _dynamic_sharing;

  vector<VC*> _vc;

public:

  Buffer( const Configuration& config, int outputs,
	  Module *parent, const string& name );
  ~Buffer();

  bool AddFlit( int vc, Flit *f );

  Flit *RemoveFlit( int vc );

  inline Flit *FrontFlit( int vc ) const
  {
    return _vc[vc]->FrontFlit( );
  }

  inline bool Empty( int vc ) const
  {
    return _vc[vc]->Empty( );
  }

  bool Full( int vc ) const;

  inline VC::eVCState GetState( int vc ) const
  {
    return _vc[vc]->GetState( );
  }

  inline int GetStateTime( int vc ) const
  {
    return _vc[vc]->GetStateTime( );
  }

  inline void SetState( int vc, VC::eVCState s )
  {
    _vc[vc]->SetState(s);
  }

  inline const OutputSet *GetRouteSet( int vc ) const
  {
    return _vc[vc]->GetRouteSet( );
  }

  inline void SetOutput( int vc, int out_port, int out_vc )
  {
    _vc[vc]->SetOutput(out_port, out_vc);
  }

  inline int GetOutputPort( int vc ) const
  {
    return _vc[vc]->GetOutputPort( );
  }

  inline int GetOutputVC( int vc ) const
  {
    return _vc[vc]->GetOutputVC( );
  }

  inline int GetPriority( int vc ) const
  {
    return _vc[vc]->GetPriority( );
  }

  inline void Route( int vc, tRoutingFunction rf, const Router* router, const Flit* f, int in_channel )
  {
    _vc[vc]->Route(rf, router, f, in_channel);
  }

  inline void AdvanceTime( )
  {
    for(vector<VC*>::iterator i = _vc.begin(); i != _vc.end(); ++i) {
      (*i)->AdvanceTime();
    }
  }

  // ==== Debug functions ====

  inline void SetWatch( int vc, bool watch = true )
  {
    _vc[vc]->SetWatch(watch);
  }

  inline bool IsWatched( int vc ) const
  {
    return _vc[vc]->IsWatched( );
  }

  inline int GetSize( int vc ) const
  {
    return _vc[vc]->GetSize( );
  }

  void Display( ) const;
};

#endif
<commit_msg>remove unused member variable<commit_after>// $Id$

/*
Copyright (c) 2007-2010, Trustees of The Leland Stanford Junior University
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 Stanford University 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.
*/

#ifndef _BUFFER_HPP_
#define _BUFFER_HPP_

#include <vector>

#include "vc.hpp"
#include "flit.hpp"
#include "outputset.hpp"
#include "routefunc.hpp"
#include "config_utils.hpp"

class Buffer : public Module {

  int _vc_size;
  int _shared_count;
  int _shared_size;

  vector<VC*> _vc;

public:

  Buffer( const Configuration& config, int outputs,
	  Module *parent, const string& name );
  ~Buffer();

  bool AddFlit( int vc, Flit *f );

  Flit *RemoveFlit( int vc );

  inline Flit *FrontFlit( int vc ) const
  {
    return _vc[vc]->FrontFlit( );
  }

  inline bool Empty( int vc ) const
  {
    return _vc[vc]->Empty( );
  }

  bool Full( int vc ) const;

  inline VC::eVCState GetState( int vc ) const
  {
    return _vc[vc]->GetState( );
  }

  inline int GetStateTime( int vc ) const
  {
    return _vc[vc]->GetStateTime( );
  }

  inline void SetState( int vc, VC::eVCState s )
  {
    _vc[vc]->SetState(s);
  }

  inline const OutputSet *GetRouteSet( int vc ) const
  {
    return _vc[vc]->GetRouteSet( );
  }

  inline void SetOutput( int vc, int out_port, int out_vc )
  {
    _vc[vc]->SetOutput(out_port, out_vc);
  }

  inline int GetOutputPort( int vc ) const
  {
    return _vc[vc]->GetOutputPort( );
  }

  inline int GetOutputVC( int vc ) const
  {
    return _vc[vc]->GetOutputVC( );
  }

  inline int GetPriority( int vc ) const
  {
    return _vc[vc]->GetPriority( );
  }

  inline void Route( int vc, tRoutingFunction rf, const Router* router, const Flit* f, int in_channel )
  {
    _vc[vc]->Route(rf, router, f, in_channel);
  }

  inline void AdvanceTime( )
  {
    for(vector<VC*>::iterator i = _vc.begin(); i != _vc.end(); ++i) {
      (*i)->AdvanceTime();
    }
  }

  // ==== Debug functions ====

  inline void SetWatch( int vc, bool watch = true )
  {
    _vc[vc]->SetWatch(watch);
  }

  inline bool IsWatched( int vc ) const
  {
    return _vc[vc]->IsWatched( );
  }

  inline int GetSize( int vc ) const
  {
    return _vc[vc]->GetSize( );
  }

  void Display( ) const;
};

#endif
<|endoftext|>