<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library 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 library 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 library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes
#include <fstream>

// Local includes
#include "libmesh/off_io.h"
#include "libmesh/mesh_base.h"
#include "libmesh/face_tri3.h"

namespace libMesh
{

// ------------------------------------------------------------
// OFFIO class members

void OFFIO::read(const std::string& name)
{
  std::ifstream in (name.c_str());

  read_stream(in);
}

void OFFIO::read_stream(std::istream& in)
{
  // This is a serial-only process for now;
  // the Mesh should be read on processor 0 and
  // broadcast later
  libmesh_assert_equal_to (libMesh::processor_id(), 0);

  // Get a reference to the mesh
  MeshBase& mesh = MeshInput<MeshBase>::mesh();

  // Clear any existing mesh data
  mesh.clear();

  // STL only works in 2D
  mesh.set_mesh_dimension(2);

#if LIBMESH_DIM < 2
  libMesh::err << "Cannot open dimension 2 mesh file when configured without 2D support." <<
                  std::endl;
  libmesh_error();
#endif

  // Check the input buffer
  libmesh_assert (in.good());

  unsigned int nn, ne, nf;

  std::string label;

  // Read the first string.  It should say "OFF"
  in >> label;

  libmesh_assert_equal_to (label, "OFF");

  // read the number of nodes, faces, and edges
  in >> nn >> nf >> ne;

  // resize local vectors.
  //  _nodes.resize(nn);
  //_elements.resize(nf);

  Real x=0., y=0., z=0.;

  // Read the nodes
  for (unsigned int n=0; n<nn; n++)
    {
      libmesh_assert (in.good());

      in >> x
	 >> y
	 >> z;

      mesh.add_point ( Point(x,y,z), n );
    }

  unsigned int dummy, n0, n1, n2;

  // Read the triangles
  for (unsigned int e=0; e<nf; e++)
    {
      libmesh_assert (in.good());

      // _elements[e] = new Tri3;
      // _elements[e]->set_id (e);
      Elem* elem = new Tri3;
      elem->set_id(e);
      mesh.add_elem (elem);

      // The number of nodes in the object
      in >> dummy;

      libmesh_assert_equal_to (dummy, 3);

      in >> n0
	 >> n1
	 >> n2;

      elem->set_node(0) = mesh.node_ptr(n0);
      elem->set_node(1) = mesh.node_ptr(n1);
      elem->set_node(2) = mesh.node_ptr(n2);
    }
}

} // namespace libMesh
<commit_msg>Patch from Roman Vetter for 1D support in OFF I/O<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library 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 library 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 library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

// C++ includes
#include <fstream>

// Local includes
#include "libmesh/off_io.h"
#include "libmesh/mesh_base.h"
#include "libmesh/edge_edge2.h"
#include "libmesh/face_tri3.h"

namespace libMesh
{

// ------------------------------------------------------------
// OFFIO class members

void OFFIO::read(const std::string& name)
{
  std::ifstream in (name.c_str());

  read_stream(in);
}

void OFFIO::read_stream(std::istream& in)
{
  // This is a serial-only process for now;
  // the Mesh should be read on processor 0 and
  // broadcast later
  libmesh_assert_equal_to (libMesh::processor_id(), 0);

  // Get a reference to the mesh
  MeshBase& mesh = MeshInput<MeshBase>::mesh();

  // Clear any existing mesh data
  mesh.clear();

  // Check the input buffer
  libmesh_assert (in.good());

  unsigned int nn, ne, nf;

  std::string label;

  // Read the first string.  It should say "OFF"
  in >> label;

  libmesh_assert_equal_to (label, "OFF");

  // read the number of nodes, faces, and edges
  in >> nn >> nf >> ne;

  Real x=0., y=0., z=0.;

  // Read the nodes
  for (unsigned int n=0; n<nn; n++)
    {
      libmesh_assert (in.good());

      in >> x
	 >> y
	 >> z;

      mesh.add_point ( Point(x,y,z), n );
    }

  unsigned int nv, nid;

  // Read the elements
  for (unsigned int e=0; e<nf; e++)
    {
      libmesh_assert (in.good());

      // The number of vertices in the element
      in >> nv;

      libmesh_assert(nv == 2 || nv == 3);
      if (e == 0)
      {
        mesh.set_mesh_dimension(nv-1);
        if (nv == 3)
        {
#if LIBMESH_DIM < 2
          libMesh::err << "Cannot open dimension 2 mesh file when configured without 2D support." <<
                          std::endl;
          libmesh_error();
#endif
        }
      }

      Elem* elem;
      switch (nv)
      {
        case 2: elem = new Edge2; break;
        case 3: elem = new Tri3 ; break;
        default: libmesh_error();
      }

      elem->set_id(e);
      mesh.add_elem (elem);

      for (unsigned int i=0; i<nv; i++)
      {
        in >> nid;
        elem->set_node(i) = mesh.node_ptr(nid);
      }
    }
}

} // namespace libMesh
<|endoftext|>


<commit_before>#include "Accel.h"

#define LOG_OUT 1
#include <FHT.h>

#define MOVING_AVERAGE_INTERVALS 20
#define ACCEL_THRESHOLD 1
#define COMPASS_AVERAGE_INTERVALS 10
#define ACCELEROMETER_CALIBRATE 0
#define MAG_CALIBRATE_X 0.7
#define MAG_CALIBRATE_Y -0.5

Accel::Accel(uint32_t intervalMS)
{
	_intervalMS = intervalMS;
}

bool Accel::begin()
{
    // Try to initialise and warn if we couldn't detect the chip
    if (!_lsm.begin())
    {
      Serial.println("Oops ... unable to initialize the LSM. Check your wiring!");
      while (1);
    }
    _lsm.setupAccel(_lsm.LSM9DS0_ACCELRANGE_4G);
    _lsm.setupMag(_lsm.LSM9DS0_MAGGAIN_4GAUSS);
    _lsm.setupGyro(_lsm.LSM9DS0_GYROSCALE_500DPS);

    return true;
}

bool
Accel::Update()
{
    float currentCompass = 0;
    if ( millis() - _lastUpdateMS > _intervalMS + 10) {
        Serial.println("ERROR: We didn't update accel in time.");
    }
    if ( millis() - _lastUpdateMS < _intervalMS) {
        return false;
    }
    _lastUpdateMS = millis();

    sensors_event_t accelEvent;
    sensors_event_t magEvent;
    sensors_event_t gyroEvent;
    //sensors_event_t tempEvent;
    _lsm.getEvent(&accelEvent, &magEvent, &gyroEvent, NULL);

    float x = accelEvent.acceleration.x;
    float y = accelEvent.acceleration.y;
    float z = accelEvent.acceleration.z;
    float magx = magEvent.magnetic.x + MAG_CALIBRATE_X;
    float magy = magEvent.magnetic.y + MAG_CALIBRATE_Y;
    float magz = magEvent.magnetic.z;
    float gyrox = gyroEvent.gyro.x * PI/180.0 * ACCEL_INTERVAL_MS / 1000;
    float gyroy = gyroEvent.gyro.y * PI/180.0 * ACCEL_INTERVAL_MS / 1000;
    float gyroz = gyroEvent.gyro.z * PI/180.0 * ACCEL_INTERVAL_MS / 1000;
    // Serial.print("Accel X: "); Serial.print(accelEvent.acceleration.x);     Serial.print(" ");
    // Serial.print("Y: "); Serial.print(accelEvent.acceleration.y);  Serial.print(" ");
    // Serial.print("Z: "); Serial.println(accelEvent.acceleration.z);
    // Serial.print("Mag X: "); Serial.print(magx);     Serial.print(" ");
    // Serial.print("Y: "); Serial.print(magy);  Serial.print(" ");
    // Serial.print("Z: "); Serial.println(magz);
    // Serial.print("Gyro X: "); Serial.print(gyrox);     Serial.print(" ");
    // Serial.print("Y: "); Serial.print(gyroy);  Serial.print(" ");
    // Serial.print("Z: "); Serial.println(gyroz);

    // Quaternion rotate;
    // rotate.from_euler_rotation(gyrox, gyroy, gyroz);
    _q = Quaternion().from_euler_rotation(gyrox, gyroy, gyroz).conj() * _q;
    Quaternion gravity(x, y, z);
    gravity.normalize();

    // Serial.print("_q W: "); Serial.print(_q.a);
    // Serial.print(" X: "); Serial.print(_q.b);
    // Serial.print(" Y: "); Serial.print(_q.c);
    // Serial.print(" Z: "); Serial.println(_q.d);

    Quaternion expected_gravity(0, 0, 1);
    expected_gravity = _q.rotate(expected_gravity);
    // Serial.print("expected W: "); Serial.print(expected_gravity.a);
    // Serial.print(" X: "); Serial.print(expected_gravity.b);
    // Serial.print(" Y: "); Serial.print(expected_gravity.c);
    // Serial.print(" Z: "); Serial.println(expected_gravity.d);

    // Serial.print("gravity W: "); Serial.print(gravity.a);
    // Serial.print(" X: "); Serial.print(gravity.b);
    // Serial.print(" Y: "); Serial.print(gravity.c);
    // Serial.print(" Z: "); Serial.println(gravity.d);

    Quaternion toRotate = expected_gravity.rotation_between_vectors(gravity);
    // Serial.print("toRot W: "); Serial.print(toRotate.a);
    // Serial.print(" X: "); Serial.print(toRotate.b);
    // Serial.print(" Y: "); Serial.print(toRotate.c);
    // Serial.print(" Z: "); Serial.println(toRotate.d);

    //expected_gravity = toRotate.frational(0.01).rotate(expected_gravity);
    //expected_gravity = (toRotate.frational(0.01) * _q).rotate(Quaternion(0, 0, 1));

    // Serial.print("afterRot W: "); Serial.print(expected_gravity.a);
    // Serial.print(" X: "); Serial.print(expected_gravity.b);
    // Serial.print(" Y: "); Serial.print(expected_gravity.c);
    // Serial.print(" Z: "); Serial.println(expected_gravity.d);

    _q = toRotate.fractional(0.1) * _q;

    float currentAccel = sqrt(x*x + y*y + z*z) - SENSORS_GRAVITY_EARTH + ACCELEROMETER_CALIBRATE;
    float currentAbsAccel = abs(currentAccel);
    computeFht(currentAccel);

    _avgAbsAccel = (_avgAbsAccel * (MOVING_AVERAGE_INTERVALS-1) + currentAbsAccel)/MOVING_AVERAGE_INTERVALS;
    _isDancing = _avgAbsAccel > ACCEL_THRESHOLD;
    // Serial.print("avgAbsAccel: "); Serial.println(_avgAbsAccel);       Serial.print(" ");
    // Serial.print("currentAccel: "); Serial.println(currentAccel);
    // Serial.print("temp (C): "); Serial.println(tempEvent.temperature);       Serial.print(" ");

    float heading = atan2(magy, magx);

    //Serial.print("heading (rad): "); Serial.println(heading);
    //Serial.print("orientation: "); Serial.println(_lsm.magData.orientation);

    // Correct for when signs are reversed.
    if (heading < 0) {
        heading += 2*PI;
    } else if (heading >= 2*PI) {
        // Check for wrap due to addition of declination.
        heading -= 2*PI;
    }

    heading = heading * 180 / PI;
    // Serial.print("headingdegrees: "); Serial.println(heading);

    // We adjust the heading before taking the moving average to handle the 360 -> 0 jump
    if (heading > _compassAvg + 180) {
        heading -= 360;
    } else if (heading < _compassAvg - 180) {
        heading += 360;
    }
    _compassAvg = (_compassAvg * (COMPASS_AVERAGE_INTERVALS - 1) + heading) / COMPASS_AVERAGE_INTERVALS;
    if (_compassAvg < 0) {
        _compassAvg += 360;
    } else if (_compassAvg >= 360) {
        _compassAvg -= 360;
    }
    //Serial.print("compasAvg: "); Serial.println(_compassAvg);

    //Convert float to int
    _compassReading = (int)_compassAvg;

    return true;
}

float normalize_rads(float angle_rad) {
    if (angle_rad < 0) {
        angle_rad += 2 * PI;
    } else if (angle_rad >= 2*PI) {
        angle_rad -= 2 * PI;
    }
    return angle_rad;
}

void Accel::computeFht(float lastValue) {
    lastValue *= 4000;
    lastValue =  max(-32767, min(32767, lastValue));
    for (int i = 0; i < FHT_N - 1; i++) {
        _old_fht[i] = _old_fht[i + 1];
        fht_input[i] = _old_fht[i];
    }
    fht_input[FHT_N - 1] = (int) lastValue;
    _old_fht[FHT_N - 1] = (int) lastValue;
    fht_window();
    fht_reorder();
    fht_run();
    fht_mag_log();
    //fht_mag_lin();
    int max = 0;
    int maxIndex = 0;
    for (int i = 0; i < FHT_N/2; i++)
    {
        uint8_t val = fht_log_out[i];
        //uint16_t val = fht_lin_out[i];
        //Serial.print("Index: "); Serial.print(i); Serial.print("  val: "); Serial.println(val);
        if (val > max)
        {
            max = val;
            maxIndex = i;
        }
    }
    // Serial.print("Index: "); Serial.print(maxIndex); Serial.print("  val: "); Serial.println(max);
    int k = maxIndex;
    int negK = FHT_N - 1 - k;
    int realPlusImg = fht_input[k];
    int realMinusImg = fht_input[negK];

    //float phase = atan2((fht_input[k]	 - fht_input[negK]), (fht_input[k] + fht_input[negK]));
    float phase = atan2(realPlusImg - realMinusImg, realPlusImg + realMinusImg);
    // Serial.print("Phase: "); Serial.println(phase);
    if (maxIndex == _old_max_index && maxIndex != 0) {
        float _phaseDiff = normalize_rads(phase - _old_phase);

        // Only update the rate if we are in the same fht bucket.
        _phaseRateAverage = (((_phaseRateAverage * 9) + _phaseDiff ) / 10);
    }
    _old_phase = phase;
    _old_max_index = maxIndex;

    _phase_avg += _phaseRateAverage;
    if (phase + PI < _phase_avg) {
        phase += 2*PI;
    } else if (phase - PI > _phase_avg) {
        phase -= 2*PI;
    }

    _phase_avg = (_phase_avg * 19 + phase) / 20;
    _phase_avg = normalize_rads(_phase_avg + PI) - PI;

    // Serial.print("Phase Rate Avg: "); Serial.println(_phaseRateAverage);
    // Serial.print("Phase Avg: "); Serial.println(_phase_avg);
    //for (int i = 0; i < FHT_N; i++) {
    //	  fht_input[i] = (int) old_fht[0];
    //}
}

float Accel::getPhase() {
    return _phase_avg;
}

float Accel::getPhasePercentage() {
    return (_phase_avg + PI)/(2*PI);
}

long Accel::GetCompassReading()
{
    return _compassReading;
}

bool Accel::isDancing()
{
    return _isDancing;
}

float Accel::getPhaseRatePercentage()
{
    return _phaseRateAverage/(2*PI);
}
<commit_msg>minor refactor: 18,832<commit_after>#include "Accel.h"

#define LOG_OUT 1
#include <FHT.h>

#define MOVING_AVERAGE_INTERVALS 20
#define ACCEL_THRESHOLD 1
#define COMPASS_AVERAGE_INTERVALS 10
#define ACCELEROMETER_CALIBRATE 0
#define MAG_CALIBRATE_X 0.7
#define MAG_CALIBRATE_Y -0.5

Accel::Accel(uint32_t intervalMS)
{
	_intervalMS = intervalMS;
}

bool Accel::begin()
{
    // Try to initialise and warn if we couldn't detect the chip
    if (!_lsm.begin())
    {
      Serial.println("Oops ... unable to initialize the LSM. Check your wiring!");
      while (1);
    }
    _lsm.setupAccel(_lsm.LSM9DS0_ACCELRANGE_4G);
    _lsm.setupMag(_lsm.LSM9DS0_MAGGAIN_4GAUSS);
    _lsm.setupGyro(_lsm.LSM9DS0_GYROSCALE_500DPS);

    return true;
}

bool
Accel::Update()
{
    float currentCompass = 0;
    if ( millis() - _lastUpdateMS > _intervalMS + 10) {
        Serial.println("ERROR: We didn't update accel in time.");
    }
    if ( millis() - _lastUpdateMS < _intervalMS) {
        return false;
    }
    _lastUpdateMS = millis();

    sensors_event_t accelEvent;
    sensors_event_t magEvent;
    sensors_event_t gyroEvent;
    //sensors_event_t tempEvent;
    _lsm.getEvent(&accelEvent, &magEvent, &gyroEvent, NULL);

    float magx = magEvent.magnetic.x + MAG_CALIBRATE_X;
    float magy = magEvent.magnetic.y + MAG_CALIBRATE_Y;
    float magz = magEvent.magnetic.z;

    // Gyro is in degrees per second, so we change to rads and mult by dt
    float gyrox = gyroEvent.gyro.x * PI/180.0 * ACCEL_INTERVAL_MS / 1000;
    float gyroy = gyroEvent.gyro.y * PI/180.0 * ACCEL_INTERVAL_MS / 1000;
    float gyroz = gyroEvent.gyro.z * PI/180.0 * ACCEL_INTERVAL_MS / 1000;

    // Serial.print("Accel X: "); Serial.print(accelEvent.acceleration.x);     Serial.print(" ");
    // Serial.print("Y: "); Serial.print(accelEvent.acceleration.y);  Serial.print(" ");
    // Serial.print("Z: "); Serial.println(accelEvent.acceleration.z);
    // Serial.print("Mag X: "); Serial.print(magx);     Serial.print(" ");
    // Serial.print("Y: "); Serial.print(magy);  Serial.print(" ");
    // Serial.print("Z: "); Serial.println(magz);
    // Serial.print("Gyro X: "); Serial.print(gyrox);     Serial.print(" ");
    // Serial.print("Y: "); Serial.print(gyroy);  Serial.print(" ");
    // Serial.print("Z: "); Serial.println(gyroz);

    // Rotate by the gyro.
    _q = Quaternion().from_euler_rotation(gyrox, gyroy, gyroz).conj() * _q;
    Quaternion gravity(accelEvent.acceleration.x, accelEvent.acceleration.y, accelEvent.acceleration.z);

    // Get the size of the vector before normalizing it.
    float currentAccel = gravity.norm() - SENSORS_GRAVITY_EARTH + ACCELEROMETER_CALIBRATE;
    float currentAbsAccel = abs(currentAccel);
    // TODO: carrino: Ignore gravity if it is too small.
    gravity.normalize();

    Quaternion expected_gravity(0, 0, 1);
    expected_gravity = _q.rotate(expected_gravity);

    Quaternion toRotate = expected_gravity.rotation_between_vectors(gravity);
    // Serial.print("toRot W: "); Serial.print(toRotate.a);
    // Serial.print(" X: "); Serial.print(toRotate.b);
    // Serial.print(" Y: "); Serial.print(toRotate.c);
    // Serial.print(" Z: "); Serial.println(toRotate.d);

    // Take gravity into account.
    _q = toRotate.fractional(0.1) * _q;

    computeFht(currentAccel);

    _avgAbsAccel = (_avgAbsAccel * (MOVING_AVERAGE_INTERVALS-1) + currentAbsAccel)/MOVING_AVERAGE_INTERVALS;
    _isDancing = _avgAbsAccel > ACCEL_THRESHOLD;

    float heading = atan2(magy, magx);

    // Correct for when signs are reversed.
    if (heading < 0) {
        heading += 2*PI;
    } else if (heading >= 2*PI) {
        // Check for wrap due to addition of declination.
        heading -= 2*PI;
    }

    heading = heading * 180 / PI;
    // Serial.print("headingdegrees: "); Serial.println(heading);

    // We adjust the heading before taking the moving average to handle the 360 -> 0 jump
    if (heading > _compassAvg + 180) {
        heading -= 360;
    } else if (heading < _compassAvg - 180) {
        heading += 360;
    }
    _compassAvg = (_compassAvg * (COMPASS_AVERAGE_INTERVALS - 1) + heading) / COMPASS_AVERAGE_INTERVALS;
    if (_compassAvg < 0) {
        _compassAvg += 360;
    } else if (_compassAvg >= 360) {
        _compassAvg -= 360;
    }
    //Serial.print("compasAvg: "); Serial.println(_compassAvg);

    //Convert float to int
    _compassReading = (int)_compassAvg;

    return true;
}

float normalize_rads(float angle_rad) {
    if (angle_rad < 0) {
        angle_rad += 2 * PI;
    } else if (angle_rad >= 2*PI) {
        angle_rad -= 2 * PI;
    }
    return angle_rad;
}

void Accel::computeFht(float lastValue) {
    lastValue *= 4000;
    lastValue =  max(-32767, min(32767, lastValue));
    for (int i = 0; i < FHT_N - 1; i++) {
        _old_fht[i] = _old_fht[i + 1];
        fht_input[i] = _old_fht[i];
    }
    fht_input[FHT_N - 1] = (int) lastValue;
    _old_fht[FHT_N - 1] = (int) lastValue;
    fht_window();
    fht_reorder();
    fht_run();
    fht_mag_log();
    //fht_mag_lin();
    int max = 0;
    int maxIndex = 0;
    for (int i = 0; i < FHT_N/2; i++)
    {
        uint8_t val = fht_log_out[i];
        //uint16_t val = fht_lin_out[i];
        //Serial.print("Index: "); Serial.print(i); Serial.print("  val: "); Serial.println(val);
        if (val > max)
        {
            max = val;
            maxIndex = i;
        }
    }
    // Serial.print("Index: "); Serial.print(maxIndex); Serial.print("  val: "); Serial.println(max);
    int k = maxIndex;
    int negK = FHT_N - 1 - k;
    int realPlusImg = fht_input[k];
    int realMinusImg = fht_input[negK];

    //float phase = atan2((fht_input[k]	 - fht_input[negK]), (fht_input[k] + fht_input[negK]));
    float phase = atan2(realPlusImg - realMinusImg, realPlusImg + realMinusImg);
    // Serial.print("Phase: "); Serial.println(phase);
    if (maxIndex == _old_max_index && maxIndex != 0) {
        float _phaseDiff = normalize_rads(phase - _old_phase);

        // Only update the rate if we are in the same fht bucket.
        _phaseRateAverage = (((_phaseRateAverage * 9) + _phaseDiff ) / 10);
    }
    _old_phase = phase;
    _old_max_index = maxIndex;

    _phase_avg += _phaseRateAverage;
    if (phase + PI < _phase_avg) {
        phase += 2*PI;
    } else if (phase - PI > _phase_avg) {
        phase -= 2*PI;
    }

    _phase_avg = (_phase_avg * 19 + phase) / 20;
    _phase_avg = normalize_rads(_phase_avg + PI) - PI;

    // Serial.print("Phase Rate Avg: "); Serial.println(_phaseRateAverage);
    // Serial.print("Phase Avg: "); Serial.println(_phase_avg);
    //for (int i = 0; i < FHT_N; i++) {
    //	  fht_input[i] = (int) old_fht[0];
    //}
}

float Accel::getPhase() {
    return _phase_avg;
}

float Accel::getPhasePercentage() {
    return (_phase_avg + PI)/(2*PI);
}

long Accel::GetCompassReading()
{
    return _compassReading;
}

bool Accel::isDancing()
{
    return _isDancing;
}

float Accel::getPhaseRatePercentage()
{
    return _phaseRateAverage/(2*PI);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PropertyInfoHash.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 02:23:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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 library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COMPHELPER_PROPERTYINFOHASH_HXX_
#define _COMPHELPER_PROPERTYINFOHASH_HXX_

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COMPHELPER_TYPEGENERATION_HXX_
#include <comphelper/TypeGeneration.hxx>
#endif
#include <hash_map>
namespace comphelper
{
    struct PropertyInfo
    {
        const sal_Char* mpName;
        sal_uInt16 mnNameLen;
        sal_Int32 mnHandle;
        CppuTypes meCppuType;
        sal_Int16 mnAttributes;
        sal_uInt8 mnMemberId;
    };
    struct PropertyData
    {
        sal_uInt8 mnMapId;
        PropertyInfo *mpInfo;
        PropertyData ( sal_uInt8 nMapId, PropertyInfo *pInfo )
        : mnMapId ( nMapId )
        , mpInfo ( pInfo ) {}
    };
    struct eqFunc
    {
        sal_Bool operator()( const rtl::OUString &r1,
                             const rtl::OUString &r2) const
        {
            return r1 == r2;
        }
    };
}

typedef std::hash_map < ::rtl::OUString,
                        ::comphelper::PropertyInfo*,
                        ::rtl::OUStringHash,
                        ::comphelper::eqFunc > PropertyInfoHash;
typedef std::hash_map < ::rtl::OUString,
                        ::comphelper::PropertyData*,
                        ::rtl::OUStringHash,
                        ::comphelper::eqFunc > PropertyDataHash;
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.246); FILE MERGED 2008/04/01 15:05:16 thb 1.2.246.3: #i85898# Stripping all external header guards 2008/04/01 12:26:23 thb 1.2.246.2: #i85898# Stripping all external header guards 2008/03/31 12:19:26 rt 1.2.246.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: PropertyInfoHash.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _COMPHELPER_PROPERTYINFOHASH_HXX_
#define _COMPHELPER_PROPERTYINFOHASH_HXX_

#include <rtl/ustring.hxx>
#include <comphelper/TypeGeneration.hxx>
#include <hash_map>
namespace comphelper
{
    struct PropertyInfo
    {
        const sal_Char* mpName;
        sal_uInt16 mnNameLen;
        sal_Int32 mnHandle;
        CppuTypes meCppuType;
        sal_Int16 mnAttributes;
        sal_uInt8 mnMemberId;
    };
    struct PropertyData
    {
        sal_uInt8 mnMapId;
        PropertyInfo *mpInfo;
        PropertyData ( sal_uInt8 nMapId, PropertyInfo *pInfo )
        : mnMapId ( nMapId )
        , mpInfo ( pInfo ) {}
    };
    struct eqFunc
    {
        sal_Bool operator()( const rtl::OUString &r1,
                             const rtl::OUString &r2) const
        {
            return r1 == r2;
        }
    };
}

typedef std::hash_map < ::rtl::OUString,
                        ::comphelper::PropertyInfo*,
                        ::rtl::OUStringHash,
                        ::comphelper::eqFunc > PropertyInfoHash;
typedef std::hash_map < ::rtl::OUString,
                        ::comphelper::PropertyData*,
                        ::rtl::OUStringHash,
                        ::comphelper::eqFunc > PropertyDataHash;
#endif
<|endoftext|>


<commit_before>#include <ncurses.h>
#include <cstring>
using namespace std;

class Snake;
class Vector;

int main()
{

}

class Vector
{
	public:
		Vector() : x(0), y(0){}
		Vector(int x, int y) {setX(x); setY(y);}

		setX(int x){this->x = x;}
		getX() const {return this->x}
		setY(int y){this->y = y;}
		getY() const {return this->y}

		Vector& operator=(const Vector& vec)
		{setX(vec.getX()); setY(vec.getY()); return *this;}
		Vector& operator+=(const Vector& vec)
		{setX(getX()+vec.getX()); setY(getY()+vec.getY()); return *this;}
		Vector operator+(Vector v, const Vector& vec)
		{return v+=vec; }
		Vector& operator-=(const Vector& vec)
		{setX(getX()-vec.getX()); setY(getY()-vec.getY()); return *this;}
		Vector operator-(Vector v, const Vector& vec)
		{return v-=vec;}

	private:
		int x,y;
};

<commit_msg>Snake class added.<commit_after>#include <ncurses.h>
#include <cstring>
#include <vector>
#include <cstdlib>
#include <ctime>

class Snake;
class Vector;

int main()
{
	//init (Snake, curses)
	//loop
	//{
	////input
	////snake->proces
	////draw<<snake
	////refresh
	//}
}

class Vector
{
	public:
		Vector() : x(0), y(0){}
		Vector(int x, int y) {setX(x); setY(y);}

		setX(int x){this->x = x;}
		getX() const {return this->x}
		setY(int y){this->y = y;}
		getY() const {return this->y}

		Vector& operator=(const Vector& vec)
		{setX(vec.getX()); setY(vec.getY()); return *this;}
		Vector& operator+=(const Vector& vec)
		{setX(getX()+vec.getX()); setY(getY()+vec.getY()); return *this;}
		Vector operator+(Vector v, const Vector& vec)
		{return v+=vec; }
		Vector& operator-=(const Vector& vec)
		{setX(getX()-vec.getX()); setY(getY()-vec.getY()); return *this;}
		Vector operator-(Vector v, const Vector& vec)
		{return v-=vec;}

	private:
		int x,y;
};

class Snake
{
	private:
		std::vector<Vector> body;
		Vector apple;
		Vector direction;
		int points;
		int level;
		int best;
		const int height, width;
		bool exit;
		int speed;
		bool move; //maybe unnecessary, otherwise move buffer
	public:
		Snake(int height, int width, int best)
		: heigth(height), width(width), best(best)
		{	getApple();
			body.push_back(Vector(height/2, width/2));
			setDirection(0);
			exit=false;
			speed=180;
			level=1;
			srand(time(NULL));
		}
};
<|endoftext|>


<commit_before>/**The MIT License (MIT)
*
*Copyright (c) 2016 Dylan
*
*Permission is hereby granted, free of charge, to any person obtaining a copy
*of this software and associated documentation files (the "Software"), to deal
*in the Software without restriction, including without limitation the rights
*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*copies of the Software, and to permit persons to whom the Software is
*furnished to do so, subject to the following conditions:
*
*The above copyright notice and this permission notice shall be included in all
*copies or substantial portions of the Software.
*
*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*SOFTWARE.
*/

#include "../include/solve.hpp"

#include <stdlib.h>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdexcept>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

#include "mkl.h"

#include "../include/simulationdata.hpp"
#include "../include/wavefunction.hpp"
#include "../include/potentialdata.hpp"
#include "../include/solve.hpp"
#include "../include/savedata.hpp"

void calculate_ground_state(SimulationData &sim_data, WaveFunction &psi, PotentialData &pot_data) {

	struct stat sb;
	if (stat("GroundState.fit", &sb) == 0){
		system("rm GroundState.fit");
		std::cout << "GroundState.fit deleted" << std::endl;
	}
	//Create handle and descriptor for the FFT routine
	MKL_LONG status = 0;
	DFTI_DESCRIPTOR_HANDLE handle = 0;
	MKL_LONG N[2]; N[0] = sim_data.get_num_x(); N[1] = sim_data.get_num_y();
	status = DftiCreateDescriptor(&handle, DFTI_DOUBLE, DFTI_COMPLEX, 2, N);
	status = DftiSetValue(handle, DFTI_BACKWARD_SCALE, (1.0 / (N[0] * N[1])));
	status = DftiCommitDescriptor(handle);

	pot_data.assign_momentum_time_evolution(sim_data, psi, false);

	//Time to find the ground state!
	for (int i = 0; i < sim_data.num_imaginary_steps; ++i) {
		if (i%100 == 0) {
			std::cout << "Imaginary step " << i << " of " << sim_data.num_imaginary_steps << std::endl;
		}

		//calculate abs(psi)**2
		psi.calc_abs_psi(sim_data.get_N());
		psi.calculate_norm(sim_data);
		//Calculate nonlinear energy term
		pot_data.calculate_non_linear(sim_data, psi);
		//Assign the position time evolution operator values
		pot_data.assign_position_time_evolution(sim_data, psi, true, false, false);
		//multiply by position operator with t/2
		vzMul(sim_data.get_N(), psi.psi, pot_data.pos_time_evolution, psi.psi);
 		//Perform forward transform and multiply by evolution operator
		status = DftiComputeForward(handle, psi.psi, psi.psi);
		vzMul(sim_data.get_N(), psi.psi, pot_data.mom_time_evolution, psi.psi);
		//Transform back then multiply by other half of position operator
		status = DftiComputeBackward(handle, psi.psi, psi.psi);
	     	vzMul(sim_data.get_N(), psi.psi, pot_data.pos_time_evolution, psi.psi);
	}
	DftiFreeDescriptor(&handle);
	save_fits_image_wavefunction(sim_data, psi, "GroundState.fit");
}

void calculate_time_evolution(SimulationData &sim_data, WaveFunction &psi, PotentialData &pot_data) {

	struct stat sb;
	if (stat("FinalState.fit", &sb) == 0){
		system("rm FinalState.fit");
		std::cout << "FinalState.fit deleted" << std::endl;
	}
	//Create handle and descriptor for the FFT routine
	MKL_LONG status = 0;
	DFTI_DESCRIPTOR_HANDLE handle = 0;
	MKL_LONG N[2]; N[0] = sim_data.get_num_x(); N[1] = sim_data.get_num_y();
	status = DftiCreateDescriptor(&handle, DFTI_DOUBLE, DFTI_COMPLEX, 2, N);
	status = DftiSetValue(handle, DFTI_BACKWARD_SCALE, (1.0 / (N[0] * N[1])));
	status = DftiCommitDescriptor(handle);

	pot_data.assign_momentum_time_evolution(sim_data, psi, true);

	//Time to find the ground state!
	for (int i = 0; i < sim_data.num_imaginary_steps; ++i) {
		//calculate abs(psi)**2
		psi.calc_abs_psi(sim_data.get_N());
		psi.calculate_norm(sim_data);
		if (i%10000 == 0) {
			std::cout << "Real step " << i << " of " << sim_data.num_real_steps << std::endl;
			char buf1[200];
			char buf2[200];
			strcpy(buf1, sim_data.folder);
			sprintf(buf2, "/psi%d.fit\0", i/500);
			strcat(buf1, buf2);
			int length = strlen(buf1);
			char *full_filename;
			full_filename = (char*)mkl_malloc(length*sizeof(char), 64);
			strcpy(full_filename, buf1);
			save_fits_image_wavefunction(sim_data, psi, full_filename);
			mkl_free(full_filename);
		}
		//Calculate nonlinear energy term
		pot_data.calculate_non_linear(sim_data, psi);
		//Assign the position time evolution operator values
		pot_data.assign_position_time_evolution(sim_data, psi, false, false, true);
		//multiply by position operator with t/2
		vzMul(sim_data.get_N(), psi.psi, pot_data.pos_time_evolution, psi.psi);
		//Perform forward transform and multiply by evolution operator
		status = DftiComputeForward(handle, psi.psi, psi.psi);
		vzMul(sim_data.get_N(), psi.psi, pot_data.mom_time_evolution, psi.psi);
		//Transform back then multiply by other half of position operator
		status = DftiComputeBackward(handle, psi.psi, psi.psi);
		vzMul(sim_data.get_N(), psi.psi, pot_data.pos_time_evolution, psi.psi);
	}
	DftiFreeDescriptor(&handle);
	save_fits_image_wavefunction(sim_data, psi, "FinalState.fit");
}
<commit_msg>Fixed mistake with real time steps<commit_after>/**The MIT License (MIT)
*
*Copyright (c) 2016 Dylan
*
*Permission is hereby granted, free of charge, to any person obtaining a copy
*of this software and associated documentation files (the "Software"), to deal
*in the Software without restriction, including without limitation the rights
*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*copies of the Software, and to permit persons to whom the Software is
*furnished to do so, subject to the following conditions:
*
*The above copyright notice and this permission notice shall be included in all
*copies or substantial portions of the Software.
*
*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*SOFTWARE.
*/

#include "../include/solve.hpp"

#include <stdlib.h>
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdexcept>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>

#include "mkl.h"

#include "../include/simulationdata.hpp"
#include "../include/wavefunction.hpp"
#include "../include/potentialdata.hpp"
#include "../include/solve.hpp"
#include "../include/savedata.hpp"

void calculate_ground_state(SimulationData &sim_data, WaveFunction &psi, PotentialData &pot_data) {

	struct stat sb;
	if (stat("GroundState.fit", &sb) == 0){
		system("rm GroundState.fit");
		std::cout << "GroundState.fit deleted" << std::endl;
	}
	//Create handle and descriptor for the FFT routine
	MKL_LONG status = 0;
	DFTI_DESCRIPTOR_HANDLE handle = 0;
	MKL_LONG N[2]; N[0] = sim_data.get_num_x(); N[1] = sim_data.get_num_y();
	status = DftiCreateDescriptor(&handle, DFTI_DOUBLE, DFTI_COMPLEX, 2, N);
	status = DftiSetValue(handle, DFTI_BACKWARD_SCALE, (1.0 / (N[0] * N[1])));
	status = DftiCommitDescriptor(handle);

	pot_data.assign_momentum_time_evolution(sim_data, psi, false);

	//Time to find the ground state!
	for (int i = 0; i < sim_data.num_imaginary_steps; ++i) {
		if (i%100 == 0) {
			std::cout << "Imaginary step " << i << " of " << sim_data.num_imaginary_steps << std::endl;
		}

		//calculate abs(psi)**2
		psi.calc_abs_psi(sim_data.get_N());
		psi.calculate_norm(sim_data);
		//Calculate nonlinear energy term
		pot_data.calculate_non_linear(sim_data, psi);
		//Assign the position time evolution operator values
		pot_data.assign_position_time_evolution(sim_data, psi, true, false, false);
		//multiply by position operator with t/2
		vzMul(sim_data.get_N(), psi.psi, pot_data.pos_time_evolution, psi.psi);
 		//Perform forward transform and multiply by evolution operator
		status = DftiComputeForward(handle, psi.psi, psi.psi);
		vzMul(sim_data.get_N(), psi.psi, pot_data.mom_time_evolution, psi.psi);
		//Transform back then multiply by other half of position operator
		status = DftiComputeBackward(handle, psi.psi, psi.psi);
	     	vzMul(sim_data.get_N(), psi.psi, pot_data.pos_time_evolution, psi.psi);
	}
	DftiFreeDescriptor(&handle);
	save_fits_image_wavefunction(sim_data, psi, "GroundState.fit");
}

void calculate_time_evolution(SimulationData &sim_data, WaveFunction &psi, PotentialData &pot_data) {

	struct stat sb;
	if (stat("FinalState.fit", &sb) == 0){
		system("rm FinalState.fit");
		std::cout << "FinalState.fit deleted" << std::endl;
	}
	//Create handle and descriptor for the FFT routine
	MKL_LONG status = 0;
	DFTI_DESCRIPTOR_HANDLE handle = 0;
	MKL_LONG N[2]; N[0] = sim_data.get_num_x(); N[1] = sim_data.get_num_y();
	status = DftiCreateDescriptor(&handle, DFTI_DOUBLE, DFTI_COMPLEX, 2, N);
	status = DftiSetValue(handle, DFTI_BACKWARD_SCALE, (1.0 / (N[0] * N[1])));
	status = DftiCommitDescriptor(handle);

	pot_data.assign_momentum_time_evolution(sim_data, psi, true);

	//Time to find the ground state!
	for (int i = 0; i < sim_data.num_real_steps; ++i) {
		//calculate abs(psi)**2
		psi.calc_abs_psi(sim_data.get_N());
		psi.calculate_norm(sim_data);
		if (i%10000 == 0) {
			std::cout << "Real step " << i << " of " << sim_data.num_real_steps << std::endl;
			char buf1[200];
			char buf2[200];
			strcpy(buf1, sim_data.folder);
			sprintf(buf2, "/psi%d.fit\0", i/10000);
			strcat(buf1, buf2);
			int length = strlen(buf1);
			char *full_filename;
			full_filename = (char*)mkl_malloc(length*sizeof(char), 64);
			strcpy(full_filename, buf1);
			save_fits_image_wavefunction(sim_data, psi, full_filename);
			mkl_free(full_filename);
		}
		//Calculate nonlinear energy term
		pot_data.calculate_non_linear(sim_data, psi);
		//Assign the position time evolution operator values
		pot_data.assign_position_time_evolution(sim_data, psi, false, false, true);
		//multiply by position operator with t/2
		vzMul(sim_data.get_N(), psi.psi, pot_data.pos_time_evolution, psi.psi);
		//Perform forward transform and multiply by evolution operator
		status = DftiComputeForward(handle, psi.psi, psi.psi);
		vzMul(sim_data.get_N(), psi.psi, pot_data.mom_time_evolution, psi.psi);
		//Transform back then multiply by other half of position operator
		status = DftiComputeBackward(handle, psi.psi, psi.psi);
		vzMul(sim_data.get_N(), psi.psi, pot_data.pos_time_evolution, psi.psi);
	}
	DftiFreeDescriptor(&handle);
	save_fits_image_wavefunction(sim_data, psi, "FinalState.fit");
}
<|endoftext|>


<commit_before>#include <cassert>

namespace Arcv {

template <typename T>
Vec<T>::Vec(const std::initializer_list<T>& list)
  : data(list.size()) {
  auto element = list.begin();

  for (std::size_t i = 0; i < list.size(); ++i, ++element)
    data[i] = *element;
}

template <typename T>
const T Vec<T>::dot(const Vec& vec) const {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  float res = 0.f;
  for (std::size_t i = 0; i < data.size(); ++i)
    res += data[i] * vec.getData()[i];
  return res;
}

template <typename T>
Vec<T> Vec<T>::operator+(Vec vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  vec += *this;
  return vec;
}

template <typename T>
Vec<T> Vec<T>::operator+(float val) {
  Vec<T> res = *this;
  res += val;
  return res;
}

template <typename T>
Vec<T> Vec<T>::operator-(Vec vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  vec -= *this;
  return vec;
}

template <typename T>
Vec<T> Vec<T>::operator-(float val) {
  Vec<T> res = *this;
  res -= val;
  return res;
}

template <typename T>
Vec<T> Vec<T>::operator*(Vec vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  vec *= *this;
  return vec;
}

template <typename T>
Vec<T> Vec<T>::operator*(float val) {
  Vec<T> res = *this;
  res *= val;
  return res;
}

template <typename T>
Vec<T> Vec<T>::operator/(Vec vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  vec /= *this;
  return vec;
}

template <typename T>
Vec<T> Vec<T>::operator/(float val) {
  Vec<T> res = *this;
  res /= val;
  return res;
}

template <typename T>
Vec<T>& Vec<T>::operator+=(const Vec& vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] += vec.getData()[i];
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator+=(float val) {
  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] += val;
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator-=(const Vec& vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] -= vec.getData()[i];
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator-=(float val) {
  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] -= val;
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator*=(const Vec& vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] *= vec.getData()[i];
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator*=(float val) {
  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] *= val;
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator/=(const Vec& vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] /= vec.getData()[i];
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator/=(float val) {
  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] /= val;
  return *this;
}

} // namespace Arcv
<commit_msg>[Update] Operators' loops changed to foreach in vectors<commit_after>#include <cassert>

namespace Arcv {

template <typename T>
Vec<T>::Vec(const std::initializer_list<T>& list)
  : data(list.size()) {
  auto element = list.begin();

  for (std::size_t i = 0; i < list.size(); ++i, ++element)
    data[i] = *element;
}

template <typename T>
const T Vec<T>::dot(const Vec& vec) const {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  float res = 0.f;
  for (std::size_t i = 0; i < data.size(); ++i)
    res += data[i] * vec.getData()[i];
  return res;
}

template <typename T>
Vec<T> Vec<T>::operator+(Vec vec) {
  vec += *this;
  return vec;
}

template <typename T>
Vec<T> Vec<T>::operator+(float val) {
  Vec<T> res = *this;
  res += val;
  return res;
}

template <typename T>
Vec<T> Vec<T>::operator-(Vec vec) {
  vec -= *this;
  return vec;
}

template <typename T>
Vec<T> Vec<T>::operator-(float val) {
  Vec<T> res = *this;
  res -= val;
  return res;
}

template <typename T>
Vec<T> Vec<T>::operator*(Vec vec) {
  vec *= *this;
  return vec;
}

template <typename T>
Vec<T> Vec<T>::operator*(float val) {
  Vec<T> res = *this;
  res *= val;
  return res;
}

template <typename T>
Vec<T> Vec<T>::operator/(Vec vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  vec /= *this;
  return vec;
}

template <typename T>
Vec<T> Vec<T>::operator/(float val) {
  Vec<T> res = *this;
  res /= val;
  return res;
}

template <typename T>
Vec<T>& Vec<T>::operator+=(const Vec& vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] += vec.getData()[i];
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator+=(float val) {
  for (T& it : data)
    it += val;
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator-=(const Vec& vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] -= vec.getData()[i];
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator-=(float val) {
  for (T& it : data)
    it -= val;
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator*=(const Vec& vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] *= vec.getData()[i];
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator*=(float val) {
  for (T& it : data)
    it *= val;
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator/=(const Vec& vec) {
  assert(("Error: Vectors aren't the same size", data.size() == vec.getData().size()));

  for (std::size_t i = 0; i < data.size(); ++i)
    data[i] /= vec.getData()[i];
  return *this;
}

template <typename T>
Vec<T>& Vec<T>::operator/=(float val) {
  for (T& it : data)
    it /= val;
  return *this;
}

} // namespace Arcv
<|endoftext|>


<commit_before>/*
Copyright (c) 2017 InversePalindrome
Nihil - GameOverState.hpp
InversePalindrome.com
*/

#pragma once

#include "State.hpp"

class GameOverState : public State
{
public:
	GameOverState(StateMachine& stateMachine, StateData& stateData);

	virtual void handleEvent(const sf::Event& event) override;
	virtual void update(float deltaTime) override;
	virtual void draw() override;

private:
	virtual bool isTransparent() const override;
};<commit_msg>Delete GameOverState.hpp<commit_after><|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#include "otbWrapperMapProjectionParametersHandler.h"

// Needed for methods relative to projections
#include "otbMapProjections.h"
#include "otbImageToGenericRSOutputParameters.h"

namespace otb
{
namespace Wrapper
{

void MapProjectionParametersHandler::AddMapProjectionParameters( Application::Pointer app, const std::string & key)
{
  app->AddParameter(ParameterType_Choice, key, "Output Cartographic Map Projection");
  app->SetParameterDescription(key,"Parameters of the ouptut map projection to be used.");

  // utm
  std::ostringstream oss;
  oss << key<<".utm";
  app->AddChoice(oss.str(),   "Universal Trans-Mercator (UTM)");
  app->SetParameterDescription(oss.str(),"A system of transverse mercator projections dividing the surface of Earth between 80S and 84N latitude.");

  oss << ".zone";
  app->AddParameter(ParameterType_Int, oss.str(), "Zone number");
  app->SetParameterDescription(oss.str(),"The zone number ranges from 1 to 60 and allows to define the transverse mercator projection (along with the hemisphere)");
  app->SetMinimumParameterIntValue(oss.str(), 1);

  oss.str("");
  oss <<key<<".utm" <<".northhem";
  app->AddParameter(ParameterType_Empty, oss.str(),  "Northern Hemisphere");
  app->SetParameterDescription(oss.str(),"The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.");

  // lambert2
  oss.str("");
  oss << key<<".lambert2";
  app->AddChoice(oss.str(),  "Lambert II Etendu");
  app->SetParameterDescription(oss.str(),"This is a Lambert Conformal Conic projection mainly used in France.");

  // lambert93
  oss.str("");
  oss << key<<".lambert93";
  app->AddChoice(oss.str(),  "Lambert93");
  app->SetParameterDescription(oss.str(), "This is a Lambert 93 projection mainly used in France.");

  // Transmercator
  oss.str("");
  oss << key<<".transmercator";
  app->AddChoice(oss.str(),  "Transmercator");
  app->SetParameterDescription(oss.str(),
                               "This is a Transverse Mercator, a cylindrical projection widely used. The required values are set by default.");

  std::ostringstream subParamKey;
  subParamKey<<oss.str()<<".falseeasting";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "False easting");
  app->SetParameterDescription( subParamKey.str(), " Transmercator false easting value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 0.);

  subParamKey.str("");
  subParamKey<<oss.str()<<".falsenorthing";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "False northing");
  app->SetParameterDescription(subParamKey.str(), " Transmercator false northing value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 0.);

  subParamKey.str("");
  subParamKey<<oss.str()<<".scale";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "Scale factor");
  app->SetParameterDescription(subParamKey.str(), " Transmercator scale factor value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 1.);

  // wgs84
  oss.str("");
  oss << key<<".wgs";
  app->AddChoice(oss.str(),  "WGS 84");
  app->SetParameterDescription(oss.str(),"This is a Geographical projection");

  // epsg code
  oss.str("");
  oss<<key<<".epsg";
  app->AddChoice(oss.str(),"EPSG Code");
  app->SetParameterDescription(oss.str(),
                               "This code is a generic way of identifying map projections, and allows to specify a large amount of them. See www.spatialreference.org to find which EPSG code is associated to your projection;");

  oss <<".code";
  app->AddParameter(ParameterType_Int, oss.str(), "EPSG Code");
  app->SetParameterDescription(oss.str(),"See www.spatialreference.org to find which EPSG code is associated to your projection");
  app->SetDefaultParameterInt(oss.str(), 32631);

  app->SetParameterString(key, "epsg");
}

/**
    * Helper method : Compute the ProjectionRef knowing the map
    * projection picked up by the user
    *
    */
const std::string MapProjectionParametersHandler::GetProjectionRefFromChoice(const Application::Pointer app,
                                                                   const std::string & key)
{
  std::ostringstream zoneKey;
  zoneKey << key<<".utm.zone";

  std::ostringstream hemKey;
  hemKey << key<<".utm.northhem";

  std::ostringstream  epsgKey;
  epsgKey << key <<".epsg.code";

  // Get the user choice
  switch ( app->GetParameterInt(key) )
    {
    case Map_Utm:
    {
    typedef UtmInverseProjection  UtmProjectionType;
    UtmProjectionType::Pointer    utmProjection = UtmProjectionType::New();

    // Set the zone
    utmProjection->SetZone(app->GetParameterInt(zoneKey.str()));

    // Set the hem
    char hem = 'N';
    if (!app->IsParameterEnabled(hemKey.str()))
      hem = 'S';
    utmProjection->SetHemisphere(hem);

    // Get the projection ref
    return utmProjection->GetWkt();
    }
    break;
    case Map_Lambert2:
    {
    typedef Lambert2EtenduForwardProjection Lambert2ProjectionType;
    Lambert2ProjectionType::Pointer lambert2Projection = Lambert2ProjectionType::New();
    return lambert2Projection->GetWkt();
    }
    break;
    case Map_Lambert93:
    {
    typedef otb::Lambert93InverseProjection Lambert93ProjectionType;
    Lambert93ProjectionType::Pointer lambert93Projection = Lambert93ProjectionType::New();
    return lambert93Projection->GetWkt();
    }
    break;
    case Map_Transmercator:
    {
    typedef otb::TransMercatorInverseProjection TransMercatorProjectionType;
    TransMercatorProjectionType::Pointer transMercatorProjection = TransMercatorProjectionType::New();

    // Get the Transmercator parameters
    std::ostringstream falseeasting;
    std::ostringstream falsenorthing;
    std::ostringstream scale;

    falseeasting  <<key <<".transmercator.falseeasting";
    falsenorthing <<key <<".transmercator.falsenorthing";
    scale         <<key <<".transmercator.scale";

    transMercatorProjection->SetParameters(app->GetParameterFloat( falseeasting.str() ),
                                           app->GetParameterFloat( falsenorthing.str() ),
                                           app->GetParameterFloat( scale.str()) );
    return transMercatorProjection->GetWkt();
    }
    break;
    case Map_WGS84:
    {
    return otb::GeoInformationConversion::ToWKT(4326);
    }
    break;
    case Map_Epsg:
    {
    return otb::GeoInformationConversion::ToWKT(app->GetParameterInt(epsgKey.str()));
    }
    break;
    }

  return "";
}

/**
    * Helper method : Compute the UTM paramaters relative to an image Origin
    * Note: The key of the image must be set to be able to get the image.
    *       The key must be totally if the InputImageParameter belongs
    *       to a ParamaterGroup, ie set io.in
    */
void MapProjectionParametersHandler::InitializeUTMParameters(Application::Pointer app,
                                                   const std::string & imageKey,
                                                   const std::string & mapKey )
{
  // Get the UTM params keys
  std::ostringstream zoneKey;
  zoneKey << mapKey<<".utm.zone";

  std::ostringstream hemKey;
  hemKey << mapKey<<".utm.northhem";

  // Compute the zone and the hemisphere if not UserValue defined
  if(!app->HasUserValue(zoneKey.str())
     && app->HasValue(imageKey)
     && !app->HasAutomaticValue(zoneKey.str()))
    {
    // Compute the Origin lat/long coordinate
    typedef otb::ImageToGenericRSOutputParameters<FloatVectorImageType> OutputParametersEstimatorType;
    OutputParametersEstimatorType::Pointer genericRSEstimator = OutputParametersEstimatorType::New();
    genericRSEstimator->SetInput(app->GetParameterImage(imageKey));
    genericRSEstimator->SetOutputProjectionRef(otb::GeoInformationConversion::ToWKT(4326));
    genericRSEstimator->Compute();

    int zone = otb::Utils::GetZoneFromGeoPoint(genericRSEstimator->GetOutputOrigin()[0],
                                               genericRSEstimator->GetOutputOrigin()[1]);
    // Update the UTM Gui fields
    app->SetParameterInt(zoneKey.str(), zone);
    if(genericRSEstimator->GetOutputOrigin()[0] > 0.)
      {
      app->EnableParameter(hemKey.str());
      }

    app->AutomaticValueOn(zoneKey.str());
    app->AutomaticValueOn(hemKey.str());
    }
}

}// End namespace Wrapper
}// End namespace otb
<commit_msg>[BUG] resolve problem with computation of UTM hemisphere when we initialize app UTM parameters<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#include "otbWrapperMapProjectionParametersHandler.h"

// Needed for methods relative to projections
#include "otbMapProjections.h"
#include "otbImageToGenericRSOutputParameters.h"

namespace otb
{
namespace Wrapper
{

void MapProjectionParametersHandler::AddMapProjectionParameters( Application::Pointer app, const std::string & key)
{
  app->AddParameter(ParameterType_Choice, key, "Output Cartographic Map Projection");
  app->SetParameterDescription(key,"Parameters of the ouptut map projection to be used.");

  // utm
  std::ostringstream oss;
  oss << key<<".utm";
  app->AddChoice(oss.str(),   "Universal Trans-Mercator (UTM)");
  app->SetParameterDescription(oss.str(),"A system of transverse mercator projections dividing the surface of Earth between 80S and 84N latitude.");

  oss << ".zone";
  app->AddParameter(ParameterType_Int, oss.str(), "Zone number");
  app->SetParameterDescription(oss.str(),"The zone number ranges from 1 to 60 and allows to define the transverse mercator projection (along with the hemisphere)");
  app->SetMinimumParameterIntValue(oss.str(), 1);

  oss.str("");
  oss <<key<<".utm" <<".northhem";
  app->AddParameter(ParameterType_Empty, oss.str(),  "Northern Hemisphere");
  app->SetParameterDescription(oss.str(),"The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.");

  // lambert2
  oss.str("");
  oss << key<<".lambert2";
  app->AddChoice(oss.str(),  "Lambert II Etendu");
  app->SetParameterDescription(oss.str(),"This is a Lambert Conformal Conic projection mainly used in France.");

  // lambert93
  oss.str("");
  oss << key<<".lambert93";
  app->AddChoice(oss.str(),  "Lambert93");
  app->SetParameterDescription(oss.str(), "This is a Lambert 93 projection mainly used in France.");

  // Transmercator
  oss.str("");
  oss << key<<".transmercator";
  app->AddChoice(oss.str(),  "Transmercator");
  app->SetParameterDescription(oss.str(),
                               "This is a Transverse Mercator, a cylindrical projection widely used. The required values are set by default.");

  std::ostringstream subParamKey;
  subParamKey<<oss.str()<<".falseeasting";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "False easting");
  app->SetParameterDescription( subParamKey.str(), " Transmercator false easting value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 0.);

  subParamKey.str("");
  subParamKey<<oss.str()<<".falsenorthing";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "False northing");
  app->SetParameterDescription(subParamKey.str(), " Transmercator false northing value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 0.);

  subParamKey.str("");
  subParamKey<<oss.str()<<".scale";
  app->AddParameter(ParameterType_Float, subParamKey.str(), "Scale factor");
  app->SetParameterDescription(subParamKey.str(), " Transmercator scale factor value.");
  app->SetDefaultParameterFloat(subParamKey.str(), 1.);

  // wgs84
  oss.str("");
  oss << key<<".wgs";
  app->AddChoice(oss.str(),  "WGS 84");
  app->SetParameterDescription(oss.str(),"This is a Geographical projection");

  // epsg code
  oss.str("");
  oss<<key<<".epsg";
  app->AddChoice(oss.str(),"EPSG Code");
  app->SetParameterDescription(oss.str(),
                               "This code is a generic way of identifying map projections, and allows to specify a large amount of them. See www.spatialreference.org to find which EPSG code is associated to your projection;");

  oss <<".code";
  app->AddParameter(ParameterType_Int, oss.str(), "EPSG Code");
  app->SetParameterDescription(oss.str(),"See www.spatialreference.org to find which EPSG code is associated to your projection");
  app->SetDefaultParameterInt(oss.str(), 32631);

  app->SetParameterString(key, "epsg");
}

/**
    * Helper method : Compute the ProjectionRef knowing the map
    * projection picked up by the user
    *
    */
const std::string MapProjectionParametersHandler::GetProjectionRefFromChoice(const Application::Pointer app,
                                                                   const std::string & key)
{
  std::ostringstream zoneKey;
  zoneKey << key<<".utm.zone";

  std::ostringstream hemKey;
  hemKey << key<<".utm.northhem";

  std::ostringstream  epsgKey;
  epsgKey << key <<".epsg.code";

  // Get the user choice
  switch ( app->GetParameterInt(key) )
    {
    case Map_Utm:
    {
    typedef UtmInverseProjection  UtmProjectionType;
    UtmProjectionType::Pointer    utmProjection = UtmProjectionType::New();

    // Set the zone
    utmProjection->SetZone(app->GetParameterInt(zoneKey.str()));

    // Set the hem
    char hem = 'N';
    if (!app->IsParameterEnabled(hemKey.str()))
      hem = 'S';
    utmProjection->SetHemisphere(hem);

    // Get the projection ref
    return utmProjection->GetWkt();
    }
    break;
    case Map_Lambert2:
    {
    typedef Lambert2EtenduForwardProjection Lambert2ProjectionType;
    Lambert2ProjectionType::Pointer lambert2Projection = Lambert2ProjectionType::New();
    return lambert2Projection->GetWkt();
    }
    break;
    case Map_Lambert93:
    {
    typedef otb::Lambert93InverseProjection Lambert93ProjectionType;
    Lambert93ProjectionType::Pointer lambert93Projection = Lambert93ProjectionType::New();
    return lambert93Projection->GetWkt();
    }
    break;
    case Map_Transmercator:
    {
    typedef otb::TransMercatorInverseProjection TransMercatorProjectionType;
    TransMercatorProjectionType::Pointer transMercatorProjection = TransMercatorProjectionType::New();

    // Get the Transmercator parameters
    std::ostringstream falseeasting;
    std::ostringstream falsenorthing;
    std::ostringstream scale;

    falseeasting  <<key <<".transmercator.falseeasting";
    falsenorthing <<key <<".transmercator.falsenorthing";
    scale         <<key <<".transmercator.scale";

    transMercatorProjection->SetParameters(app->GetParameterFloat( falseeasting.str() ),
                                           app->GetParameterFloat( falsenorthing.str() ),
                                           app->GetParameterFloat( scale.str()) );
    return transMercatorProjection->GetWkt();
    }
    break;
    case Map_WGS84:
    {
    return otb::GeoInformationConversion::ToWKT(4326);
    }
    break;
    case Map_Epsg:
    {
    return otb::GeoInformationConversion::ToWKT(app->GetParameterInt(epsgKey.str()));
    }
    break;
    }

  return "";
}

/**
    * Helper method : Compute the UTM paramaters relative to an image Origin
    * Note: The key of the image must be set to be able to get the image.
    *       The key must be totally if the InputImageParameter belongs
    *       to a ParamaterGroup, ie set io.in
    */
void MapProjectionParametersHandler::InitializeUTMParameters(Application::Pointer app,
                                                   const std::string & imageKey,
                                                   const std::string & mapKey )
{
  // Get the UTM params keys
  std::ostringstream zoneKey;
  zoneKey << mapKey<<".utm.zone";

  std::ostringstream hemKey;
  hemKey << mapKey<<".utm.northhem";

  // Compute the zone and the hemisphere if not UserValue defined
  if(!app->HasUserValue(zoneKey.str())
     && app->HasValue(imageKey)
     && !app->HasAutomaticValue(zoneKey.str()))
    {
    // Compute the Origin lat/long coordinate
    typedef otb::ImageToGenericRSOutputParameters<FloatVectorImageType> OutputParametersEstimatorType;
    OutputParametersEstimatorType::Pointer genericRSEstimator = OutputParametersEstimatorType::New();

    genericRSEstimator->SetInput(app->GetParameterImage(imageKey));
    genericRSEstimator->SetOutputProjectionRef(otb::GeoInformationConversion::ToWKT(4326));
    genericRSEstimator->Compute();

    int zone = otb::Utils::GetZoneFromGeoPoint(genericRSEstimator->GetOutputOrigin()[0],
                                               genericRSEstimator->GetOutputOrigin()[1]);
    // Update the UTM Gui fields
    app->SetParameterInt(zoneKey.str(), zone);
    if(genericRSEstimator->GetOutputOrigin()[1] > 0.)
      {
      app->EnableParameter(hemKey.str());
      }

    app->AutomaticValueOn(zoneKey.str());
    app->AutomaticValueOn(hemKey.str());
    }
}

}// End namespace Wrapper
}// End namespace otb
<|endoftext|>


<commit_before>/***********************************************************************
 Moses - factored phrase-based language decoder
 Copyright (C) 2010 Hieu Hoang

 This library 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 library 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 library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ***********************************************************************/

#include <algorithm>
#include <iostream>
#include <vector>
#include "StaticData.h"
#include "ChartTranslationOptionList.h"
#include "ChartTranslationOptions.h"
#include "ChartCellCollection.h"
#include "WordsRange.h"
#include "InputType.h"
#include "InputPath.h"

using namespace std;

namespace Moses
{

ChartTranslationOptionList::ChartTranslationOptionList(size_t ruleLimit, const InputType &input)
  : m_size(0)
  , m_ruleLimit(ruleLimit)
{
  m_scoreThreshold = std::numeric_limits<float>::infinity();
}

ChartTranslationOptionList::~ChartTranslationOptionList()
{
  RemoveAllInColl(m_collection);
}

void ChartTranslationOptionList::Clear()
{
  m_size = 0;
  m_scoreThreshold = std::numeric_limits<float>::infinity();
}

class ChartTranslationOptionOrderer
{
public:
  bool operator()(const ChartTranslationOptions* itemA, const ChartTranslationOptions* itemB) const {
    return itemA->GetEstimateOfBestScore() > itemB->GetEstimateOfBestScore();
  }
};

void ChartTranslationOptionList::Add(const TargetPhraseCollection &tpc,
                                     const StackVec &stackVec,
                                     const WordsRange &range)
{
  if (tpc.IsEmpty()) {
    return;
  }

  for (size_t i = 0; i < stackVec.size(); ++i) {
    const ChartCellLabel &chartCellLabel = *stackVec[i];
    size_t numHypos = chartCellLabel.GetStack().cube->size();
    if (numHypos == 0) {
      return; // empty stack. These rules can't be used
    }
  }

  const TargetPhrase &targetPhrase = **(tpc.begin());
  float score = targetPhrase.GetFutureScore();
  for (StackVec::const_iterator p = stackVec.begin(); p != stackVec.end(); ++p) {
    score += (*p)->GetBestScore(this);
  }

  // If the rule limit has already been reached then don't add the option
  // unless it is better than at least one existing option.
  if (m_size > m_ruleLimit && score < m_scoreThreshold) {
    return;
  }

  // Add the option to the list.
  if (m_size == m_collection.size()) {
    // m_collection has reached capacity: create a new object.
    m_collection.push_back(new ChartTranslationOptions(tpc, stackVec,
                           range, score));
  } else {
    // Overwrite an unused object.
    *(m_collection[m_size]) = ChartTranslationOptions(tpc, stackVec,
                              range, score);
  }
  ++m_size;

  // If the rule limit hasn't been exceeded then update the threshold.
  if (m_size <= m_ruleLimit) {
    m_scoreThreshold = (score < m_scoreThreshold) ? score : m_scoreThreshold;
  }

  // Prune if bursting
  if (m_size == m_ruleLimit * 2) {
	NTH_ELEMENT4(m_collection.begin(),
                     m_collection.begin() + m_ruleLimit - 1,
                     m_collection.begin() + m_size,
                     ChartTranslationOptionOrderer());
    m_scoreThreshold = m_collection[m_ruleLimit-1]->GetEstimateOfBestScore();
    m_size = m_ruleLimit;
  }
}

void ChartTranslationOptionList::AddPhraseOOV(TargetPhrase &phrase, std::list<TargetPhraseCollection*> &waste_memory, const WordsRange &range)
{
  TargetPhraseCollection *tpc = new TargetPhraseCollection();
  tpc->Add(&phrase);
  waste_memory.push_back(tpc);
  StackVec empty;
  Add(*tpc, empty, range);
}

void ChartTranslationOptionList::ApplyThreshold()
{
  if (m_size > m_ruleLimit) {
    // Something's gone wrong if the list has grown to m_ruleLimit * 2
    // without being pruned.
    assert(m_size < m_ruleLimit * 2);
    // Reduce the list to the best m_ruleLimit options.  The remaining
    // options can be overwritten on subsequent calls to Add().
    NTH_ELEMENT4(m_collection.begin(),
                     m_collection.begin()+m_ruleLimit,
                     m_collection.begin()+m_size,
                     ChartTranslationOptionOrderer());
    m_size = m_ruleLimit;
  }

  // keep only those over best + threshold

  float scoreThreshold = -std::numeric_limits<float>::infinity();

  CollType::const_iterator iter;
  for (iter = m_collection.begin(); iter != m_collection.begin()+m_size; ++iter) {
    const ChartTranslationOptions *transOpt = *iter;
    float score = transOpt->GetEstimateOfBestScore();
    scoreThreshold = (score > scoreThreshold) ? score : scoreThreshold;
  }

  scoreThreshold += StaticData::Instance().GetTranslationOptionThreshold();

  CollType::iterator bound = std::partition(m_collection.begin(),
                             m_collection.begin()+m_size,
                             ScoreThresholdPred(scoreThreshold));

  m_size = std::distance(m_collection.begin(), bound);
}

float ChartTranslationOptionList::GetBestScore(const ChartCellLabel *chartCell) const
{
    const HypoList *stack = chartCell->GetStack().cube;
    assert(stack);
    assert(!stack->empty());
	const ChartHypothesis &bestHypo = **(stack->begin());
	return bestHypo.GetTotalScore();
}

void ChartTranslationOptionList::Evaluate(const InputType &input, const InputPath &inputPath)
{
  // NEVER iterate over ALL of the collection. Just over the first m_size
  CollType::iterator iter;
  for (iter = m_collection.begin(); iter != m_collection.begin() + m_size; ++iter) {
    ChartTranslationOptions &transOpts = **iter;
    transOpts.Evaluate(input, inputPath);
  }

  // get rid of empty trans opts
  size_t numDiscard = 0;
  for (size_t i = 0; i < m_size; ++i) {
    ChartTranslationOptions *transOpts = m_collection[i];
    if (transOpts->GetSize() == 0) {
    	//delete transOpts;
      	++numDiscard;
    }
    else if (numDiscard) {
    	SwapTranslationOptions(i - numDiscard, i);
    	//m_collection[] = transOpts;
    }
  }

  size_t newSize = m_size - numDiscard;
  m_size = newSize;
}

void ChartTranslationOptionList::SwapTranslationOptions(size_t a, size_t b)
{
  ChartTranslationOptions *transOptsA = m_collection[a];
  ChartTranslationOptions *transOptsB = m_collection[b];
  m_collection[a] = transOptsB;
  m_collection[b] = transOptsA;
}

std::ostream& operator<<(std::ostream &out, const ChartTranslationOptionList &obj)
{
	for (size_t i = 0; i < obj.m_collection.size(); ++i) {
		const ChartTranslationOptions &transOpts = *obj.m_collection[i];
		out << transOpts << endl;
	}
	return out;
}

}
<commit_msg>rule-limit=0: unlimited<commit_after>/***********************************************************************
 Moses - factored phrase-based language decoder
 Copyright (C) 2010 Hieu Hoang

 This library 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 library 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 library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ***********************************************************************/

#include <algorithm>
#include <iostream>
#include <vector>
#include "StaticData.h"
#include "ChartTranslationOptionList.h"
#include "ChartTranslationOptions.h"
#include "ChartCellCollection.h"
#include "WordsRange.h"
#include "InputType.h"
#include "InputPath.h"

using namespace std;

namespace Moses
{

ChartTranslationOptionList::ChartTranslationOptionList(size_t ruleLimit, const InputType &input)
  : m_size(0)
  , m_ruleLimit(ruleLimit)
{
  m_scoreThreshold = std::numeric_limits<float>::infinity();
}

ChartTranslationOptionList::~ChartTranslationOptionList()
{
  RemoveAllInColl(m_collection);
}

void ChartTranslationOptionList::Clear()
{
  m_size = 0;
  m_scoreThreshold = std::numeric_limits<float>::infinity();
}

class ChartTranslationOptionOrderer
{
public:
  bool operator()(const ChartTranslationOptions* itemA, const ChartTranslationOptions* itemB) const {
    return itemA->GetEstimateOfBestScore() > itemB->GetEstimateOfBestScore();
  }
};

void ChartTranslationOptionList::Add(const TargetPhraseCollection &tpc,
                                     const StackVec &stackVec,
                                     const WordsRange &range)
{
  if (tpc.IsEmpty()) {
    return;
  }

  for (size_t i = 0; i < stackVec.size(); ++i) {
    const ChartCellLabel &chartCellLabel = *stackVec[i];
    size_t numHypos = chartCellLabel.GetStack().cube->size();
    if (numHypos == 0) {
      return; // empty stack. These rules can't be used
    }
  }

  const TargetPhrase &targetPhrase = **(tpc.begin());
  float score = targetPhrase.GetFutureScore();
  for (StackVec::const_iterator p = stackVec.begin(); p != stackVec.end(); ++p) {
    score += (*p)->GetBestScore(this);
  }

  // If the rule limit has already been reached then don't add the option
  // unless it is better than at least one existing option.
  if (m_ruleLimit && m_size > m_ruleLimit && score < m_scoreThreshold) {
    return;
  }

  // Add the option to the list.
  if (m_size == m_collection.size()) {
    // m_collection has reached capacity: create a new object.
    m_collection.push_back(new ChartTranslationOptions(tpc, stackVec,
                           range, score));
  } else {
    // Overwrite an unused object.
    *(m_collection[m_size]) = ChartTranslationOptions(tpc, stackVec,
                              range, score);
  }
  ++m_size;

  // If the rule limit hasn't been exceeded then update the threshold.
  if (!m_ruleLimit || m_size <= m_ruleLimit) {
    m_scoreThreshold = (score < m_scoreThreshold) ? score : m_scoreThreshold;
  }

  // Prune if bursting
  if (m_ruleLimit && m_size == m_ruleLimit * 2) {
	NTH_ELEMENT4(m_collection.begin(),
                     m_collection.begin() + m_ruleLimit - 1,
                     m_collection.begin() + m_size,
                     ChartTranslationOptionOrderer());
    m_scoreThreshold = m_collection[m_ruleLimit-1]->GetEstimateOfBestScore();
    m_size = m_ruleLimit;
  }
}

void ChartTranslationOptionList::AddPhraseOOV(TargetPhrase &phrase, std::list<TargetPhraseCollection*> &waste_memory, const WordsRange &range)
{
  TargetPhraseCollection *tpc = new TargetPhraseCollection();
  tpc->Add(&phrase);
  waste_memory.push_back(tpc);
  StackVec empty;
  Add(*tpc, empty, range);
}

void ChartTranslationOptionList::ApplyThreshold()
{
  if (m_ruleLimit && m_size > m_ruleLimit) {
    // Something's gone wrong if the list has grown to m_ruleLimit * 2
    // without being pruned.
    assert(m_size < m_ruleLimit * 2);
    // Reduce the list to the best m_ruleLimit options.  The remaining
    // options can be overwritten on subsequent calls to Add().
    NTH_ELEMENT4(m_collection.begin(),
                     m_collection.begin()+m_ruleLimit,
                     m_collection.begin()+m_size,
                     ChartTranslationOptionOrderer());
    m_size = m_ruleLimit;
  }

  // keep only those over best + threshold

  float scoreThreshold = -std::numeric_limits<float>::infinity();

  CollType::const_iterator iter;
  for (iter = m_collection.begin(); iter != m_collection.begin()+m_size; ++iter) {
    const ChartTranslationOptions *transOpt = *iter;
    float score = transOpt->GetEstimateOfBestScore();
    scoreThreshold = (score > scoreThreshold) ? score : scoreThreshold;
  }

  scoreThreshold += StaticData::Instance().GetTranslationOptionThreshold();

  CollType::iterator bound = std::partition(m_collection.begin(),
                             m_collection.begin()+m_size,
                             ScoreThresholdPred(scoreThreshold));

  m_size = std::distance(m_collection.begin(), bound);
}

float ChartTranslationOptionList::GetBestScore(const ChartCellLabel *chartCell) const
{
    const HypoList *stack = chartCell->GetStack().cube;
    assert(stack);
    assert(!stack->empty());
	const ChartHypothesis &bestHypo = **(stack->begin());
	return bestHypo.GetTotalScore();
}

void ChartTranslationOptionList::Evaluate(const InputType &input, const InputPath &inputPath)
{
  // NEVER iterate over ALL of the collection. Just over the first m_size
  CollType::iterator iter;
  for (iter = m_collection.begin(); iter != m_collection.begin() + m_size; ++iter) {
    ChartTranslationOptions &transOpts = **iter;
    transOpts.Evaluate(input, inputPath);
  }

  // get rid of empty trans opts
  size_t numDiscard = 0;
  for (size_t i = 0; i < m_size; ++i) {
    ChartTranslationOptions *transOpts = m_collection[i];
    if (transOpts->GetSize() == 0) {
    	//delete transOpts;
      	++numDiscard;
    }
    else if (numDiscard) {
    	SwapTranslationOptions(i - numDiscard, i);
    	//m_collection[] = transOpts;
    }
  }

  size_t newSize = m_size - numDiscard;
  m_size = newSize;
}

void ChartTranslationOptionList::SwapTranslationOptions(size_t a, size_t b)
{
  ChartTranslationOptions *transOptsA = m_collection[a];
  ChartTranslationOptions *transOptsB = m_collection[b];
  m_collection[a] = transOptsB;
  m_collection[b] = transOptsA;
}

std::ostream& operator<<(std::ostream &out, const ChartTranslationOptionList &obj)
{
	for (size_t i = 0; i < obj.m_collection.size(); ++i) {
		const ChartTranslationOptions &transOpts = *obj.m_collection[i];
		out << transOpts << endl;
	}
	return out;
}

}
<|endoftext|>


<commit_before>#include "include/uuid_admin.h"
#include <iostream>
#include <assert.h>
#include <string>
#include <string.h>

int main()
{
  //Initialize the UUID Admin
  uuidAdmin uuid;

  //Generate a UUID
  std::string id_str;
  try {
    id_str = ua->generate();
  }
  catch (UuidSecurityException& ue) {
    //Continue and print the security error
    std::cout << "UUID Security Exception" << std::endl;
    std::cout << ue.what() << std::endl;
  }
  assert ( !id_str.empty() );
  std::cout << id_str << std::endl;

}
<commit_msg>Test Scripts fixes<commit_after>#include "include/uuid_admin.h"
#include <iostream>
#include <assert.h>
#include <string>
#include <string.h>

int main()
{
  //Initialize the UUID Admin
  uuidAdmin uuid;

  //Generate a UUID
  std::string id_str;
  try {
    id_str = uuid->generate();
  }
  catch (UuidSecurityException& ue) {
    //Continue and print the security error
    std::cout << "UUID Security Exception" << std::endl;
    std::cout << ue.what() << std::endl;
  }
  assert ( !id_str.empty() );
  std::cout << id_str << std::endl;

}
<|endoftext|>


<commit_before>#ifndef SILICIUM_THREAD_HPP
#define SILICIUM_THREAD_HPP

#include <silicium/observer.hpp>
#include <silicium/override.hpp>
#include <silicium/config.hpp>
#include <silicium/exchange.hpp>
#include <silicium/yield_context.hpp>
#include <future>
#include <boost/thread/future.hpp>
#include <boost/optional.hpp>

namespace Si
{
	template <class Element, class ThreadingAPI>
	struct thread_observable
	{
		typedef Element element_type;

		thread_observable()
		{
		}

		template <class Action>
		explicit thread_observable(Action &&action)
			: state(make_unique<movable_state>(std::forward<Action>(action)))
		{
		}

		void wait()
		{
			assert(state);
			state->thread.get();
		}

		void async_get_one(observer<element_type> &receiver)
		{
			assert(state);
			typename ThreadingAPI::unique_lock lock(state->result_mutex);
			assert(!state->receiver_);
			state->receiver_ = &receiver;
			if (!state->cached_result)
			{
				if (!state->thread.valid())
				{
					lock.unlock();
					return Si::exchange(state->receiver_, nullptr)->ended();
				}
				return;
			}
			auto ready_result = std::move(*state->cached_result);
			state->result_retrieved.notify_one();
			lock.unlock();
			Si::exchange(state->receiver_, nullptr)->got_element(std::move(ready_result));
		}

		void cancel()
		{
			throw std::logic_error("to do");
		}

	private:

		struct movable_state : private detail::yield_context_impl<Element>
		{
			typename ThreadingAPI::template future<void> thread;
			typename ThreadingAPI::mutex result_mutex;
			typename ThreadingAPI::condition_variable result_retrieved;
			observer<element_type> *receiver_ = nullptr;
			boost::optional<Element> cached_result;

			template <class Action>
			explicit movable_state(Action &&action)
			{
				//start the background thread after the initialization of all the members
				thread = ThreadingAPI::template launch_async([this, action]() -> void
				{
					yield_context<Element> yield(*this);
					action(yield);
				});
			}

			virtual void push_result(Element result) SILICIUM_OVERRIDE
			{
				typename ThreadingAPI::unique_lock lock(result_mutex);
				while (cached_result.is_initialized())
				{
					result_retrieved.wait(lock);
				}
				if (receiver_)
				{
					auto receiver = Si::exchange(receiver_, nullptr);
					lock.unlock();
					receiver->got_element(std::move(result));
				}
				else
				{
					cached_result = std::move(result);
				}
			}

			virtual void get_one(observable<nothing> &target) SILICIUM_OVERRIDE
			{
				boost::ignore_unused(target);
				throw std::logic_error("todo");
			}
		};

		std::unique_ptr<movable_state> state;
	};

	struct std_threading
	{
		template <class T>
		using future = std::future<T>;
		using mutex = std::mutex;
		using condition_variable = std::condition_variable;
		using unique_lock = std::unique_lock<std::mutex>;
		template <class Action, class ...Args>
		static auto launch_async(Action &&action, Args &&...args) -> std::future<decltype(action(std::forward<Args>(args)...))>
		{
			return std::async(std::launch::async, std::forward<Action>(action), std::forward<Args>(args)...);
		}
	};

	struct boost_threading
	{
		template <class T>
		using future = boost::unique_future<T>;
		using mutex = boost::mutex;
		using condition_variable = boost::condition_variable;
		using unique_lock = boost::unique_lock<boost::mutex>;
		template <class Action, class ...Args>
		static auto launch_async(Action &&action, Args &&...args) -> boost::unique_future<decltype(action(std::forward<Args>(args)...))>
		{
			return boost::async(boost::launch::async, std::forward<Action>(action), std::forward<Args>(args)...);
		}
	};

	template <class Element, class ThreadingAPI, class Action>
	auto make_thread(Action &&action) -> thread_observable<Element, ThreadingAPI>
	{
		return thread_observable<Element, ThreadingAPI>(std::forward<Action>(action));
	}
}

#endif
<commit_msg>fix compilation with Boost 1.55<commit_after>#ifndef SILICIUM_THREAD_HPP
#define SILICIUM_THREAD_HPP

#include <silicium/observer.hpp>
#include <silicium/override.hpp>
#include <silicium/config.hpp>
#include <silicium/exchange.hpp>
#include <silicium/yield_context.hpp>
#include <future>
#include <boost/thread/future.hpp>
#include <boost/optional.hpp>
#include <boost/utility.hpp>

namespace Si
{
	template <class Element, class ThreadingAPI>
	struct thread_observable
	{
		typedef Element element_type;

		thread_observable()
		{
		}

		template <class Action>
		explicit thread_observable(Action &&action)
			: state(make_unique<movable_state>(std::forward<Action>(action)))
		{
		}

		void wait()
		{
			assert(state);
			state->thread.get();
		}

		void async_get_one(observer<element_type> &receiver)
		{
			assert(state);
			typename ThreadingAPI::unique_lock lock(state->result_mutex);
			assert(!state->receiver_);
			state->receiver_ = &receiver;
			if (!state->cached_result)
			{
				if (!state->thread.valid())
				{
					lock.unlock();
					return Si::exchange(state->receiver_, nullptr)->ended();
				}
				return;
			}
			auto ready_result = std::move(*state->cached_result);
			state->result_retrieved.notify_one();
			lock.unlock();
			Si::exchange(state->receiver_, nullptr)->got_element(std::move(ready_result));
		}

		void cancel()
		{
			throw std::logic_error("to do");
		}

	private:

		struct movable_state : private detail::yield_context_impl<Element>
		{
			typename ThreadingAPI::template future<void> thread;
			typename ThreadingAPI::mutex result_mutex;
			typename ThreadingAPI::condition_variable result_retrieved;
			observer<element_type> *receiver_ = nullptr;
			boost::optional<Element> cached_result;

			template <class Action>
			explicit movable_state(Action &&action)
			{
				//start the background thread after the initialization of all the members
				thread = ThreadingAPI::template launch_async([this, action]() -> void
				{
					yield_context<Element> yield(*this);
					action(yield);
				});
			}

			virtual void push_result(Element result) SILICIUM_OVERRIDE
			{
				typename ThreadingAPI::unique_lock lock(result_mutex);
				while (cached_result.is_initialized())
				{
					result_retrieved.wait(lock);
				}
				if (receiver_)
				{
					auto receiver = Si::exchange(receiver_, nullptr);
					lock.unlock();
					receiver->got_element(std::move(result));
				}
				else
				{
					cached_result = std::move(result);
				}
			}

			virtual void get_one(observable<nothing> &target) SILICIUM_OVERRIDE
			{
				boost::ignore_unused_variable_warning(target);
				throw std::logic_error("todo");
			}
		};

		std::unique_ptr<movable_state> state;
	};

	struct std_threading
	{
		template <class T>
		using future = std::future<T>;
		using mutex = std::mutex;
		using condition_variable = std::condition_variable;
		using unique_lock = std::unique_lock<std::mutex>;
		template <class Action, class ...Args>
		static auto launch_async(Action &&action, Args &&...args) -> std::future<decltype(action(std::forward<Args>(args)...))>
		{
			return std::async(std::launch::async, std::forward<Action>(action), std::forward<Args>(args)...);
		}
	};

	struct boost_threading
	{
		template <class T>
		using future = boost::unique_future<T>;
		using mutex = boost::mutex;
		using condition_variable = boost::condition_variable;
		using unique_lock = boost::unique_lock<boost::mutex>;
		template <class Action, class ...Args>
		static auto launch_async(Action &&action, Args &&...args) -> boost::unique_future<decltype(action(std::forward<Args>(args)...))>
		{
			return boost::async(boost::launch::async, std::forward<Action>(action), std::forward<Args>(args)...);
		}
	};

	template <class Element, class ThreadingAPI, class Action>
	auto make_thread(Action &&action) -> thread_observable<Element, ThreadingAPI>
	{
		return thread_observable<Element, ThreadingAPI>(std::forward<Action>(action));
	}
}

#endif
<|endoftext|>