<commit_before>#include "Context.h"

#include <cmath>
#include <iostream>
#include <glm/glm.hpp>

using namespace std;
using namespace canvas;

void
Context::resize(unsigned int _width, unsigned int _height) {
  width = _width;
  height = _height;
  getDefaultSurface().resize(_width, _height);
}

void
Context::fillRect(double x, double y, double w, double h) {
  save();
  beginPath();
  moveTo(x, y);
  lineTo(x + w, y);
  lineTo(x + w, y + h);
  lineTo(x, y + h);
  closePath();
  fill();
  beginPath(); // tmp fix
  restore();
}

void
Context::strokeRect(double x, double y, double w, double h) {
  beginPath();
  moveTo(x, y);
  lineTo(x + w, y);
  lineTo(x + w, y + h);
  lineTo(x, y + h);
  closePath();
  stroke();
}

void
Context::fillText(const std::string & text, double x, double y) {
  if (hasShadow()) {
    // cerr << "DRAWING SHADOW for text " << text << ", w = " << getWidth() << ", h = " << getHeight() << endl;
    auto shadow = createSurface(getDefaultSurface().getWidth(), getDefaultSurface().getHeight());
    Style tmp = fillStyle;
    fillStyle.color = shadowColor;
    shadow->fillText(*this, text, x + shadowOffsetX, y + shadowOffsetY);
    shadow->gaussianBlur(shadowBlur, shadowBlur);
    fillStyle = tmp;
    drawImage(*shadow, 0, 0, shadow->getWidth(), shadow->getHeight());
  }
  getDefaultSurface().fillText(*this, text, x, y);
}

// Implementation by node-canvas (Node canvas is a Cairo backed Canvas implementation for NodeJS)
// Original implementation influenced by WebKit.
void
Context::arcTo(double x1, double y1, double x2, double y2, double radius) {
#if 0
  Point _p0 = getCurrentPoint();
  glm::dvec2 current(_p0.x, _p0.y);
  glm::dvec2 p1(x1, y1), p2(x2, y2);

  glm::dvec2 v1 = glm::normalize(current - p1);
  glm::dvec2 v2 = glm::normalize(p2 - p1);

  double alpha = atan2(v1.y, v1.x) - atan2(v2.y, v2.x);
  if (alpha < 0) alpha += 2*M_PI;
  // TODO obtuse angles

  double dist = radius / sin(alpha / 2) * cos(alpha / 2);
  // calculate tangential points
  glm::dvec2 t1 = dist * v1 + p1;

  double a0 = atan2(v1.y, v1.x) - M_PI / 2;
  glm::dvec2 nv1(cos(a0), sin(a0));
  glm::dvec2 c = t1 + radius * nv1;

  double a1 = atan2(v1.y, v1.x) + M_PI / 2;
  double a2 = atan2(v2.y, v2.x) - M_PI / 2;

  lineTo(t1.x, t1.y);
  arc(c.x, c.y, radius, a1, a2, a1 > a2);
  lineTo(p2.x, p2.y);
#else
  Point p0 = getCurrentPoint();
  Point p1(x1, y1);
  Point p2(x2, y2);

  if ((p1.x == p0.x && p1.y == p0.y) || (p1.x == p2.x && p1.y == p2.y) || radius == 0.f) {
    lineTo(p1.x, p1.y);
    // p2?
    return;
  }

  Point p1p0((p0.x - p1.x), (p0.y - p1.y));
  Point p1p2((p2.x - p1.x), (p2.y - p1.y));
  float p1p0_length = sqrt(p1p0.x * p1p0.x + p1p0.y * p1p0.y);
  float p1p2_length = sqrt(p1p2.x * p1p2.x + p1p2.y * p1p2.y);

  double cos_phi = (p1p0.x * p1p2.x + p1p0.y * p1p2.y) / (p1p0_length * p1p2_length);
  // all points on a line logic
  if (-1 == cos_phi) {
    lineTo(p1.x, p1.y);
    // p2?
    return;
  }

  if (1 == cos_phi) {
    // add infinite far away point
    unsigned int max_length = 65535;
    double factor_max = max_length / p1p0_length;
    Point ep((p0.x + factor_max * p1p0.x), (p0.y + factor_max * p1p0.y));
    lineTo(ep.x, ep.y);
    return;
  }

  double tangent = radius / tan(acos(cos_phi) / 2);
  double factor_p1p0 = tangent / p1p0_length;
  Point t_p1p0((p1.x + factor_p1p0 * p1p0.x), (p1.y + factor_p1p0 * p1p0.y));

  Point orth_p1p0(p1p0.y, -p1p0.x);
  double orth_p1p0_length = sqrt(orth_p1p0.x * orth_p1p0.x + orth_p1p0.y * orth_p1p0.y);
  double factor_ra = radius / orth_p1p0_length;

  double cos_alpha = (orth_p1p0.x * p1p2.x + orth_p1p0.y * p1p2.y) / (orth_p1p0_length * p1p2_length);
  if (cos_alpha < 0.f) {
    orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
  }

  Point p((t_p1p0.x + factor_ra * orth_p1p0.x), (t_p1p0.y + factor_ra * orth_p1p0.y));

  orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
  double sa = acos(orth_p1p0.x / orth_p1p0_length);
  if (orth_p1p0.y < 0.f) {
    sa = 2 * M_PI - sa;
  }

  bool anticlockwise = false;

  double factor_p1p2 = tangent / p1p2_length;
  Point t_p1p2((p1.x + factor_p1p2 * p1p2.x), (p1.y + factor_p1p2 * p1p2.y));
  Point orth_p1p2((t_p1p2.x - p.x),(t_p1p2.y - p.y));
  double orth_p1p2_length = sqrt(orth_p1p2.x * orth_p1p2.x + orth_p1p2.y * orth_p1p2.y);
  double ea = acos(orth_p1p2.x / orth_p1p2_length);

  if (orth_p1p2.y < 0) ea = 2 * M_PI - ea;
  if ((sa > ea) && ((sa - ea) < M_PI)) anticlockwise = true;
  if ((sa < ea) && ((ea - sa) > M_PI)) anticlockwise = true;

  cerr << "ARC " << int(t_p1p0.x) << " " << int(t_p1p0.y) << " " << int(p.x) << " " << int(p.y) << " " << radius << " " << int(sa * 180.0 / M_PI) << " " << int(ea * 180.0 / M_PI) << " " << (anticlockwise ? "acw" : "cw") << endl;

  lineTo(t_p1p0.x, t_p1p0.y);
  arc(p.x, p.y, radius, sa, ea, anticlockwise); // && M_PI * 2 != radius);
#endif
}
<commit_msg>temporarily remove lineTo<commit_after>#include "Context.h"

#include <cmath>
#include <iostream>
#include <glm/glm.hpp>

using namespace std;
using namespace canvas;

void
Context::resize(unsigned int _width, unsigned int _height) {
  width = _width;
  height = _height;
  getDefaultSurface().resize(_width, _height);
}

void
Context::fillRect(double x, double y, double w, double h) {
  save();
  beginPath();
  moveTo(x, y);
  lineTo(x + w, y);
  lineTo(x + w, y + h);
  lineTo(x, y + h);
  closePath();
  fill();
  beginPath(); // tmp fix
  restore();
}

void
Context::strokeRect(double x, double y, double w, double h) {
  beginPath();
  moveTo(x, y);
  lineTo(x + w, y);
  lineTo(x + w, y + h);
  lineTo(x, y + h);
  closePath();
  stroke();
}

void
Context::fillText(const std::string & text, double x, double y) {
  if (hasShadow()) {
    // cerr << "DRAWING SHADOW for text " << text << ", w = " << getWidth() << ", h = " << getHeight() << endl;
    auto shadow = createSurface(getDefaultSurface().getWidth(), getDefaultSurface().getHeight());
    Style tmp = fillStyle;
    fillStyle.color = shadowColor;
    shadow->fillText(*this, text, x + shadowOffsetX, y + shadowOffsetY);
    shadow->gaussianBlur(shadowBlur, shadowBlur);
    fillStyle = tmp;
    drawImage(*shadow, 0, 0, shadow->getWidth(), shadow->getHeight());
  }
  getDefaultSurface().fillText(*this, text, x, y);
}

// Implementation by node-canvas (Node canvas is a Cairo backed Canvas implementation for NodeJS)
// Original implementation influenced by WebKit.
void
Context::arcTo(double x1, double y1, double x2, double y2, double radius) {
#if 0
  Point _p0 = getCurrentPoint();
  glm::dvec2 current(_p0.x, _p0.y);
  glm::dvec2 p1(x1, y1), p2(x2, y2);

  glm::dvec2 v1 = glm::normalize(current - p1);
  glm::dvec2 v2 = glm::normalize(p2 - p1);

  double alpha = atan2(v1.y, v1.x) - atan2(v2.y, v2.x);
  if (alpha < 0) alpha += 2*M_PI;
  // TODO obtuse angles

  double dist = radius / sin(alpha / 2) * cos(alpha / 2);
  // calculate tangential points
  glm::dvec2 t1 = dist * v1 + p1;

  double a0 = atan2(v1.y, v1.x) - M_PI / 2;
  glm::dvec2 nv1(cos(a0), sin(a0));
  glm::dvec2 c = t1 + radius * nv1;

  double a1 = atan2(v1.y, v1.x) + M_PI / 2;
  double a2 = atan2(v2.y, v2.x) - M_PI / 2;

  lineTo(t1.x, t1.y);
  arc(c.x, c.y, radius, a1, a2, a1 > a2);
  lineTo(p2.x, p2.y);
#else
  Point p0 = getCurrentPoint();
  Point p1(x1, y1);
  Point p2(x2, y2);

  if ((p1.x == p0.x && p1.y == p0.y) || (p1.x == p2.x && p1.y == p2.y) || radius == 0.f) {
    lineTo(p1.x, p1.y);
    // p2?
    return;
  }

  Point p1p0((p0.x - p1.x), (p0.y - p1.y));
  Point p1p2((p2.x - p1.x), (p2.y - p1.y));
  float p1p0_length = sqrt(p1p0.x * p1p0.x + p1p0.y * p1p0.y);
  float p1p2_length = sqrt(p1p2.x * p1p2.x + p1p2.y * p1p2.y);

  double cos_phi = (p1p0.x * p1p2.x + p1p0.y * p1p2.y) / (p1p0_length * p1p2_length);
  // all points on a line logic
  if (-1 == cos_phi) {
    lineTo(p1.x, p1.y);
    // p2?
    return;
  }

  if (1 == cos_phi) {
    // add infinite far away point
    unsigned int max_length = 65535;
    double factor_max = max_length / p1p0_length;
    Point ep((p0.x + factor_max * p1p0.x), (p0.y + factor_max * p1p0.y));
    lineTo(ep.x, ep.y);
    return;
  }

  double tangent = radius / tan(acos(cos_phi) / 2);
  double factor_p1p0 = tangent / p1p0_length;
  Point t_p1p0((p1.x + factor_p1p0 * p1p0.x), (p1.y + factor_p1p0 * p1p0.y));

  Point orth_p1p0(p1p0.y, -p1p0.x);
  double orth_p1p0_length = sqrt(orth_p1p0.x * orth_p1p0.x + orth_p1p0.y * orth_p1p0.y);
  double factor_ra = radius / orth_p1p0_length;

  double cos_alpha = (orth_p1p0.x * p1p2.x + orth_p1p0.y * p1p2.y) / (orth_p1p0_length * p1p2_length);
  if (cos_alpha < 0.f) {
    orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
  }

  Point p((t_p1p0.x + factor_ra * orth_p1p0.x), (t_p1p0.y + factor_ra * orth_p1p0.y));

  orth_p1p0 = Point(-orth_p1p0.x, -orth_p1p0.y);
  double sa = acos(orth_p1p0.x / orth_p1p0_length);
  if (orth_p1p0.y < 0.f) {
    sa = 2 * M_PI - sa;
  }

  bool anticlockwise = false;

  double factor_p1p2 = tangent / p1p2_length;
  Point t_p1p2((p1.x + factor_p1p2 * p1p2.x), (p1.y + factor_p1p2 * p1p2.y));
  Point orth_p1p2((t_p1p2.x - p.x),(t_p1p2.y - p.y));
  double orth_p1p2_length = sqrt(orth_p1p2.x * orth_p1p2.x + orth_p1p2.y * orth_p1p2.y);
  double ea = acos(orth_p1p2.x / orth_p1p2_length);

  if (orth_p1p2.y < 0) ea = 2 * M_PI - ea;
  if ((sa > ea) && ((sa - ea) < M_PI)) anticlockwise = true;
  if ((sa < ea) && ((ea - sa) > M_PI)) anticlockwise = true;

  cerr << "ARC " << int(t_p1p0.x) << " " << int(t_p1p0.y) << " " << int(p.x) << " " << int(p.y) << " " << radius << " " << int(sa * 180.0 / M_PI) << " " << int(ea * 180.0 / M_PI) << " " << (anticlockwise ? "acw" : "cw") << endl;

  // lineTo(t_p1p0.x, t_p1p0.y);
  arc(p.x, p.y, radius, sa, ea, anticlockwise); // && M_PI * 2 != radius);
#endif
}
<|endoftext|>


<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.60
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 "Rotation.h"
#include "Translate.h"
#include "VolumeTransfer.h"
#include "MoleculeTransfer.h"
#include "IntraSwap.h"
#include "MultiParticle.h"
#include "Regrowth.h"
#include "MoleculeExchange1.h"
#include "MoleculeExchange2.h"
#include "MoleculeExchange3.h"
#include "IntraMoleculeExchange1.h"
#include "IntraMoleculeExchange2.h"
#include "IntraMoleculeExchange3.h"
#include "CrankShaft.h"
#include "CFCMC.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), checkpointSet(*this, statics)
{
  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];
  delete moves[mv::INTRA_MEMC];
  delete moves[mv::CRANKSHAFT];
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
  delete moves[mv::VOL_TRANSFER];
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
  delete moves[mv::MOL_TRANSFER];
  delete moves[mv::MEMC];
  delete moves[mv::CFCMC];
#endif
}

void System::Init(Setup const& set, ulong & startStep)
{
  prng.Init(set.prng.prngMaker.prng);
#ifdef VARIABLE_VOLUME
  boxDimensions->Init(set.config.in.restart,
                      set.config.sys.volume, set.pdb.cryst,
                      statV.forcefield);
#endif
#ifdef VARIABLE_PARTICLE_NUMBER
  molLookup.Init(statV.mol, set.pdb.atoms);
#endif
  moveSettings.Init(statV, set.pdb.remarks, molLookupRef.GetNumKind());
  //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);

  // At this point see if checkpoint is enabled. if so re-initialize
  // coordinates, prng, mollookup, step, boxdim, and movesettings
  if(set.config.in.restart.restartFromCheckpoint) {
    checkpointSet.ReadAll();
    checkpointSet.SetStepNumber(startStep);
    checkpointSet.SetBoxDimensions(boxDimRef);
    checkpointSet.SetPRNGVariables(prng);
    checkpointSet.SetCoordinates(coordinates);
    checkpointSet.SetMoleculeLookup(molLookupRef);
    checkpointSet.SetMoveSettings(moveSettings);
  }

  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();
  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

  //Initial the lambda before calling SystemTotal
  InitLambda();
  calcEnergy.Init(*this);
  calcEwald->Init();
  potential = calcEnergy.SystemTotal();
  InitMoves(set);
  for(uint m = 0; m < mv::MOVE_KINDS_TOTAL; m++)
    moveTime[m] = 0.0;
}

void System::InitMoves(Setup const& set)
{
  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);
  moves[mv::CRANKSHAFT] = new CrankShaft(*this, statV);
  if(set.config.sys.intraMemcVal.MEMC1) {
    moves[mv::INTRA_MEMC] = new IntraMoleculeExchange1(*this, statV);
  } else if (set.config.sys.intraMemcVal.MEMC2) {
    moves[mv::INTRA_MEMC] = new IntraMoleculeExchange2(*this, statV);
  } else {
    moves[mv::INTRA_MEMC] = new IntraMoleculeExchange3(*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);
  if(set.config.sys.memcVal.MEMC1) {
    moves[mv::MEMC] = new MoleculeExchange1(*this, statV);
  } else if (set.config.sys.memcVal.MEMC2) {
    moves[mv::MEMC] = new MoleculeExchange2(*this, statV);
  } else {
    moves[mv::MEMC] = new MoleculeExchange3(*this, statV);
  }
  moves[mv::CFCMC] = new CFCMC(*this, statV);
#endif
}

void System::InitLambda()
{
#ifdef GOMC_CUDA
  int temp_molIndex[BOX_TOTAL], temp_kindIndex[BOX_TOTAL];
  double temp_lambdaVDW[BOX_TOTAL], temp_lambdaCoulomb[BOX_TOTAL];
  bool temp_isFraction[BOX_TOTAL];
  for(int i = 0; i < BOX_TOTAL; i++) {
    temp_isFraction[i] = false;
  }
#endif
  if(statV.freeEnVal.enable) {
    bool found = false;
    for(uint k = 0; k < statV.mol.GetKindsCount(); k++) {
      std::string kindName = statV.mol.kinds[k].name;
      if(statV.freeEnVal.molType == kindName) {
        found = true;
        uint totalMol = molLookupRef.NumKindInBox(k, mv::BOX0);
        //In PDB file, molIndex start from 1.
        uint FEmolIndex = statV.freeEnVal.molIndex - 1;
        if(totalMol == 0) {
          found = false;
        } else if(totalMol <= FEmolIndex) {
          std::cout << "Error: Molecule index " << statV.freeEnVal.molIndex <<
                    " of kind " << kindName << " does not exist in the simulation box!\n";
          exit(EXIT_FAILURE);
        } else {
          uint m = molLookupRef.GetMolNum(FEmolIndex, k, mv::BOX0);
          uint state = statV.freeEnVal.iState;
          double lambdaCoulomb = statV.freeEnVal.lambdaCoulomb[state];
          double lambdaVDW = statV.freeEnVal.lambdaVDW[state];
          lambdaRef.Set(lambdaVDW, lambdaCoulomb, m, k, mv::BOX0);

#ifdef GOMC_CUDA
          // initialize arrays to copy to GPU
          temp_molIndex[mv::BOX0] = m;
          temp_kindIndex[mv::BOX0] = k;
          temp_lambdaVDW[mv::BOX0] = lambdaVDW;
          temp_lambdaCoulomb[mv::BOX0] = lambdaCoulomb;
          temp_isFraction[mv::BOX0] = true;
#endif
        }
        break;
      }
    }

    if(!found) {
      std::cout << "Error: No molecule of kind " << statV.freeEnVal.molType <<
                " in the simulation box! \n";
      exit(EXIT_FAILURE);
    }
  }
#ifdef GOMC_CUDA
  InitGPULambda(statV.forcefield.particles->getCUDAVars(), temp_molIndex,
                temp_kindIndex, temp_lambdaVDW, temp_lambdaCoulomb,
                temp_isFraction);
#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::PrintAcceptance()
{
  std::cout << std::endl;
  printf("%-24s %-15s", "Move Type", "Mol. Kind");
  for(uint b = 0; b < BOX_TOTAL; b++) {
    sstrm::Converter toStr;
    std::string numStr = "";
    toStr << b;
    toStr >> numStr;
    numStr = "BOX_" + numStr;
    printf("%-11s", numStr.c_str());
  }
  std::cout << std::endl;

  for(uint m = 0; m < mv::MOVE_KINDS_TOTAL; m++) {
    if(statV.movePerc[m] > 0.0)
      moves[m]->PrintAcceptKind();
  }
  std::cout << std::endl;
}

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

#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
  printf("%-36s %10.4f    sec.\n", "Mol-Transfer:",
         moveTime[mv::MOL_TRANSFER]);
  printf("%-36s %10.4f    sec.\n", "MEMC:", moveTime[mv::MEMC]);
  printf("%-36s %10.4f    sec.\n", "CFCMC:", moveTime[mv::CFCMC]);
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
  printf("%-36s %10.4f    sec.\n", "Vol-Transfer:", moveTime[mv::VOL_TRANSFER]);
#endif
  std::cout << std::endl;
}
<commit_msg>delete mp move in system destructor<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.60
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 "Rotation.h"
#include "Translate.h"
#include "VolumeTransfer.h"
#include "MoleculeTransfer.h"
#include "IntraSwap.h"
#include "MultiParticle.h"
#include "Regrowth.h"
#include "MoleculeExchange1.h"
#include "MoleculeExchange2.h"
#include "MoleculeExchange3.h"
#include "IntraMoleculeExchange1.h"
#include "IntraMoleculeExchange2.h"
#include "IntraMoleculeExchange3.h"
#include "CrankShaft.h"
#include "CFCMC.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), checkpointSet(*this, statics)
{
  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];
  delete moves[mv::INTRA_MEMC];
  delete moves[mv::CRANKSHAFT];
  delete moves[mv::MULTIPARTICLE];
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
  delete moves[mv::VOL_TRANSFER];
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
  delete moves[mv::MOL_TRANSFER];
  delete moves[mv::MEMC];
  delete moves[mv::CFCMC];
#endif
}

void System::Init(Setup const& set, ulong & startStep)
{
  prng.Init(set.prng.prngMaker.prng);
#ifdef VARIABLE_VOLUME
  boxDimensions->Init(set.config.in.restart,
                      set.config.sys.volume, set.pdb.cryst,
                      statV.forcefield);
#endif
#ifdef VARIABLE_PARTICLE_NUMBER
  molLookup.Init(statV.mol, set.pdb.atoms);
#endif
  moveSettings.Init(statV, set.pdb.remarks, molLookupRef.GetNumKind());
  //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);

  // At this point see if checkpoint is enabled. if so re-initialize
  // coordinates, prng, mollookup, step, boxdim, and movesettings
  if(set.config.in.restart.restartFromCheckpoint) {
    checkpointSet.ReadAll();
    checkpointSet.SetStepNumber(startStep);
    checkpointSet.SetBoxDimensions(boxDimRef);
    checkpointSet.SetPRNGVariables(prng);
    checkpointSet.SetCoordinates(coordinates);
    checkpointSet.SetMoleculeLookup(molLookupRef);
    checkpointSet.SetMoveSettings(moveSettings);
  }

  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();
  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

  //Initial the lambda before calling SystemTotal
  InitLambda();
  calcEnergy.Init(*this);
  calcEwald->Init();
  potential = calcEnergy.SystemTotal();
  InitMoves(set);
  for(uint m = 0; m < mv::MOVE_KINDS_TOTAL; m++)
    moveTime[m] = 0.0;
}

void System::InitMoves(Setup const& set)
{
  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);
  moves[mv::CRANKSHAFT] = new CrankShaft(*this, statV);
  if(set.config.sys.intraMemcVal.MEMC1) {
    moves[mv::INTRA_MEMC] = new IntraMoleculeExchange1(*this, statV);
  } else if (set.config.sys.intraMemcVal.MEMC2) {
    moves[mv::INTRA_MEMC] = new IntraMoleculeExchange2(*this, statV);
  } else {
    moves[mv::INTRA_MEMC] = new IntraMoleculeExchange3(*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);
  if(set.config.sys.memcVal.MEMC1) {
    moves[mv::MEMC] = new MoleculeExchange1(*this, statV);
  } else if (set.config.sys.memcVal.MEMC2) {
    moves[mv::MEMC] = new MoleculeExchange2(*this, statV);
  } else {
    moves[mv::MEMC] = new MoleculeExchange3(*this, statV);
  }
  moves[mv::CFCMC] = new CFCMC(*this, statV);
#endif
}

void System::InitLambda()
{
#ifdef GOMC_CUDA
  int temp_molIndex[BOX_TOTAL], temp_kindIndex[BOX_TOTAL];
  double temp_lambdaVDW[BOX_TOTAL], temp_lambdaCoulomb[BOX_TOTAL];
  bool temp_isFraction[BOX_TOTAL];
  for(int i = 0; i < BOX_TOTAL; i++) {
    temp_isFraction[i] = false;
  }
#endif
  if(statV.freeEnVal.enable) {
    bool found = false;
    for(uint k = 0; k < statV.mol.GetKindsCount(); k++) {
      std::string kindName = statV.mol.kinds[k].name;
      if(statV.freeEnVal.molType == kindName) {
        found = true;
        uint totalMol = molLookupRef.NumKindInBox(k, mv::BOX0);
        //In PDB file, molIndex start from 1.
        uint FEmolIndex = statV.freeEnVal.molIndex - 1;
        if(totalMol == 0) {
          found = false;
        } else if(totalMol <= FEmolIndex) {
          std::cout << "Error: Molecule index " << statV.freeEnVal.molIndex <<
                    " of kind " << kindName << " does not exist in the simulation box!\n";
          exit(EXIT_FAILURE);
        } else {
          uint m = molLookupRef.GetMolNum(FEmolIndex, k, mv::BOX0);
          uint state = statV.freeEnVal.iState;
          double lambdaCoulomb = statV.freeEnVal.lambdaCoulomb[state];
          double lambdaVDW = statV.freeEnVal.lambdaVDW[state];
          lambdaRef.Set(lambdaVDW, lambdaCoulomb, m, k, mv::BOX0);

#ifdef GOMC_CUDA
          // initialize arrays to copy to GPU
          temp_molIndex[mv::BOX0] = m;
          temp_kindIndex[mv::BOX0] = k;
          temp_lambdaVDW[mv::BOX0] = lambdaVDW;
          temp_lambdaCoulomb[mv::BOX0] = lambdaCoulomb;
          temp_isFraction[mv::BOX0] = true;
#endif
        }
        break;
      }
    }

    if(!found) {
      std::cout << "Error: No molecule of kind " << statV.freeEnVal.molType <<
                " in the simulation box! \n";
      exit(EXIT_FAILURE);
    }
  }
#ifdef GOMC_CUDA
  InitGPULambda(statV.forcefield.particles->getCUDAVars(), temp_molIndex,
                temp_kindIndex, temp_lambdaVDW, temp_lambdaCoulomb,
                temp_isFraction);
#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::PrintAcceptance()
{
  std::cout << std::endl;
  printf("%-24s %-15s", "Move Type", "Mol. Kind");
  for(uint b = 0; b < BOX_TOTAL; b++) {
    sstrm::Converter toStr;
    std::string numStr = "";
    toStr << b;
    toStr >> numStr;
    numStr = "BOX_" + numStr;
    printf("%-11s", numStr.c_str());
  }
  std::cout << std::endl;

  for(uint m = 0; m < mv::MOVE_KINDS_TOTAL; m++) {
    if(statV.movePerc[m] > 0.0)
      moves[m]->PrintAcceptKind();
  }
  std::cout << std::endl;
}

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

#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
  printf("%-36s %10.4f    sec.\n", "Mol-Transfer:",
         moveTime[mv::MOL_TRANSFER]);
  printf("%-36s %10.4f    sec.\n", "MEMC:", moveTime[mv::MEMC]);
  printf("%-36s %10.4f    sec.\n", "CFCMC:", moveTime[mv::CFCMC]);
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
  printf("%-36s %10.4f    sec.\n", "Vol-Transfer:", moveTime[mv::VOL_TRANSFER]);
#endif
  std::cout << std::endl;
}
<|endoftext|>


<commit_before>/* LogPrintf.cpp	Tue Nov  1 2016 12:55:06 tmm */

/*

Module:  LogPrintf.cpp

Function:
	Arduino_LoRaWAN::LogPrintf()

Version:
	V0.2.0	Tue Nov  1 2016 12:55:06 tmm	Edit level 1

Copyright notice:
	This file copyright (C) 2016 by

		MCCI Corporation
		3520 Krums Corners Road
		Ithaca, NY  14850

	An unpublished work.  All rights reserved.

	This file is proprietary information, and may not be disclosed or
	copied without the prior permission of MCCI Corporation.

Author:
	Terry Moore, MCCI Corporation	November 2016

Revision history:
   0.2.0  Tue Nov  1 2016 12:55:06  tmm
	Module created.

*/

#include <Arduino_LoRaWAN.h>

#include <Arduino.h>
#include <stdio.h>
#include <stdarg.h>

void
Arduino_LoRaWAN::LogPrintf(
	const char *fmt,
	...
	)
	{
	if (! Serial)
		return;

	char buf[128];
	va_list ap;

	va_start(ap, fmt);
	(void) vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
	va_end(ap);

	// in case we overflowed:
	buf[sizeof(buf) - 1] = '\0';
	if (Serial) Serial.print(buf);
	}
<commit_msg>Don't use bool(Serial) -- implementation inserts 10ms delay<commit_after>/* LogPrintf.cpp	Tue Nov  1 2016 12:55:06 tmm */

/*

Module:  LogPrintf.cpp

Function:
	Arduino_LoRaWAN::LogPrintf()

Version:
	V0.2.0	Tue Nov  1 2016 12:55:06 tmm	Edit level 1

Copyright notice:
	This file copyright (C) 2016 by

		MCCI Corporation
		3520 Krums Corners Road
		Ithaca, NY  14850

	An unpublished work.  All rights reserved.

	This file is proprietary information, and may not be disclosed or
	copied without the prior permission of MCCI Corporation.

Author:
	Terry Moore, MCCI Corporation	November 2016

Revision history:
   0.2.0  Tue Nov  1 2016 12:55:06  tmm
	Module created.

*/

#include <Arduino_LoRaWAN.h>

#include <Arduino.h>
#include <stdio.h>
#include <stdarg.h>

void
Arduino_LoRaWAN::LogPrintf(
	const char *fmt,
	...
	)
	{
	if (! Serial.dtr())
		return;

	char buf[128];
	va_list ap;

	va_start(ap, fmt);
	(void) vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
	va_end(ap);

	// in case we overflowed:
	buf[sizeof(buf) - 1] = '\0';
	if (Serial.dtr()) Serial.print(buf);
	}
<|endoftext|>


<commit_before>#include "Widget.hpp"

#include <cassert>
#include <cmath>

static const int TEXTURE_WIDTH = 90;
static const int TEXTURE_HEIGHT = 90;

Widget::Widget(SDL_Renderer *renderer)
   : mXPos(0),
   mXVelocity(0),
   mYPos(0),
   mYVelocity(0),
   mAngle(0),
   mAngleMomentum(0),
   mWindowWidth(640),
   mWindowHeight(480),
   mTexture(SDL_CreateTexture(renderer,
                              SDL_PIXELFORMAT_RGBA8888,
                              SDL_TEXTUREACCESS_TARGET,
                              TEXTURE_WIDTH,
                              TEXTURE_HEIGHT))
{
   assert(nullptr != mTexture);
   SDL_SetRenderTarget(renderer, mTexture);

   SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
   SDL_RenderClear(renderer);
   SDL_Rect fill_rect = {
      (TEXTURE_WIDTH * 1) / 3,
      (TEXTURE_HEIGHT * 0) / 3,
      (TEXTURE_WIDTH * 1) / 3,
      (TEXTURE_HEIGHT * 2) / 3
   };
   SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
   SDL_RenderFillRect(renderer, &fill_rect);
   fill_rect.x = (TEXTURE_WIDTH * 0) / 3;
   fill_rect.y = (TEXTURE_HEIGHT * 2) / 3;
   fill_rect.h = (TEXTURE_HEIGHT * 1) / 3;
   SDL_RenderFillRect(renderer, &fill_rect);
   fill_rect.x = (TEXTURE_WIDTH * 2) / 3;
   SDL_RenderFillRect(renderer, &fill_rect);
}

void Widget::Render(SDL_Renderer *renderer) {
   // Update position
   mAngle += mAngleMomentum;
   mXPos += mXVelocity;
   mYPos += mYVelocity;
   if (mXPos > mWindowWidth / 2)
      mXPos -= mWindowWidth;
   else if (mXPos < mWindowWidth / -2)
      mXPos += mWindowWidth;
   if (mYPos > mWindowHeight / 2)
      mYPos -= mWindowHeight;
   else if (mYPos < mWindowHeight / -2)
      mYPos += mWindowHeight;

   SDL_Rect destination = {
      static_cast<int>(mXPos), // x
      static_cast<int>(mYPos), // y
      TEXTURE_WIDTH, // w
      TEXTURE_HEIGHT // h
   };

   SDL_RenderCopyEx(renderer, mTexture, nullptr, &destination, mAngle, nullptr, SDL_FLIP_NONE);
   destination.x += mWindowWidth;
   SDL_RenderCopyEx(renderer, mTexture, nullptr, &destination, mAngle, nullptr, SDL_FLIP_NONE);
   destination.y += mWindowHeight;
   SDL_RenderCopyEx(renderer, mTexture, nullptr, &destination, mAngle, nullptr, SDL_FLIP_NONE);
   destination.x -= mWindowWidth;
   SDL_RenderCopyEx(renderer, mTexture, nullptr, &destination, mAngle, nullptr, SDL_FLIP_NONE);
}

void Widget::HandleKeyboardEvent(SDL_Keycode key) {
   switch (key) {
      case SDLK_SPACE:
         mXPos = 0;
         mYPos = 0;
         break;
      case SDLK_UP:
         mXVelocity += std::sin(mAngle * M_PI / 180.0) * 1;
         mYVelocity -= std::cos(mAngle * M_PI / 180.0) * 1;
         break;
      case SDLK_DOWN:
         // TODO: Figure out what ownship should do when down is pressed
         break;
      case SDLK_LEFT:
         mAngleMomentum -= 1;
         break;
      case SDLK_RIGHT:
         mAngleMomentum += 1;
         break;
      default:
         break;
   }
}

void Widget::MoveForward(void) {
   mXPos += std::sin(mAngle * M_PI / 180.0) * 10;
   mYPos += std::cos(mAngle * M_PI / 180.0) * 10;
}
<commit_msg>Made ownship less phallic<commit_after>#include "Widget.hpp"

#include <cassert>
#include <cmath>

static const int TEXTURE_WIDTH = 90;
static const int TEXTURE_HEIGHT = 90;

Widget::Widget(SDL_Renderer *renderer)
   : mXPos(0),
   mXVelocity(0),
   mYPos(0),
   mYVelocity(0),
   mAngle(0),
   mAngleMomentum(0),
   mWindowWidth(640),
   mWindowHeight(480),
   mTexture(SDL_CreateTexture(renderer,
                              SDL_PIXELFORMAT_RGBA8888,
                              SDL_TEXTUREACCESS_TARGET,
                              TEXTURE_WIDTH,
                              TEXTURE_HEIGHT))
{
   assert(nullptr != mTexture);
   SDL_SetRenderTarget(renderer, mTexture);

   SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
   SDL_RenderClear(renderer);
   SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
   SDL_RenderDrawLine(renderer, TEXTURE_WIDTH / 2, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT);
   SDL_RenderDrawLine(renderer, TEXTURE_WIDTH / 2, 0, 0, TEXTURE_HEIGHT);
   SDL_RenderDrawLine(renderer, TEXTURE_WIDTH / 2, TEXTURE_HEIGHT * 2 / 3, TEXTURE_WIDTH, TEXTURE_HEIGHT);
   SDL_RenderDrawLine(renderer, TEXTURE_WIDTH / 2, TEXTURE_HEIGHT * 2 / 3, 0, TEXTURE_HEIGHT);
}

void Widget::Render(SDL_Renderer *renderer) {
   // Update position
   mAngle += mAngleMomentum;
   mXPos += mXVelocity;
   mYPos += mYVelocity;
   if (mXPos > mWindowWidth / 2)
      mXPos -= mWindowWidth;
   else if (mXPos < mWindowWidth / -2)
      mXPos += mWindowWidth;
   if (mYPos > mWindowHeight / 2)
      mYPos -= mWindowHeight;
   else if (mYPos < mWindowHeight / -2)
      mYPos += mWindowHeight;

   SDL_Rect destination = {
      static_cast<int>(mXPos), // x
      static_cast<int>(mYPos), // y
      TEXTURE_WIDTH, // w
      TEXTURE_HEIGHT // h
   };

   SDL_RenderCopyEx(renderer, mTexture, nullptr, &destination, mAngle, nullptr, SDL_FLIP_NONE);
   destination.x += mWindowWidth;
   SDL_RenderCopyEx(renderer, mTexture, nullptr, &destination, mAngle, nullptr, SDL_FLIP_NONE);
   destination.y += mWindowHeight;
   SDL_RenderCopyEx(renderer, mTexture, nullptr, &destination, mAngle, nullptr, SDL_FLIP_NONE);
   destination.x -= mWindowWidth;
   SDL_RenderCopyEx(renderer, mTexture, nullptr, &destination, mAngle, nullptr, SDL_FLIP_NONE);
}

void Widget::HandleKeyboardEvent(SDL_Keycode key) {
   switch (key) {
      case SDLK_SPACE:
         mXPos = 0;
         mYPos = 0;
         break;
      case SDLK_UP:
         mXVelocity += std::sin(mAngle * M_PI / 180.0) * 1;
         mYVelocity -= std::cos(mAngle * M_PI / 180.0) * 1;
         break;
      case SDLK_DOWN:
         // TODO: Figure out what ownship should do when down is pressed
         break;
      case SDLK_LEFT:
         mAngleMomentum -= 1;
         break;
      case SDLK_RIGHT:
         mAngleMomentum += 1;
         break;
      default:
         break;
   }
}

void Widget::MoveForward(void) {
   mXPos += std::sin(mAngle * M_PI / 180.0) * 10;
   mYPos += std::cos(mAngle * M_PI / 180.0) * 10;
}
<|endoftext|>


<commit_before>#include "Window.h"
#include "Logger.h"
#include "Configuration.h"

#include <iostream>

SDL_Renderer* Window::sdlRenderer = nullptr;

Window::Window(const unsigned int width_, const unsigned int height_, const std::string& title_) :
	windowTitle(title_),
	sdlWindow(nullptr)
{
	create(width_, height_);
}

Window::~Window(){
	destroy();
}

void Window::destroy(){
	// Destroys the Window renderer.
	SDL_DestroyRenderer(Window::sdlRenderer);
	Window::sdlRenderer = nullptr;

	// Destroys the Window window.
	SDL_DestroyWindow(this->sdlWindow);
	this->sdlWindow = nullptr;
}

void Window::minimize(){
	SDL_MinimizeWindow(this->sdlWindow);
}

void Window::maximize(){
	SDL_MaximizeWindow(this->sdlWindow);
}

void Window::clear(){
	SDL_SetRenderDrawColor(Window::sdlRenderer, 0x00, 0x00, 0x00, 0xFF);
	SDL_RenderClear(Window::sdlRenderer);
}

void Window::render(){
	SDL_RenderPresent(Window::sdlRenderer);
}

void Window::create(const unsigned int width_, const unsigned int height_){
	/// @todo Toggle VSync.

	// Creates the SDL window.
	const Uint32 windowFlags = SDL_WINDOW_SHOWN;
	this->sdlWindow = SDL_CreateWindow(
		this->windowTitle.c_str(),
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
		width_, height_,
		windowFlags
	);

	if(this->sdlWindow != nullptr){

		// Creates the SDL renderer.
		Window::sdlRenderer = SDL_CreateRenderer(this->sdlWindow, -1, SDL_RENDERER_ACCELERATED);
		if(Window::sdlRenderer != nullptr){

			// Set texture filtering to linear.
			SDL_bool linearFilter = SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest");

			if(linearFilter){
				Log(INFO) << "Linear texture filtering enabled!";
				rescale(Configuration::getLogicalRenderSize());
			}

			else{
				Log(WARN) << "Linear texture filtering disabled!";
			}

			Log(DEBUG) << "Game successfully loaded.";

		}
		else{
			Log(ERROR) << "Renderer could not be created. " << SDL_GetError();
		}
	}
	else{
		Log(ERROR) << "Window failed to be created. " << SDL_GetError();
	}
}

void Window::resize(const unsigned int width_, const unsigned int height_){
	SDL_SetWindowSize(this->sdlWindow, width_, height_);
}

void Window::rescale(unsigned int size_){
	// Just a precaution, so there is no abuse on the size.
	if(size_ > 10){
		size_ = 10;
		Log(WARN) << "Trying to rescale for a value too big.";
	}

	SDL_RenderSetLogicalSize(
		Window::sdlRenderer,
		Configuration::getResolutionWidth() * size_,
		Configuration::getResolutionHeight() * size_
	);
}

SDL_Renderer* Window::getRenderer(){
	return Window::sdlRenderer;
}

void Window::getLogicalSize(int* w, int* h){
	SDL_RenderGetLogicalSize(Window::getRenderer(), w, h);
}
<commit_msg>Commenting methods on the window Class<commit_after>#include "Window.h"
#include "Logger.h"
#include "Configuration.h"

#include <iostream>

SDL_Renderer* Window::sdlRenderer = nullptr;

// Constructor of window class, creates a window.
Window::Window(const unsigned int width_, const unsigned int height_, const std::string& title_) :
	windowTitle(title_),
	sdlWindow(nullptr)
{
	create(width_, height_);
}

// Destructor method, runs when the class is deallocated.
Window::~Window(){
	destroy();
}

// Deallocate all resourses used in this class.
void Window::destroy(){
	// Destroys the Window renderer.
	SDL_DestroyRenderer(Window::sdlRenderer);
	Window::sdlRenderer = nullptr;

	// Destroys the Window window.
	SDL_DestroyWindow(this->sdlWindow);
	this->sdlWindow = nullptr;
}

// Method that minimizes the window.
void Window::minimize(){
	SDL_MinimizeWindow(this->sdlWindow);
}

// Method that maximizes the window.
void Window::maximize(){
	SDL_MaximizeWindow(this->sdlWindow);
}

// Draw a white rect filling the whole screen, used for clean.
void Window::clear(){
	SDL_SetRenderDrawColor(Window::sdlRenderer, 0x00, 0x00, 0x00, 0xFF);
	SDL_RenderClear(Window::sdlRenderer);
}

// Render the window
void Window::render(){
	SDL_RenderPresent(Window::sdlRenderer);
}

// Creates the SDL window, with the width and height.
void Window::create(const unsigned int width_, const unsigned int height_){
	/// @todo Toggle VSync.

	const Uint32 windowFlags = SDL_WINDOW_SHOWN;
	this->sdlWindow = SDL_CreateWindow(
		this->windowTitle.c_str(),
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
		width_, height_,
		windowFlags
	);

	if(this->sdlWindow != nullptr){

		// Creates the SDL renderer.
		Window::sdlRenderer = SDL_CreateRenderer(this->sdlWindow, -1, SDL_RENDERER_ACCELERATED);
		if(Window::sdlRenderer != nullptr){

			// Set texture filtering to linear.
			SDL_bool linearFilter = SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest");

			if(linearFilter){
				Log(INFO) << "Linear texture filtering enabled!";
				rescale(Configuration::getLogicalRenderSize());
			}

			else{
				Log(WARN) << "Linear texture filtering disabled!";
			}

			Log(DEBUG) << "Game successfully loaded.";

		}
		else{
			Log(ERROR) << "Renderer could not be created. " << SDL_GetError();
		}
	}
	else{
		Log(ERROR) << "Window failed to be created. " << SDL_GetError();
	}
}

// Resize the window with a new width and height.
void Window::resize(const unsigned int width_, const unsigned int height_){
	SDL_SetWindowSize(this->sdlWindow, width_, height_);
}

// Apply a scale on the screen.
void Window::rescale(unsigned int size_){
	// Just a precaution, so there is no abuse on the size.
	if(size_ > 10){
		size_ = 10;
		Log(WARN) << "Trying to rescale for a value too big.";
	}

	SDL_RenderSetLogicalSize(
		Window::sdlRenderer,
		Configuration::getResolutionWidth() * size_,
		Configuration::getResolutionHeight() * size_
	);
}

SDL_Renderer* Window::getRenderer(){
	return Window::sdlRenderer;
}

void Window::getLogicalSize(int* w, int* h){
	SDL_RenderGetLogicalSize(Window::getRenderer(), w, h);
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "MediaLibrary.h"

extern "C" medialibrary::IMediaLibrary* NewMediaLibrary()
{
    return new medialibrary::MediaLibrary();
}
<commit_msg>ml factory: Ensure no exception is thrown<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "MediaLibrary.h"

extern "C" medialibrary::IMediaLibrary* NewMediaLibrary()
{
    try
    {
        return new medialibrary::MediaLibrary();
    }
    catch ( const std::exception& ex )
    {
        LOG_ERROR( "Failed to instantiate medialibrary: ", ex.what() );
    }
    return nullptr;
}
<|endoftext|>


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

#include "iceoryx_posh/roudi/roudi_app.hpp"

namespace iox
{
namespace roudi
{
class IceOryxRouDiApp : public RouDiApp
{
  public:
    /// @brief constructor to create the RouDi daemon with a given config
    /// @param[in] Command liner parser object, that provides the settings
    /// @param[in] RouDi config for mempool configuration
    IceOryxRouDiApp(const iox::config::CmdLineArgs_t& cmdLineArgs, const RouDiConfig_t& roudiConfig) noexcept;

    /// @brief starts the execution of the RouDi daemon
    /// @return Return code for programm execution
    uint8_t run() noexcept override;
};

} // namespace roudi
} // namespace iox

#endif // IOX_POSH_ROUDI_ICEORYX_ROUDI_APP_HPP
<commit_msg>iox-#404 Remove unecessary namespace<commit_after>// Copyright (c) 2019, 2020 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IOX_POSH_ROUDI_ICEORYX_ROUDI_APP_HPP
#define IOX_POSH_ROUDI_ICEORYX_ROUDI_APP_HPP

#include "iceoryx_posh/roudi/roudi_app.hpp"

namespace iox
{
namespace roudi
{
class IceOryxRouDiApp : public RouDiApp
{
  public:
    /// @brief constructor to create the RouDi daemon with a given config
    /// @param[in] Command liner parser object, that provides the settings
    /// @param[in] RouDi config for mempool configuration
    IceOryxRouDiApp(const config::CmdLineArgs_t& cmdLineArgs, const RouDiConfig_t& roudiConfig) noexcept;

    /// @brief starts the execution of the RouDi daemon
    /// @return Return code for programm execution
    uint8_t run() noexcept override;
};

} // namespace roudi
} // namespace iox

#endif // IOX_POSH_ROUDI_ICEORYX_ROUDI_APP_HPP
<|endoftext|>


<commit_before>#include "readfile.h"
#include <vector>

#ifndef _MAX_
#define MAX 256
#endif _MAX_

struct id
{
	id() {m = n = 0;}
	int m, n;
};

struct Point3d
{
	Point3d(){x = y = z = 0.0f;}
	float x, y, z;
	bool operator<(const Point3d& p2) const
	{
		if(x == p2.x)
		{
			if(y == p2.y)
			{
				return (z < p2.z);
			}
			else
				return (y < p2.y);
		}
		else
			return (x < p2.x);
	}
};

void ReadxyzFile(const char* Path)
{
	FILE *fp = fopen(Path, "r");
	if(fp == NULL)
	{
		printf("Cannot open point cloud file.\n");
		return;
	}

	//	ȡstd::vector
	const int BUFSIZE = 512;
	char buf[BUFSIZE];
	int rowNumber = 0;
	while(fgets(buf, BUFSIZE, fp) != NULL)	//	жȡ
	{
		++ rowNumber;
	}
	fclose(fp);
	fp = 0;

	//	´ļ
	fp = fopen(Path, "r");
	id pointID;
	Point3d pointXYZ;
	Point3d pointColor;

	std::vector<id> vecPtID;
	std::vector<Point3d> vecPtXYZ;		//
	std::vector<Point3d> vecPtColor;	//	ɫ

	vecPtID.reserve(rowNumber);
	vecPtXYZ.reserve(rowNumber);
	vecPtColor.reserve(rowNumber);

	while(fgets(buf, BUFSIZE, fp) != NULL)
	{
		sscanf(buf, "%d %d %lf %lf %lf %d %d %d",
			&(pointID.m),    &(pointID.n),
			&(pointXYZ.x),   &(pointXYZ.y),   &(pointXYZ.z),
			&(pointColor.x), &(pointColor.y), &(pointColor.z));

		vecPtID.push_back(pointID);
		vecPtXYZ.push_back(pointXYZ);
		vecPtColor.push_back(pointColor);
	}

	fclose(fp);
	fp = 0;

	double *M = new double[vecPtXYZ.size() * 3];
	for(int i=0; i<(int)vecPtXYZ.size(); i++)
	{
		M[i] = vecPtXYZ[i].x;
		M[i+1] = vecPtXYZ[i].y;
		M[i+2] = vecPtXYZ[i].z;
	}
	char sPath[MAX];
	getcwd(sPath, MAX_PATH);

	strcat(sPath, "\\ȡ.txt");
	WriteFile(sPath, M, rowNumber, 3);
}

double* ReadFile(const char* strPath, std::vector<int>& DataFile)
	// Read file data one by one
{
	/*
	std::ifstream fin(strPath);
	std::vector<double> vec;
	while(fin)
	{
		double idata;
		fin >> idata;
		vec.push_back(idata);	//	can't read?
	}	*/
	FILE *fp;
	fp = fopen(strPath, "r");
	std::vector<double> vec;
	int num = 0, dim = 3;
	double idata1, idata2, idata3;
	while(!feof(fp))
	{
		fscanf(fp, "%lf,%lf,%lf", &idata1,&idata2,&idata3);
		vec.push_back(idata1);
		vec.push_back(idata2);
		vec.push_back(idata3);
		num++;
	}
	DataFile[0] = num;
	DataFile[1] = dim;
	DataFile[2] = idata1;
	DataFile[3] = idata2;
	double *M = new double[(int)vec.size()];
	for(int i=0; i<(int)vec.size(); i++)
		M[i]=vec[i];
	vec.clear();
	//num=(int)vec.size()/3;		//	icp need it!
	fclose(fp);
	return M;
}

void WriteFile(char* strPath, double* M, int32_t num, int32_t dim)
{
	FILE *fp;
	fp = fopen(strPath, "w");
	for(int i=0; i<num*dim; i+=dim)
	{
		if(i<(num-1)*dim)
			fprintf(fp, "%lf,%lf,%lf\n", M[i], M[i+1], M[i+2]);
		else
			fprintf(fp, "%lf,%lf,%lf", M[i], M[i+1], M[i+2]);
	}
	fclose(fp);
}<commit_msg>readfile修改<commit_after>#include "readfile.h"
#include <vector>
#include <algorithm>

#ifndef _MAX_
#define MAX 256
#endif _MAX_

struct id
{
	id() {m = n = 0;}
	int m, n;
};

struct Point3d
{
	Point3d(){x = y = z = 0.0f;}
	float x, y, z;
	bool operator<(const Point3d& p2) const
	{
		if(x == p2.x)
		{
			if(y == p2.y)
			{
				return (z < p2.z);
			}
			else
				return (y < p2.y);
		}
		else
			return (x < p2.x);
	}
};

int cmp(Point3d p1, Point3d p2)
{
	return p1 < p2;
}

void ReadxyzFile(const char* Path)
	//	ȡ.xyzļ
{
	FILE *fp = fopen(Path, "r");
	if(fp == NULL)
	{
		printf("Cannot open point cloud file.\n");
		return;
	}

	//	ȡstd::vector
	const int BUFSIZE = 512;
	char buf[BUFSIZE];
	int rowNumber = 0;
	while(fgets(buf, BUFSIZE, fp) != NULL)	//	жȡ
	{
		++ rowNumber;
	}
	fclose(fp);
	fp = 0;

	//	´ļ
	fp = fopen(Path, "r");
	id pointID;
	Point3d pointXYZ;
	Point3d pointColor;

	std::vector<id> vecPtID;
	std::vector<Point3d> vecPtXYZ;		//
	std::vector<Point3d> vecPtColor;	//	ɫ

	vecPtID.reserve(rowNumber);
	vecPtXYZ.reserve(rowNumber);
	vecPtColor.reserve(rowNumber);

	//	ݶȡ
	while(fgets(buf, BUFSIZE, fp) != NULL)
	{
		sscanf(buf, "%f %f %f %f %f %f %f %f",
			&(pointID.m),    &(pointID.n),
			&(pointXYZ.x),   &(pointXYZ.y),   &(pointXYZ.z),
			&(pointColor.x), &(pointColor.y), &(pointColor.z));

		vecPtID.push_back(pointID);
		vecPtXYZ.push_back(pointXYZ);
		vecPtColor.push_back(pointColor);
	}

	fclose(fp);
	fp = 0;

	sort(vecPtXYZ.begin(), vecPtXYZ.end(), cmp);

	//
	double *M = new double[vecPtXYZ.size() * 3];
	for(int i=0; i<(int)vecPtXYZ.size(); i++)
	{
		M[i*3]   = vecPtXYZ[i].x;
		M[i*3+1] = vecPtXYZ[i].y;
		M[i*3+2] = vecPtXYZ[i].z;
	}
	char sPath[MAX];
	getcwd(sPath, MAX_PATH);

	strcat(sPath, "\\ȡ.txt");
	FILE *ifp = fopen(sPath, "w+");	//	дļķʽ򿪣ٹرռļ
	fclose(ifp);
	WriteFile(sPath, M, rowNumber, 3);
	delete [] M;
}

double* ReadFile(const char* strPath, std::vector<int>& DataFile)
	// Read file data one by one
{
	/*
	std::ifstream fin(strPath);
	std::vector<double> vec;
	while(fin)
	{
		double idata;
		fin >> idata;
		vec.push_back(idata);	//	can't read?
	}	*/
	FILE *fp;
	fp = fopen(strPath, "r");
	std::vector<double> vec;
	int num = 0, dim = 3;
	double idata1, idata2, idata3;
	while(!feof(fp))
	{
		fscanf(fp, "%lf,%lf,%lf", &idata1,&idata2,&idata3);
		vec.push_back(idata1);
		vec.push_back(idata2);
		vec.push_back(idata3);
		num++;
	}
	DataFile[0] = num;
	DataFile[1] = dim;
	DataFile[2] = idata1;
	DataFile[3] = idata2;
	double *M = new double[(int)vec.size()];
	for(int i=0; i<(int)vec.size(); i++)
		M[i]=vec[i];
	vec.clear();
	//num=(int)vec.size()/3;		//	icp need it!
	fclose(fp);
	return M;
}

void WriteFile(char* strPath, double* M, int32_t num, int32_t dim)
{
	FILE *fp;
	fp = fopen(strPath, "w");
	for(int i=0; i<num*dim; i+=dim)
	{
		if(i<(num-1)*dim)
			fprintf(fp, "%lf,%lf,%lf\n", M[i], M[i+1], M[i+2]);
		else
			fprintf(fp, "%lf,%lf,%lf", M[i], M[i+1], M[i+2]);
	}
	fclose(fp);
}<|endoftext|>


<commit_before>#ifndef __STAN__MCMC__BASE__HAMILTONIAN__BETA__
#define __STAN__MCMC__BASE__HAMILTONIAN__BETA__

#include <stdexcept>
#include <fstream>
#include <iostream>
#include <vector>

#include <stan/math/matrix/Eigen.hpp>
#include <stan/model/util.hpp>

namespace stan {

  namespace mcmc {

    template <typename M, typename P, typename BaseRNG>
    class base_hamiltonian {

    public:

      base_hamiltonian(M& m, std::ostream* e): _model(m), _err_stream(e) {};
      ~base_hamiltonian() {};

      virtual double T(P& z) = 0;
      double V(P& z) { return z.V; }

      virtual double tau(P& z) = 0;
      virtual double phi(P& z) = 0;

      double H(P& z) { return T(z) + V(z); }

      // tau = 0.5 p_{i} p_{j} Lambda^{ij} (q)
      virtual const Eigen::VectorXd dtau_dq(P& z) = 0;
      virtual const Eigen::VectorXd dtau_dp(P& z) = 0;

      // phi = 0.5 * log | Lambda (q) | + V(q)
      virtual const Eigen::VectorXd dphi_dq(P& z) = 0;

      virtual void sample_p(P& z, BaseRNG& rng) = 0;

      virtual void init(P& z) { this->update(z); }

      virtual void update(P& z) {

        try {
          stan::model::gradient(_model, z.q, z.V, z.g, _err_stream);
        } catch (const std::exception& e) {
          this->_write_error_msg(_err_stream, e);
          z.V = std::numeric_limits<double>::infinity();
        }

        z.V *= -1;
        z.g *= -1;

      }

    protected:

        M& _model;

        std::ostream* _err_stream;

        void _write_error_msg(std::ostream* error_msgs,
                             const std::exception& e) {

          if (!error_msgs) return;

          *error_msgs << std::endl
                      << "Informational Message: The current Metropolis proposal is about to be "
                      << "rejected becuase of the following issue:"
                      << std::endl
                      << e.what() << std::endl
                      << "If this warning occurs sporadically, such as for highly constrained "
                      << "variable types like covariance matrices, then the sampler is fine,"
                      << std::endl
                      << "but if this warning occurs often then your model may be either severely "
                      << "ill-conditioned or misspecified."
                      << std::endl;

      }

    };

  } // mcmc

} // stan

#endif
<commit_msg>fixes issue #543<commit_after>#ifndef __STAN__MCMC__BASE__HAMILTONIAN__BETA__
#define __STAN__MCMC__BASE__HAMILTONIAN__BETA__

#include <stdexcept>
#include <fstream>
#include <iostream>
#include <vector>

#include <stan/math/matrix/Eigen.hpp>
#include <stan/model/util.hpp>

namespace stan {

  namespace mcmc {

    template <typename M, typename P, typename BaseRNG>
    class base_hamiltonian {

    public:

      base_hamiltonian(M& m, std::ostream* e): _model(m), _err_stream(e) {};
      ~base_hamiltonian() {};

      virtual double T(P& z) = 0;
      double V(P& z) { return z.V; }

      virtual double tau(P& z) = 0;
      virtual double phi(P& z) = 0;

      double H(P& z) { return T(z) + V(z); }

      // tau = 0.5 p_{i} p_{j} Lambda^{ij} (q)
      virtual const Eigen::VectorXd dtau_dq(P& z) = 0;
      virtual const Eigen::VectorXd dtau_dp(P& z) = 0;

      // phi = 0.5 * log | Lambda (q) | + V(q)
      virtual const Eigen::VectorXd dphi_dq(P& z) = 0;

      virtual void sample_p(P& z, BaseRNG& rng) = 0;

      virtual void init(P& z) { this->update(z); }

      virtual void update(P& z) {

        try {
          stan::model::gradient(_model, z.q, z.V, z.g, _err_stream);
          z.V *= -1;
        } catch (const std::exception& e) {
          this->_write_error_msg(_err_stream, e);
          z.V = std::numeric_limits<double>::infinity();
        }

        z.g *= -1;

      }

    protected:

        M& _model;

        std::ostream* _err_stream;

        void _write_error_msg(std::ostream* error_msgs,
                             const std::exception& e) {

          if (!error_msgs) return;

          *error_msgs << std::endl
                      << "Informational Message: The current Metropolis proposal is about to be "
                      << "rejected becuase of the following issue:"
                      << std::endl
                      << e.what() << std::endl
                      << "If this warning occurs sporadically, such as for highly constrained "
                      << "variable types like covariance matrices, then the sampler is fine,"
                      << std::endl
                      << "but if this warning occurs often then your model may be either severely "
                      << "ill-conditioned or misspecified."
                      << std::endl;

      }

    };

  } // mcmc

} // stan

#endif
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "ValuePrinterSynthesizer.h"

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclGroup.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"

#include "llvm/Support/raw_os_ostream.h"

#include <iostream>

using namespace clang;

namespace cling {

  ValuePrinterSynthesizer::ValuePrinterSynthesizer(clang::Sema* S,
                                                   llvm::raw_ostream* Stream)
    : TransactionTransformer(S), m_Context(&S->getASTContext()) {
    if (Stream)
      m_ValuePrinterStream.reset(Stream);
    else
      m_ValuePrinterStream.reset(new llvm::raw_os_ostream(std::cout));
  }

  // pin the vtable here.
  ValuePrinterSynthesizer::~ValuePrinterSynthesizer()
  { }

  void ValuePrinterSynthesizer::Transform() {
    if (getTransaction()->getCompilationOpts().ValuePrinting
        == CompilationOptions::VPDisabled)
      return;

    if (!tryAttachVP(getTransaction()->getWrapperFD()))
      return setTransaction(0); // On error set to NULL.
  }

  bool ValuePrinterSynthesizer::tryAttachVP(FunctionDecl* FD) {
    // We have to be able to mark the expression for printout. There are
    // three scenarios:
    // 0: Expression printing disabled - don't do anything just exit.
    // 1: Expression printing enabled - print no matter what.
    // 2: Expression printing auto - analyze - rely on the omitted ';' to
    //    not produce the suppress marker.
    int indexOfLastExpr = -1;
    Expr* To = utils::Analyze::GetOrCreateLastExpr(FD, &indexOfLastExpr,
                                                   /*omitDS*/false,
                                                   m_Sema);
    if (To) {
      // Update the CompoundStmt body, avoiding alloc/dealloc of all the el.
      CompoundStmt* CS = cast<CompoundStmt>(FD->getBody());
      assert(CS && "Missing body?");

      const CompilationOptions& CO(getTransaction()->getCompilationOpts());
      switch (CO.ValuePrinting) {
      case CompilationOptions::VPDisabled:
        assert("Don't wait that long. Exit early!");
        break;
      case CompilationOptions::VPEnabled:
        break;
      case CompilationOptions::VPAuto:
        if ((int)CS->size() > indexOfLastExpr+1
            && (*(CS->body_begin() + indexOfLastExpr + 1))
            && isa<NullStmt>(*(CS->body_begin() + indexOfLastExpr + 1)))
          return true; // If next is NullStmt disable VP is disabled - exit.
        break;
      }

      // We can't PushDeclContext, because we don't have scope.
      Sema::ContextRAII pushedDC(*m_Sema, FD);

      if (To) {
        // Strip the parenthesis if any
        if (ParenExpr* PE = dyn_cast<ParenExpr>(To))
          To = PE->getSubExpr();

        Expr* Result = 0;
        if (m_Sema->getLangOpts().CPlusPlus)
          Result = SynthesizeCppVP(To);
        else
          Result = SynthesizeVP(To);

        if (Result)
          *(CS->body_begin()+indexOfLastExpr) = Result;
      }
      // Clear the artificial NullStmt-s
      if (!ClearNullStmts(CS)) {
        // FIXME: Why it is here? Shouldn't it be in DeclExtractor?
        // if no body remove the wrapper
        DeclContext* DC = FD->getDeclContext();
        Scope* S = m_Sema->getScopeForContext(DC);
        if (S)
          S->RemoveDecl(FD);
        DC->removeDecl(FD);
      }
    }

    return true;
  }

  // We need to artificially create:
  // cling::valuePrinterInternal::Select((void*) raw_ostream,
  //                                    (ASTContext)Ctx, (Expr*)E, &i);
  Expr* ValuePrinterSynthesizer::SynthesizeCppVP(Expr* E) {
    QualType QT = E->getType();
    // For now we skip void and function pointer types.
    if (QT.isNull() || QT->isVoidType())
      return 0;

    // 1. Call gCling->getValuePrinterStream()
    // 1.1. Find gCling
    SourceLocation NoSLoc = SourceLocation();

    NamespaceDecl* NSD = utils::Lookup::Namespace(m_Sema, "cling");
    NSD = utils::Lookup::Namespace(m_Sema, "valuePrinterInternal", NSD);

    DeclarationName PVName = &m_Context->Idents.get("Select");
    LookupResult R(*m_Sema, PVName, E->getLocStart(), Sema::LookupOrdinaryName,
                   Sema::ForRedeclaration);
    assert(NSD && "There must be a valid namespace.");
    m_Sema->LookupQualifiedName(R, NSD);
    assert(!R.empty() && "Cannot find valuePrinterInternal::Select(...)");

    CXXScopeSpec CSS;
    Expr* UnresolvedLookup
      = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take();

    // 2.4. Prepare the params

    // 2.4.1 Lookup the llvm::raw_ostream
    CXXRecordDecl* RawOStreamRD
      = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "raw_ostream",
                                                 utils::Lookup::Namespace(m_Sema,
                                                                "llvm")));

    assert(RawOStreamRD && "Declaration of the expr not found!");
    QualType RawOStreamRDTy = m_Context->getTypeDeclType(RawOStreamRD);
    // 2.4.2 Lookup the expr type
    CXXRecordDecl* ExprRD
      = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Expr",
                                                 utils::Lookup::Namespace(m_Sema,
                                                                "clang")));
   assert(ExprRD && "Declaration of the expr not found!");
    QualType ExprRDTy = m_Context->getTypeDeclType(ExprRD);
    // 2.4.3 Lookup ASTContext type
    CXXRecordDecl* ASTContextRD
      = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "ASTContext",
                                                 utils::Lookup::Namespace(m_Sema,
                                                                "clang")));
    assert(ASTContextRD && "Declaration of the expr not found!");
    QualType ASTContextRDTy = m_Context->getTypeDeclType(ASTContextRD);

    Expr* RawOStreamTy
      = utils::Synthesize::CStyleCastPtrExpr(m_Sema, RawOStreamRDTy,
                                             (uint64_t)m_ValuePrinterStream.get()
                                             );

    Expr* ExprTy = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ExprRDTy,
                                                        (uint64_t)E);
    Expr* ASTContextTy
      = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ASTContextRDTy,
                                             (uint64_t)m_Context);

    // E might contain temporaries. This means that the topmost expr is
    // ExprWithCleanups. This contains the information about the temporaries and
    // signals when they should be destroyed.
    // Here we replace E with call to value printer and we must extend the life
    // time of those temporaries to the end of the new CallExpr.
    bool NeedsCleanup = false;
    if (ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(E)) {
      E = EWC->getSubExpr();
      NeedsCleanup = true;
    }

    if (QT->isFunctionPointerType()) {
       // convert func ptr to void*:
      E = utils::Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy, E);
    }

    llvm::SmallVector<Expr*, 4> CallArgs;
    CallArgs.push_back(RawOStreamTy);
    CallArgs.push_back(ExprTy);
    CallArgs.push_back(ASTContextTy);
    CallArgs.push_back(E);

    Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext);

    // Here we expect a template instantiation. We need to open the transaction
    // that we are currently work with.
    Transaction::State oldState = getTransaction()->getState();
    getTransaction()->setState(Transaction::kCollecting);
    Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, E->getLocStart(),
                                         CallArgs, E->getLocEnd()).take();
    getTransaction()->setState(oldState);

    Result = m_Sema->ActOnFinishFullExpr(Result).take();
    if (NeedsCleanup && !isa<ExprWithCleanups>(Result)) {
      llvm::ArrayRef<ExprWithCleanups::CleanupObject> Cleanups;
      ExprWithCleanups* EWC
        = ExprWithCleanups::Create(*m_Context, Result, Cleanups);
      Result = EWC;
    }

    assert(Result && "Cannot create value printer!");

    return Result;
  }

  // We need to artificially create:
  // cling_PrintValue(void* (ASTContext)C, void* (Expr)E, const void* (&i)
  Expr* ValuePrinterSynthesizer::SynthesizeVP(Expr* E) {
    QualType QT = E->getType();
    // For now we skip void and function pointer types.
    if (!QT.isNull() && (QT->isVoidType() || QT->isFunctionType()))
      return 0;

    // Find cling_PrintValue
    SourceLocation NoSLoc = SourceLocation();
    DeclarationName PVName = &m_Context->Idents.get("cling_PrintValue");
    LookupResult R(*m_Sema, PVName, E->getLocStart(), Sema::LookupOrdinaryName,
                   Sema::ForRedeclaration);

    Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext);
    m_Sema->LookupName(R, S);
    assert(!R.empty() && "Cannot find cling_PrintValue(...)");

    CXXScopeSpec CSS;
    Expr* UnresolvedLookup
      = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take();

    Expr* VoidEArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema,
                                                          m_Context->VoidPtrTy,
                                                          (uint64_t)E);
    Expr* VoidCArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema,
                                                          m_Context->VoidPtrTy,
                                                          (uint64_t)m_Context);

    if (!QT->isPointerType()) {
      while(ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E))
        E = ICE->getSubExpr();
      E = m_Sema->BuildUnaryOp(S, NoSLoc, UO_AddrOf, E).take();
    }

    llvm::SmallVector<Expr*, 4> CallArgs;
    CallArgs.push_back(VoidEArg);
    CallArgs.push_back(VoidCArg);
    CallArgs.push_back(E);

    Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, E->getLocStart(),
                                         CallArgs, E->getLocEnd()).take();
    assert(Result && "Cannot create value printer!");

    return Result;
  }

  unsigned ValuePrinterSynthesizer::ClearNullStmts(CompoundStmt* CS) {
    llvm::SmallVector<Stmt*, 8> FBody;
    for (StmtRange range = CS->children(); range; ++range)
      if (!isa<NullStmt>(*range))
        FBody.push_back(*range);

    CS->setStmts(*m_Context, FBody.data(), FBody.size());
    return FBody.size();
  }

} // namespace cling
<commit_msg>Remove unused variable.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "ValuePrinterSynthesizer.h"

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Utils/AST.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclGroup.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"

#include "llvm/Support/raw_os_ostream.h"

#include <iostream>

using namespace clang;

namespace cling {

  ValuePrinterSynthesizer::ValuePrinterSynthesizer(clang::Sema* S,
                                                   llvm::raw_ostream* Stream)
    : TransactionTransformer(S), m_Context(&S->getASTContext()) {
    if (Stream)
      m_ValuePrinterStream.reset(Stream);
    else
      m_ValuePrinterStream.reset(new llvm::raw_os_ostream(std::cout));
  }

  // pin the vtable here.
  ValuePrinterSynthesizer::~ValuePrinterSynthesizer()
  { }

  void ValuePrinterSynthesizer::Transform() {
    if (getTransaction()->getCompilationOpts().ValuePrinting
        == CompilationOptions::VPDisabled)
      return;

    if (!tryAttachVP(getTransaction()->getWrapperFD()))
      return setTransaction(0); // On error set to NULL.
  }

  bool ValuePrinterSynthesizer::tryAttachVP(FunctionDecl* FD) {
    // We have to be able to mark the expression for printout. There are
    // three scenarios:
    // 0: Expression printing disabled - don't do anything just exit.
    // 1: Expression printing enabled - print no matter what.
    // 2: Expression printing auto - analyze - rely on the omitted ';' to
    //    not produce the suppress marker.
    int indexOfLastExpr = -1;
    Expr* To = utils::Analyze::GetOrCreateLastExpr(FD, &indexOfLastExpr,
                                                   /*omitDS*/false,
                                                   m_Sema);
    if (To) {
      // Update the CompoundStmt body, avoiding alloc/dealloc of all the el.
      CompoundStmt* CS = cast<CompoundStmt>(FD->getBody());
      assert(CS && "Missing body?");

      const CompilationOptions& CO(getTransaction()->getCompilationOpts());
      switch (CO.ValuePrinting) {
      case CompilationOptions::VPDisabled:
        assert("Don't wait that long. Exit early!");
        break;
      case CompilationOptions::VPEnabled:
        break;
      case CompilationOptions::VPAuto:
        if ((int)CS->size() > indexOfLastExpr+1
            && (*(CS->body_begin() + indexOfLastExpr + 1))
            && isa<NullStmt>(*(CS->body_begin() + indexOfLastExpr + 1)))
          return true; // If next is NullStmt disable VP is disabled - exit.
        break;
      }

      // We can't PushDeclContext, because we don't have scope.
      Sema::ContextRAII pushedDC(*m_Sema, FD);

      if (To) {
        // Strip the parenthesis if any
        if (ParenExpr* PE = dyn_cast<ParenExpr>(To))
          To = PE->getSubExpr();

        Expr* Result = 0;
        if (m_Sema->getLangOpts().CPlusPlus)
          Result = SynthesizeCppVP(To);
        else
          Result = SynthesizeVP(To);

        if (Result)
          *(CS->body_begin()+indexOfLastExpr) = Result;
      }
      // Clear the artificial NullStmt-s
      if (!ClearNullStmts(CS)) {
        // FIXME: Why it is here? Shouldn't it be in DeclExtractor?
        // if no body remove the wrapper
        DeclContext* DC = FD->getDeclContext();
        Scope* S = m_Sema->getScopeForContext(DC);
        if (S)
          S->RemoveDecl(FD);
        DC->removeDecl(FD);
      }
    }

    return true;
  }

  // We need to artificially create:
  // cling::valuePrinterInternal::Select((void*) raw_ostream,
  //                                    (ASTContext)Ctx, (Expr*)E, &i);
  Expr* ValuePrinterSynthesizer::SynthesizeCppVP(Expr* E) {
    QualType QT = E->getType();
    // For now we skip void and function pointer types.
    if (QT.isNull() || QT->isVoidType())
      return 0;

    // 1. Call gCling->getValuePrinterStream()
    // 1.1. Find gCling
    NamespaceDecl* NSD = utils::Lookup::Namespace(m_Sema, "cling");
    NSD = utils::Lookup::Namespace(m_Sema, "valuePrinterInternal", NSD);

    DeclarationName PVName = &m_Context->Idents.get("Select");
    LookupResult R(*m_Sema, PVName, E->getLocStart(), Sema::LookupOrdinaryName,
                   Sema::ForRedeclaration);
    assert(NSD && "There must be a valid namespace.");
    m_Sema->LookupQualifiedName(R, NSD);
    assert(!R.empty() && "Cannot find valuePrinterInternal::Select(...)");

    CXXScopeSpec CSS;
    Expr* UnresolvedLookup
      = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take();

    // 2.4. Prepare the params

    // 2.4.1 Lookup the llvm::raw_ostream
    CXXRecordDecl* RawOStreamRD
      = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "raw_ostream",
                                                 utils::Lookup::Namespace(m_Sema,
                                                                "llvm")));

    assert(RawOStreamRD && "Declaration of the expr not found!");
    QualType RawOStreamRDTy = m_Context->getTypeDeclType(RawOStreamRD);
    // 2.4.2 Lookup the expr type
    CXXRecordDecl* ExprRD
      = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "Expr",
                                                 utils::Lookup::Namespace(m_Sema,
                                                                "clang")));
   assert(ExprRD && "Declaration of the expr not found!");
    QualType ExprRDTy = m_Context->getTypeDeclType(ExprRD);
    // 2.4.3 Lookup ASTContext type
    CXXRecordDecl* ASTContextRD
      = dyn_cast<CXXRecordDecl>(utils::Lookup::Named(m_Sema, "ASTContext",
                                                 utils::Lookup::Namespace(m_Sema,
                                                                "clang")));
    assert(ASTContextRD && "Declaration of the expr not found!");
    QualType ASTContextRDTy = m_Context->getTypeDeclType(ASTContextRD);

    Expr* RawOStreamTy
      = utils::Synthesize::CStyleCastPtrExpr(m_Sema, RawOStreamRDTy,
                                             (uint64_t)m_ValuePrinterStream.get()
                                             );

    Expr* ExprTy = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ExprRDTy,
                                                        (uint64_t)E);
    Expr* ASTContextTy
      = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ASTContextRDTy,
                                             (uint64_t)m_Context);

    // E might contain temporaries. This means that the topmost expr is
    // ExprWithCleanups. This contains the information about the temporaries and
    // signals when they should be destroyed.
    // Here we replace E with call to value printer and we must extend the life
    // time of those temporaries to the end of the new CallExpr.
    bool NeedsCleanup = false;
    if (ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(E)) {
      E = EWC->getSubExpr();
      NeedsCleanup = true;
    }

    if (QT->isFunctionPointerType()) {
       // convert func ptr to void*:
      E = utils::Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy, E);
    }

    llvm::SmallVector<Expr*, 4> CallArgs;
    CallArgs.push_back(RawOStreamTy);
    CallArgs.push_back(ExprTy);
    CallArgs.push_back(ASTContextTy);
    CallArgs.push_back(E);

    Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext);

    // Here we expect a template instantiation. We need to open the transaction
    // that we are currently work with.
    Transaction::State oldState = getTransaction()->getState();
    getTransaction()->setState(Transaction::kCollecting);
    Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, E->getLocStart(),
                                         CallArgs, E->getLocEnd()).take();
    getTransaction()->setState(oldState);

    Result = m_Sema->ActOnFinishFullExpr(Result).take();
    if (NeedsCleanup && !isa<ExprWithCleanups>(Result)) {
      llvm::ArrayRef<ExprWithCleanups::CleanupObject> Cleanups;
      ExprWithCleanups* EWC
        = ExprWithCleanups::Create(*m_Context, Result, Cleanups);
      Result = EWC;
    }

    assert(Result && "Cannot create value printer!");

    return Result;
  }

  // We need to artificially create:
  // cling_PrintValue(void* (ASTContext)C, void* (Expr)E, const void* (&i)
  Expr* ValuePrinterSynthesizer::SynthesizeVP(Expr* E) {
    QualType QT = E->getType();
    // For now we skip void and function pointer types.
    if (!QT.isNull() && (QT->isVoidType() || QT->isFunctionType()))
      return 0;

    // Find cling_PrintValue
    SourceLocation NoSLoc = SourceLocation();
    DeclarationName PVName = &m_Context->Idents.get("cling_PrintValue");
    LookupResult R(*m_Sema, PVName, E->getLocStart(), Sema::LookupOrdinaryName,
                   Sema::ForRedeclaration);

    Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext);
    m_Sema->LookupName(R, S);
    assert(!R.empty() && "Cannot find cling_PrintValue(...)");

    CXXScopeSpec CSS;
    Expr* UnresolvedLookup
      = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take();

    Expr* VoidEArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema,
                                                          m_Context->VoidPtrTy,
                                                          (uint64_t)E);
    Expr* VoidCArg = utils::Synthesize::CStyleCastPtrExpr(m_Sema,
                                                          m_Context->VoidPtrTy,
                                                          (uint64_t)m_Context);

    if (!QT->isPointerType()) {
      while(ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E))
        E = ICE->getSubExpr();
      E = m_Sema->BuildUnaryOp(S, NoSLoc, UO_AddrOf, E).take();
    }

    llvm::SmallVector<Expr*, 4> CallArgs;
    CallArgs.push_back(VoidEArg);
    CallArgs.push_back(VoidCArg);
    CallArgs.push_back(E);

    Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, E->getLocStart(),
                                         CallArgs, E->getLocEnd()).take();
    assert(Result && "Cannot create value printer!");

    return Result;
  }

  unsigned ValuePrinterSynthesizer::ClearNullStmts(CompoundStmt* CS) {
    llvm::SmallVector<Stmt*, 8> FBody;
    for (StmtRange range = CS->children(); range; ++range)
      if (!isa<NullStmt>(*range))
        FBody.push_back(*range);

    CS->setStmts(*m_Context, FBody.data(), FBody.size());
    return FBody.size();
  }

} // namespace cling
<|endoftext|>


<commit_before>#include <AndroidClient.h>
#include <jni.h>
#include <android/log.h>

class AndroidClient : public HTTPClient {
 public:

	AndroidClient(JNIEnv * _env, const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive)
 : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive), env(_env) {

		__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndroidClient Constructor called");

	}

	void androidInit(){

		cookieManagerClass =  env->FindClass("android/webkit/CookieManager");
		httpClass = env->FindClass("java/net/HttpURLConnection");
		urlClass = env->FindClass("java/net/URL");
	 	inputStreamClass = env->FindClass("java/io/InputStream");

	 	readMethod = env->GetMethodID(inputStreamClass, "read", "([B)I");
	 	urlConstructor =  env->GetMethodID(urlClass, "<init>", "(Ljava/lang/String;)V");
		openConnectionMethod = env->GetMethodID(urlClass, "openConnection", "()Ljava/net/URLConnection;");
		setRequestProperty = env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
		setRequestMethod = env->GetMethodID(httpClass, "setRequestMethod", "(Ljava/lang/String;)V");
		setFollowMethod = env->GetMethodID(httpClass, "setInstanceFollowRedirects", "(Z)V");
		setDoInputMethod = env->GetMethodID(httpClass, "setDoInput", "(Z)V");
		connectMethod = env->GetMethodID(httpClass, "connect", "()V");
		getResponseCodeMethod = env->GetMethodID(httpClass, "getResponseCode", "()I");
		getResponseMessageMethod = env->GetMethodID(httpClass, "getResponseMessage", "()Ljava/lang/String;");
		setRequestPropertyMethod =  env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
		clearCookiesMethod =  env->GetMethodID(cookieManagerClass, "removeAllCookie", "()V");
		getInputStreamMethod =  env->GetMethodID(httpClass, "getInputStream", "()Ljava/io/InputStream;");

		initDone = true;

	}

  HTTPResponse request(const HTTPRequest & req, const Authorization & auth){

		__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndroidClient request called");

  	if (!initDone){
  		androidInit();
  	}

  	jobject url = env->NewObject(urlClass, urlConstructor, env->NewStringUTF(req.getURI().c_str()));
  	jobject connection = env->CallObjectMethod(url, openConnectionMethod);

  	//Authorization example
		//env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF("Authorization"), env->NewStringUTF("myUsername"));

		//  std::string auth_header = auth.createHeader();

		// if (!auth_header.empty()) {
		//		env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF(auth.getHeaderName()), env->NewStringUTF(auth_header.c_str()));
		//}

		env->CallVoidMethod(connection, setFollowMethod, req.getFollowLocation() ? JNI_TRUE : JNI_FALSE);

		switch (req.getType()) {
		case HTTPRequest::POST:
			env->CallVoidMethod(connection, setRequestMethod, env->NewStringUTF("POST"));
			break;
		case HTTPRequest::GET:
			env->CallVoidMethod(connection, setRequestMethod, env->NewStringUTF("GET"));
			;
			break;
		}

		int responseCode = env->CallIntMethod(connection, getResponseCodeMethod);

		if (env->ExceptionCheck()) {
			env->ExceptionClear();
			__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "EXCPETION http request responsecode = %i", responseCode);
			return HTTPResponse(0, "exception");
		}
		__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "http request responsecode = %i", responseCode);

		const char *errorMessage = "";

		if (responseCode >= 400 && responseCode <= 599){
			jstring javaMessage = (jstring)env->CallObjectMethod(connection, getResponseMessageMethod);
			errorMessage = env->GetStringUTFChars(javaMessage, 0);

		}

		jobject input = env->CallObjectMethod(connection, getInputStreamMethod);
		env->ExceptionClear();

		jbyteArray array = env->NewByteArray(4096);
		int g = 0;
		std::string content;

		while ((g = env->CallIntMethod(input, readMethod, array)) != -1) {

			jbyte* content_array = env->GetByteArrayElements(array, NULL);
			if (callback) {
				callback->handleChunk(g, (char*) content_array);
			} else {
				content += std::string((char*) content_array, g);
			}

			env->ReleaseByteArrayElements(array, content_array, JNI_ABORT);

		}

		if (responseCode >= 300 && responseCode <= 399) {
		  // TODO: connection.getURL()
		}

		__android_log_print(ANDROID_LOG_INFO, "content", "contentti = %Ld", content.size());

		return HTTPResponse(responseCode, errorMessage, "", content);

  }

  void clearCookies() {

  	env->CallVoidMethod(cookieManagerClass, clearCookiesMethod);

  }

 protected:
  bool initialize() { return true; }

 private:
	bool initDone = false;

  JNIEnv * env;
  jclass cookieManagerClass;
  jmethodID clearCookiesMethod;

  jclass bitmapClass;
  jclass factoryClass;
  jclass httpClass;
  jclass urlClass;
  jclass bufferedReaderClass;
  jclass inputStreamReaderClass;
  jclass inputStreamClass;
  jmethodID urlConstructor;
  jmethodID openConnectionMethod;
  jmethodID setRequestProperty;
  jmethodID setRequestMethod;
  jmethodID setDoInputMethod;
  jmethodID connectMethod;
  jmethodID getResponseCodeMethod;
  jmethodID getResponseMessageMethod;
  jmethodID setRequestPropertyMethod;
  jmethodID outputStreamConstructor;
  jmethodID factoryDecodeMethod;
  jmethodID getInputStreamMethod;
  jmethodID bufferedReaderConstructor;
  jmethodID inputStreamReaderConstructor;
  jmethodID readLineMethod;
  jmethodID readerCloseMethod;
  jmethodID readMethod;
  jmethodID inputStreamCloseMethod;
  jmethodID setFollowMethod;

};

std::shared_ptr<HTTPClient>
AndroidClientFactory::createClient(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {
  return std::make_shared<AndroidClient>(env, _user_agent, _enable_cookies, _enable_keepalive);
}

<commit_msg>Add url follow link get<commit_after>#include <AndroidClient.h>
#include <jni.h>
#include <android/log.h>

class AndroidClient : public HTTPClient {
 public:

	AndroidClient(JNIEnv * _env, const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive)
 : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive), env(_env) {

		__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndroidClient Constructor called");

	}

	void androidInit(){

		cookieManagerClass =  env->FindClass("android/webkit/CookieManager");
		httpClass = env->FindClass("java/net/HttpURLConnection");
		urlClass = env->FindClass("java/net/URL");
	 	inputStreamClass = env->FindClass("java/io/InputStream");

		getHeaderMethod = env->GetMethodID(httpClass, "getHeaderField", "(Ljava/lang/String;)Ljava/lang/String;");
	 	readMethod = env->GetMethodID(inputStreamClass, "read", "([B)I");
	 	urlConstructor =  env->GetMethodID(urlClass, "<init>", "(Ljava/lang/String;)V");
		openConnectionMethod = env->GetMethodID(urlClass, "openConnection", "()Ljava/net/URLConnection;");
		setRequestProperty = env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
		setRequestMethod = env->GetMethodID(httpClass, "setRequestMethod", "(Ljava/lang/String;)V");
		setFollowMethod = env->GetMethodID(httpClass, "setInstanceFollowRedirects", "(Z)V");
		setDoInputMethod = env->GetMethodID(httpClass, "setDoInput", "(Z)V");
		connectMethod = env->GetMethodID(httpClass, "connect", "()V");
		getResponseCodeMethod = env->GetMethodID(httpClass, "getResponseCode", "()I");
		getResponseMessageMethod = env->GetMethodID(httpClass, "getResponseMessage", "()Ljava/lang/String;");
		setRequestPropertyMethod =  env->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
		clearCookiesMethod =  env->GetMethodID(cookieManagerClass, "removeAllCookie", "()V");
		getInputStreamMethod =  env->GetMethodID(httpClass, "getInputStream", "()Ljava/io/InputStream;");

		initDone = true;

	}

  HTTPResponse request(const HTTPRequest & req, const Authorization & auth){

		__android_log_print(ANDROID_LOG_VERBOSE, "Sometrik", "AndroidClient request called");

  	if (!initDone){
  		androidInit();
  	}

  	jobject url = env->NewObject(urlClass, urlConstructor, env->NewStringUTF(req.getURI().c_str()));
  	jobject connection = env->CallObjectMethod(url, openConnectionMethod);

  	//Authorization example
		//env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF("Authorization"), env->NewStringUTF("myUsername"));

		//  std::string auth_header = auth.createHeader();

		// if (!auth_header.empty()) {
		//		env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF(auth.getHeaderName()), env->NewStringUTF(auth_header.c_str()));
		//}

		env->CallVoidMethod(connection, setFollowMethod, req.getFollowLocation() ? JNI_TRUE : JNI_FALSE);

		switch (req.getType()) {
		case HTTPRequest::POST:
			env->CallVoidMethod(connection, setRequestMethod, env->NewStringUTF("POST"));
			break;
		case HTTPRequest::GET:
			env->CallVoidMethod(connection, setRequestMethod, env->NewStringUTF("GET"));
			;
			break;
		}

		int responseCode = env->CallIntMethod(connection, getResponseCodeMethod);

		if (env->ExceptionCheck()) {
			env->ExceptionClear();
			__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "EXCPETION http request responsecode = %i", responseCode);
			return HTTPResponse(0, "exception");
		}
		__android_log_print(ANDROID_LOG_INFO, "AndroidClient", "http request responsecode = %i", responseCode);

		const char *errorMessage = "";

		if (responseCode >= 400 && responseCode <= 599){
			jstring javaMessage = (jstring)env->CallObjectMethod(connection, getResponseMessageMethod);
			errorMessage = env->GetStringUTFChars(javaMessage, 0);

		}

		jobject input = env->CallObjectMethod(connection, getInputStreamMethod);
		env->ExceptionClear();

		jbyteArray array = env->NewByteArray(4096);
		int g = 0;
		std::string content;

		while ((g = env->CallIntMethod(input, readMethod, array)) != -1) {

			jbyte* content_array = env->GetByteArrayElements(array, NULL);
			if (callback) {
				callback->handleChunk(g, (char*) content_array);
			} else {
				content += std::string((char*) content_array, g);
			}

			env->ReleaseByteArrayElements(array, content_array, JNI_ABORT);

		}

		if (responseCode >= 300 && responseCode <= 399) {

			jstring followURL = (jstring)env->CallObjectMethod(connection, getHeaderMethod, env->NewStringUTF("location"));
			const char *followString = env->GetStringUTFChars(followURL, 0);

			__android_log_print(ANDROID_LOG_INFO, "content", "followURL = %s", followString);

		}

		__android_log_print(ANDROID_LOG_INFO, "content", "contentti = %Ld", content.size());

		return HTTPResponse(responseCode, errorMessage, "", content);

  }

  void clearCookies() {

  	env->CallVoidMethod(cookieManagerClass, clearCookiesMethod);

  }

 protected:
  bool initialize() { return true; }

 private:
	bool initDone = false;

  JNIEnv * env;
  jclass cookieManagerClass;
  jmethodID clearCookiesMethod;

  jclass bitmapClass;
  jclass factoryClass;
  jclass httpClass;
  jclass urlClass;
  jclass bufferedReaderClass;
  jclass inputStreamReaderClass;
  jclass inputStreamClass;
  jmethodID urlConstructor;
  jmethodID openConnectionMethod;
  jmethodID setRequestProperty;
  jmethodID setRequestMethod;
  jmethodID setDoInputMethod;
  jmethodID connectMethod;
  jmethodID getResponseCodeMethod;
  jmethodID getResponseMessageMethod;
  jmethodID setRequestPropertyMethod;
  jmethodID outputStreamConstructor;
  jmethodID factoryDecodeMethod;
  jmethodID getInputStreamMethod;
  jmethodID bufferedReaderConstructor;
  jmethodID inputStreamReaderConstructor;
  jmethodID readLineMethod;
  jmethodID readerCloseMethod;
  jmethodID readMethod;
  jmethodID inputStreamCloseMethod;
  jmethodID setFollowMethod;
  jmethodID getHeaderMethod;

};

std::shared_ptr<HTTPClient>
AndroidClientFactory::createClient(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {
  return std::make_shared<AndroidClient>(env, _user_agent, _enable_cookies, _enable_keepalive);
}

<|endoftext|>