<commit_before>/*
 *            Copyright 2009-2020 The VOTCA Development Team
 *                       (http://www.votca.org)
 *
 *      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.
 *
 */

#include <boost/format.hpp>
#include <votca/xtp/anderson_mixing.h>

namespace votca {
namespace xtp {

void ANDERSON::UpdateOutput(const Eigen::VectorXd &newOutput) {

  // Check if max mixing history is reached and adding new step to history
  Index size = _output.size();
  if (size > _max_history - 1) {
    _output.erase(_output.begin());
  }
  _output.push_back(newOutput);
}

void ANDERSON::UpdateInput(const Eigen::VectorXd &newInput) {
  Index size = _output.size();
  if (size > _max_history - 1) {
    _input.erase(_input.begin());
  }
  _input.push_back(newInput);
}

Eigen::VectorXd ANDERSON::NPAndersonMixing(const double alpha) {

  _iteration++;

  Eigen::VectorXd OutMixed = _output.back();
  Eigen::VectorXd InMixed = _input.back();

  if (_iteration > 1 && _max_history > 1) {

    Eigen::VectorXd DeltaN = OutMixed - InMixed;

    // Building Linear System for Coefficients
    const Index used_history = _output.size()-1;
    Eigen::MatrixXd A =
        Eigen::MatrixXd::Zero(used_history, used_history);
    Eigen::VectorXd c = Eigen::VectorXd::Zero(used_history);

    for (Index m = 1; m <= used_history; m++) {

      c(m - 1) = (DeltaN - _output.at(used_history - m) +
                  _input.at(used_history - m))
                     .cwiseProduct(DeltaN)
                     .sum();

      for (Index j = 1; j <= used_history; j++) {
        A(m - 1, j - 1) =
            (DeltaN - _output.at(used_history - m) +
             _input.at(used_history - m))
                .cwiseProduct((DeltaN - _output.at(used_history - j) +
                               _input.at(used_history - j)))
                .sum();
      }
    }
    // Solving the System to obtain coefficients
    Eigen::VectorXd coefficients = A.fullPivHouseholderQr().solve(c);

    // Mixing the Potentials
    for (Index n = 1; n <= used_history; n++) {

      OutMixed += coefficients(n - 1) * (_output.at(used_history - n) -
                                         _output.at(used_history));
      InMixed += coefficients(n - 1) * (_input.at(used_history - n) -
                                        _input.at(used_history));
    }
  }

  // Returning the linear Mix of Input and Output
  return alpha * OutMixed + (1 - alpha) * InMixed;
}
}  // namespace xtp
}  // namespace votca<commit_msg>format<commit_after>/*
 *            Copyright 2009-2020 The VOTCA Development Team
 *                       (http://www.votca.org)
 *
 *      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.
 *
 */

#include <boost/format.hpp>
#include <votca/xtp/anderson_mixing.h>

namespace votca {
namespace xtp {

void ANDERSON::UpdateOutput(const Eigen::VectorXd &newOutput) {

  // Check if max mixing history is reached and adding new step to history
  Index size = _output.size();
  if (size > _max_history - 1) {
    _output.erase(_output.begin());
  }
  _output.push_back(newOutput);
}

void ANDERSON::UpdateInput(const Eigen::VectorXd &newInput) {
  Index size = _output.size();
  if (size > _max_history - 1) {
    _input.erase(_input.begin());
  }
  _input.push_back(newInput);
}

Eigen::VectorXd ANDERSON::NPAndersonMixing(const double alpha) {

  _iteration++;

  Eigen::VectorXd OutMixed = _output.back();
  Eigen::VectorXd InMixed = _input.back();

  if (_iteration > 1 && _max_history > 1) {

    Eigen::VectorXd DeltaN = OutMixed - InMixed;

    // Building Linear System for Coefficients
    const Index used_history = _output.size() - 1;
    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(used_history, used_history);
    Eigen::VectorXd c = Eigen::VectorXd::Zero(used_history);

    for (Index m = 1; m <= used_history; m++) {

      c(m - 1) =
          (DeltaN - _output.at(used_history - m) + _input.at(used_history - m))
              .cwiseProduct(DeltaN)
              .sum();

      for (Index j = 1; j <= used_history; j++) {
        A(m - 1, j - 1) =
            (DeltaN - _output.at(used_history - m) +
             _input.at(used_history - m))
                .cwiseProduct((DeltaN - _output.at(used_history - j) +
                               _input.at(used_history - j)))
                .sum();
      }
    }
    // Solving the System to obtain coefficients
    Eigen::VectorXd coefficients = A.fullPivHouseholderQr().solve(c);

    // Mixing the Potentials
    for (Index n = 1; n <= used_history; n++) {

      OutMixed += coefficients(n - 1) *
                  (_output.at(used_history - n) - _output.at(used_history));
      InMixed += coefficients(n - 1) *
                 (_input.at(used_history - n) - _input.at(used_history));
    }
  }

  // Returning the linear Mix of Input and Output
  return alpha * OutMixed + (1 - alpha) * InMixed;
}
}  // namespace xtp
}  // namespace votca<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2015 Marius Kaufmann, Tamara Frieß, Jannis Hoppe, Christian Hack

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.
*/

/**
 * @file
 * @brief Implementation of srpphat.h
 */
#include "srp_phat.h"
#include <string>
#include <tuple>
#include <vector>
#include "utils/fft_lib.h"

namespace taylortrack {
namespace localization {
double SrpPhat::inter_microphone_time_delay(const RArray &point,
                                            const RArray &microphone1,
                                            const RArray &microphone2) {
  return (std::sqrt(std::pow(point - microphone1, 2).sum())
      - std::sqrt(std::pow(point - microphone2, 2).sum()))
      / kSpeedOfSound;
}

int SrpPhat::point_to_degree(double x_coordinate, double y_coordinate) {
  return static_cast<int>(round(fmod(((atan2(y_coordinate, x_coordinate)
      * 180 / kPI) + 360), 360.0)));
}

std::vector<std::tuple<int, int>> SrpPhat::get_microphone_pairs() {
  std::vector<std::tuple<int, int>> pairs;
  // iterating over microphones
  for (int i = 0; i < static_cast<int>(x_dim_mics_.size()); i++) {
    for (int j = 0; j < static_cast<int>(x_dim_mics_.size()); j++) {
      // only append pairs once and don't consider pairs of the same microphone
      if (j > i) {
        pairs.push_back(std::make_tuple(i, j));
      }
    }
  }
  return pairs;
}

RArray SrpPhat::generalized_cross_correlation(const RArray &signal1, const RArray &signal2) {
  size_t corr_length = signal1.size() + signal2.size() - 1;
  /* bringing the signals into the right shape to work with the fftlib
   first making them complex and pad with necessary zeros */
  taylortrack::utils::FftLib fft_obj = taylortrack::utils::FftLib();
  CArray tempsignal1 = fft_obj.convert_to_complex(signal1);
  CArray tempsignal2 = fft_obj.convert_to_complex(signal2);
  CArray csignal1 =
      fft_obj.zero_padding(tempsignal1,
                           static_cast<int> (corr_length - signal1.size()));
  CArray csignal2 =
      fft_obj.zero_padding(tempsignal2,
                           static_cast<int> (corr_length - signal2.size()));

  // perform FFT on the converted signals
  fft_obj.fft(csignal1);
  fft_obj.fft(csignal2);

  // computing nominator and denominator of the generalized cross correlation
  CArray nominator = csignal1 * csignal2.apply(std::conj);
  CArray denominator = std::pow(abs(nominator), static_cast<float>(beta_));

  // reverse transfering to time domain
  CArray temp = nominator / denominator;

  fft_obj.ifft(temp);

  RArray result(temp.size());
  RArray temp3 = fft_obj.convert_to_real(temp);

  fft_obj.fftshift(temp3, result);

  return result;
}

std::vector<double> SrpPhat::get_axis_values(bool xaxis) {
  std::vector<double> axisValues;
  int vectorSize = static_cast<int>(
      xaxis ? x_length_ / stepsize_ + 1 : y_length_ / stepsize_ + 1);
  double axStart = xaxis ? x_length_ / 2 * -1 : y_length_ / 2;
  while (static_cast<int>(axisValues.size()) < vectorSize) {
    axisValues.push_back(axStart);
    axStart = xaxis ? axStart + stepsize_ : axStart - stepsize_;
  }
  return axisValues;
}

RArray SrpPhat::get_position_distribution(const std::vector<RArray> &signals) {
  std::vector<std::vector<double>> gcc_grid = get_generalized_cross_correlation(signals);
  RArray degree_values(360);
  std::vector<double> xAxisValues = get_axis_values(true);
  std::vector<double> yAxisValues = get_axis_values(false);

  for (int i = 0; i < static_cast<int>(xAxisValues.size()); i++) {
    for (int j = 0; j < static_cast<int>(yAxisValues.size()); j++) {
      int degree = point_to_degree(xAxisValues[i], yAxisValues[j]);
      if (degree == 360)
        degree = 0;
      degree_values[degree] += gcc_grid[i][j];
    }
  }
  // get maximum for normalization of values
  double res = degree_values.sum();
  return degree_values / res;
}

int SrpPhat::get_position(const std::vector<RArray> &signals) {
  std::vector<std::vector<double>> gcc_grid = get_generalized_cross_correlation(signals);
  RArray degree_values(360);
  std::vector<double> xAxisValues = get_axis_values(true);
  std::vector<double> yAxisValues = get_axis_values(false);
  for (int i = 0; i < 360; i++) {
    degree_values[i] = 0;
  }
  int vectorSize = static_cast<int> (x_length_ / stepsize_ + 1);
  for (int i = 0; i < vectorSize; i++) {
    for (int j = 0; j < vectorSize; j++) {
      int degree = point_to_degree(xAxisValues[j],
                                   static_cast<double> (yAxisValues[i]));
      if (degree == 360)
        degree = 0;
      degree_values[degree] += gcc_grid[j][i];
    }
  }
  double res = degree_values.max();
  return find_value(degree_values, res);
}

int SrpPhat::find_value(const RArray &in_vector, double value) {
  for (int i = 0; i < static_cast<int>(in_vector.size()); i++) {
    if (std::abs(in_vector[i] - value) < 0.0001) {
      return i;
    }
  }
  return -1;
}

std::vector<std::vector<double>>
SrpPhat::get_generalized_cross_correlation(const std::vector<RArray> &signals) {
  std::vector<std::tuple<int, int>> pairs = get_microphone_pairs();
  std::vector<std::vector<double>> generalized_cross_correlation_values;
  int64_t vectorSize = int64_t(x_length_ / stepsize_ + 1);
  // initializing the gcc grid
  generalized_cross_correlation_values.resize(static_cast<unsigned long>(vectorSize));
  for (int i = 0; i < vectorSize; ++i) {
    generalized_cross_correlation_values[i].resize(static_cast<unsigned long>(vectorSize));
  }
  std::vector<std::vector<std::vector<double>>> micDelays = delay_tensor_;
  // iterating over all microphone pairs
  for (int i = 0; i < static_cast<int>(pairs.size()); i++) {
    int index1 = std::get<0>(pairs[i]);
    int index2 = std::get<1>(pairs[i]);
    // assigning the corresponding signals
    RArray signal1 = signals[index1];
    RArray signal2 = signals[index2];
    // get the current frame from the complete signal
    RArray signalSlice1 = signal1[std::slice(0, static_cast<size_t>(steps_ + 1), 1)];
    RArray signalSlice2 = signal2[std::slice(0, static_cast<size_t>(steps_), 1)];
    // computing the cross correlation of both frames
    RArray generalized_cross_temp = generalized_cross_correlation(signalSlice1, signalSlice2);
    // iterating over the whole x-y grid
    for (int x = 0; x < vectorSize; x++) {
      for (int y = 0; y < vectorSize; y++) {
        double delay = micDelays[x][y][i];
        // adding the corresponding cross correlation value to the grid
        generalized_cross_correlation_values[x][y] += generalized_cross_temp[(steps_ - 1) +
            round(delay / (1.0 / samplerate_))];
      }
    }
  }
  return generalized_cross_correlation_values;
}

std::vector<std::vector<std::vector<double>>> SrpPhat::get_delay_tensor() {
  std::vector<std::vector<std::vector<double>>> delay_tensor;
  std::vector<double> xAxisValues = get_axis_values(true);
  std::vector<double> yAxisValues = get_axis_values(false);
  std::vector<std::tuple<int, int>> pairs = get_microphone_pairs();
  int vector_size = x_length_ / stepsize_ + 1;
  int depth = pairs.size();
  delay_tensor.resize(vector_size);
  for (int i = 0; i < vector_size; ++i) {
    delay_tensor[i].resize(vector_size);
    for (int j = 0; j < vector_size; ++j)
      delay_tensor[i][j].resize(depth);
  }
  // iterating over the grid
  for (int x = 0; x < vector_size; x++) {
    for (int y = 0; y < vector_size; y++) {
      // iterating over microphone pairs
      for (int i = 0; i < static_cast<int>(pairs.size()); i++) {
        //
        RArray point(2);
        RArray microphone1(2);
        RArray microphone2(2);
        // assigning the current point in the grid
        point[0] = xAxisValues[x];
        point[1] = yAxisValues[y];
        // assigning the microphone values
        int index1 = std::get<0>(pairs[i]);
        int index2 = std::get<1>(pairs[i]);
        microphone1[0] = x_dim_mics_[index1];
        microphone1[1] = y_dim_mics_[index1];
        microphone2[0] = x_dim_mics_[index2];
        microphone2[1] = y_dim_mics_[index2];
        double delay = inter_microphone_time_delay(point, microphone1, microphone2);
        delay_tensor[x][y][i] = delay;
      }
    }
  }
  // iterating over all microphone pairs
  return delay_tensor;
}

RArray SrpPhat::get_microphone_signal(const std::string &filepath_name) {
  std::vector<double> temporary_vector;
  std::ifstream infile(filepath_name);
  std::string line = "";
  while (std::getline(infile, line)) {
    std::istringstream string_stream(line);
    double temporary_value;
    if (!(string_stream >> temporary_value))
      break;
    temporary_vector.push_back(temporary_value);
  }
  infile.close();
  RArray signal(temporary_vector.size());
  for (int i = 0; i < static_cast<int>(temporary_vector.size()); i++) {
    signal[i] = temporary_vector[i];
  }
  return signal;
}
void SrpPhat::calculate_position_and_distribution(const std::vector<RArray> &signals) {
  std::vector<std::vector<double>> gcc_grid = get_generalized_cross_correlation(signals);
  RArray degree_values(360);
  std::vector<double> xAxisValues = get_axis_values(true);
  std::vector<double> yAxisValues = get_axis_values(false);

  for (int i = 0; i < static_cast<int>(xAxisValues.size()); i++) {
    for (int j = 0; j < static_cast<int>(yAxisValues.size()); j++) {
      int degree = point_to_degree(xAxisValues[i], yAxisValues[j]);
      if (degree == 360)
        degree = 0;
      degree_values[degree] += gcc_grid[i][j];
    }
  }
  // get maximum for normalization of values
  double normalization = degree_values.sum();
  last_distribution_ = degree_values / normalization;
  double maximum_position = degree_values.max();
  last_position_ = find_value(degree_values, maximum_position);
}
}  // namespace localization
}  // namespace taylortrack
<commit_msg>had to do the lint again<commit_after>/*
The MIT License (MIT)

Copyright (c) 2015 Marius Kaufmann, Tamara Frieß, Jannis Hoppe, Christian Hack

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.
*/

/**
 * @file
 * @brief Implementation of srpphat.h
 */
#include "localization/srp_phat.h"
#include <string>
#include <tuple>
#include <vector>
#include "utils/fft_lib.h"

namespace taylortrack {
namespace localization {
double SrpPhat::inter_microphone_time_delay(const RArray &point,
                                            const RArray &microphone1,
                                            const RArray &microphone2) {
  return (std::sqrt(std::pow(point - microphone1, 2).sum())
      - std::sqrt(std::pow(point - microphone2, 2).sum()))
      / kSpeedOfSound;
}

int SrpPhat::point_to_degree(double x_coordinate, double y_coordinate) {
  return static_cast<int>(round(fmod(((atan2(y_coordinate, x_coordinate)
      * 180 / kPI) + 360), 360.0)));
}

std::vector<std::tuple<int, int>> SrpPhat::get_microphone_pairs() {
  std::vector<std::tuple<int, int>> pairs;
  // iterating over microphones
  for (int i = 0; i < static_cast<int>(x_dim_mics_.size()); i++) {
    for (int j = 0; j < static_cast<int>(x_dim_mics_.size()); j++) {
      // only append pairs once and don't consider pairs of the same microphone
      if (j > i) {
        pairs.push_back(std::make_tuple(i, j));
      }
    }
  }
  return pairs;
}

RArray SrpPhat::generalized_cross_correlation(const RArray &signal1,
                                              const RArray &signal2) {
  size_t corr_length = signal1.size() + signal2.size() - 1;
  /* bringing the signals into the right shape to work with the fftlib
   first making them complex and pad with necessary zeros */
  taylortrack::utils::FftLib fft_obj = taylortrack::utils::FftLib();
  CArray tempsignal1 = fft_obj.convert_to_complex(signal1);
  CArray tempsignal2 = fft_obj.convert_to_complex(signal2);
  CArray csignal1 =
      fft_obj.zero_padding(tempsignal1,
                           static_cast<int> (corr_length - signal1.size()));
  CArray csignal2 =
      fft_obj.zero_padding(tempsignal2,
                           static_cast<int> (corr_length - signal2.size()));

  // perform FFT on the converted signals
  fft_obj.fft(csignal1);
  fft_obj.fft(csignal2);

  // computing nominator and denominator of the generalized cross correlation
  CArray nominator = csignal1 * csignal2.apply(std::conj);
  CArray denominator = std::pow(abs(nominator), static_cast<float>(beta_));

  // reverse transfering to time domain
  CArray temp = nominator / denominator;

  fft_obj.ifft(temp);

  RArray result(temp.size());
  RArray temp3 = fft_obj.convert_to_real(temp);

  fft_obj.fftshift(temp3, result);

  return result;
}

std::vector<double> SrpPhat::get_axis_values(bool xaxis) {
  std::vector<double> axisValues;
  int vectorSize = static_cast<int>(
      xaxis ? x_length_ / stepsize_ + 1 : y_length_ / stepsize_ + 1);
  double axStart = xaxis ? x_length_ / 2 * -1 : y_length_ / 2;
  while (static_cast<int>(axisValues.size()) < vectorSize) {
    axisValues.push_back(axStart);
    axStart = xaxis ? axStart + stepsize_ : axStart - stepsize_;
  }
  return axisValues;
}

RArray SrpPhat::get_position_distribution(const std::vector<RArray> &signals) {
  std::vector<std::vector<double>> gcc_grid =
      get_generalized_cross_correlation(signals);
  RArray degree_values(360);
  std::vector<double> xAxisValues = get_axis_values(true);
  std::vector<double> yAxisValues = get_axis_values(false);

  for (int i = 0; i < static_cast<int>(xAxisValues.size()); i++) {
    for (int j = 0; j < static_cast<int>(yAxisValues.size()); j++) {
      int degree = point_to_degree(xAxisValues[i], yAxisValues[j]);
      if (degree == 360)
        degree = 0;
      degree_values[degree] += gcc_grid[i][j];
    }
  }
  // get maximum for normalization of values
  double res = degree_values.sum();
  return degree_values / res;
}

int SrpPhat::get_position(const std::vector<RArray> &signals) {
  std::vector<std::vector<double>> gcc_grid =
      get_generalized_cross_correlation(signals);
  RArray degree_values(360);
  std::vector<double> xAxisValues = get_axis_values(true);
  std::vector<double> yAxisValues = get_axis_values(false);
  for (int i = 0; i < 360; i++) {
    degree_values[i] = 0;
  }
  int vectorSize = static_cast<int> (x_length_ / stepsize_ + 1);
  for (int i = 0; i < vectorSize; i++) {
    for (int j = 0; j < vectorSize; j++) {
      int degree = point_to_degree(xAxisValues[j],
                                   static_cast<double> (yAxisValues[i]));
      if (degree == 360)
        degree = 0;
      degree_values[degree] += gcc_grid[j][i];
    }
  }
  double res = degree_values.max();
  return find_value(degree_values, res);
}

int SrpPhat::find_value(const RArray &in_vector, double value) {
  for (int i = 0; i < static_cast<int>(in_vector.size()); i++) {
    if (std::abs(in_vector[i] - value) < 0.0001) {
      return i;
    }
  }
  return -1;
}

std::vector<std::vector<double>>
SrpPhat::get_generalized_cross_correlation(const std::vector<RArray> &signals) {
  std::vector<std::tuple<int, int>> pairs = get_microphone_pairs();
  std::vector<std::vector<double>> generalized_cross_correlation_values;
  int64_t vectorSize = int64_t(x_length_ / stepsize_ + 1);
  // initializing the gcc grid
  generalized_cross_correlation_values.
      resize(static_cast<int64_t>(vectorSize));
  for (int i = 0; i < vectorSize; ++i) {
    generalized_cross_correlation_values[i].
        resize(static_cast<int64_t>(vectorSize));
  }
  std::vector<std::vector<std::vector<double>>> micDelays = delay_tensor_;
  // iterating over all microphone pairs
  for (int i = 0; i < static_cast<int>(pairs.size()); i++) {
    int index1 = std::get<0>(pairs[i]);
    int index2 = std::get<1>(pairs[i]);
    // assigning the corresponding signals
    RArray signal1 = signals[index1];
    RArray signal2 = signals[index2];
    // get the current frame from the complete signal
    RArray signalSlice1 =
        signal1[std::slice(0, static_cast<size_t>(steps_ + 1), 1)];
    RArray signalSlice2 =
        signal2[std::slice(0, static_cast<size_t>(steps_), 1)];
    // computing the cross correlation of both frames
    RArray generalized_cross_temp =
        generalized_cross_correlation(signalSlice1, signalSlice2);
    // iterating over the whole x-y grid
    for (int x = 0; x < vectorSize; x++) {
      for (int y = 0; y < vectorSize; y++) {
        double delay = micDelays[x][y][i];
        // adding the corresponding cross correlation value to the grid
        generalized_cross_correlation_values[x][y] +=
            generalized_cross_temp[(steps_ - 1) +
                round(delay / (1.0 / samplerate_))];
      }
    }
  }
  return generalized_cross_correlation_values;
}

std::vector<std::vector<std::vector<double>>> SrpPhat::get_delay_tensor() {
  std::vector<std::vector<std::vector<double>>> delay_tensor;
  std::vector<double> xAxisValues = get_axis_values(true);
  std::vector<double> yAxisValues = get_axis_values(false);
  std::vector<std::tuple<int, int>> pairs = get_microphone_pairs();
  int vector_size = x_length_ / stepsize_ + 1;
  int depth = pairs.size();
  delay_tensor.resize(vector_size);
  for (int i = 0; i < vector_size; ++i) {
    delay_tensor[i].resize(vector_size);
    for (int j = 0; j < vector_size; ++j)
      delay_tensor[i][j].resize(depth);
  }
  // iterating over the grid
  for (int x = 0; x < vector_size; x++) {
    for (int y = 0; y < vector_size; y++) {
      // iterating over microphone pairs
      for (int i = 0; i < static_cast<int>(pairs.size()); i++) {
        //
        RArray point(2);
        RArray microphone1(2);
        RArray microphone2(2);
        // assigning the current point in the grid
        point[0] = xAxisValues[x];
        point[1] = yAxisValues[y];
        // assigning the microphone values
        int index1 = std::get<0>(pairs[i]);
        int index2 = std::get<1>(pairs[i]);
        microphone1[0] = x_dim_mics_[index1];
        microphone1[1] = y_dim_mics_[index1];
        microphone2[0] = x_dim_mics_[index2];
        microphone2[1] = y_dim_mics_[index2];
        double delay =
            inter_microphone_time_delay(point, microphone1, microphone2);
        delay_tensor[x][y][i] = delay;
      }
    }
  }
  // iterating over all microphone pairs
  return delay_tensor;
}

RArray SrpPhat::get_microphone_signal(const std::string &filepath_name) {
  std::vector<double> temporary_vector;
  std::ifstream infile(filepath_name);
  std::string line = "";
  while (std::getline(infile, line)) {
    std::istringstream string_stream(line);
    double temporary_value;
    if (!(string_stream >> temporary_value))
      break;
    temporary_vector.push_back(temporary_value);
  }
  infile.close();
  RArray signal(temporary_vector.size());
  for (int i = 0; i < static_cast<int>(temporary_vector.size()); i++) {
    signal[i] = temporary_vector[i];
  }
  return signal;
}
void SrpPhat::calculate_position_and_distribution(
    const std::vector<RArray> &signals) {
  std::vector<std::vector<double>> gcc_grid =
      get_generalized_cross_correlation(signals);
  RArray degree_values(360);
  std::vector<double> xAxisValues = get_axis_values(true);
  std::vector<double> yAxisValues = get_axis_values(false);

  for (int i = 0; i < static_cast<int>(xAxisValues.size()); i++) {
    for (int j = 0; j < static_cast<int>(yAxisValues.size()); j++) {
      int degree = point_to_degree(xAxisValues[i], yAxisValues[j]);
      if (degree == 360)
        degree = 0;
      degree_values[degree] += gcc_grid[i][j];
    }
  }
  // get maximum for normalization of values
  double normalization = degree_values.sum();
  last_distribution_ = degree_values / normalization;
  double maximum_position = degree_values.max();
  last_position_ = find_value(degree_values, maximum_position);
}
}  // namespace localization
}  // namespace taylortrack
<|endoftext|>


<commit_before>/*
 * Copyright 2018 Google Inc.
 *
 * 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.
 */

#include "config.h"

#include "buildjson.hpp"
#include "file_handler.hpp"
#include "firmware_handler.hpp"
#include "flags.hpp"
#include "general_systemd.hpp"
#include "image_handler.hpp"
#include "lpc_aspeed.hpp"
#include "lpc_handler.hpp"
#include "lpc_nuvoton.hpp"
#include "net_handler.hpp"
#include "pci_handler.hpp"
#include "status.hpp"
#include "util.hpp"

#include <sdbusplus/bus.hpp>

#include <cstdint>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

namespace ipmi_flash
{

namespace
{

#ifdef NUVOTON_P2A_MBOX
static constexpr std::size_t memoryRegionSize = 16 * 1024UL;
#elif defined NUVOTON_P2A_VGA
static constexpr std::size_t memoryRegionSize = 4 * 1024 * 1024UL;
#else
/* The maximum external buffer size we expect is 64KB. */
static constexpr std::size_t memoryRegionSize = 64 * 1024UL;
#endif

static constexpr const char* jsonConfigurationPath =
    "/usr/share/phosphor-ipmi-flash/";

#ifdef ENABLE_LPC_BRIDGE
#if defined(ASPEED_LPC)
LpcDataHandler lpcDataHandler(
    LpcMapperAspeed::createAspeedMapper(MAPPED_ADDRESS, memoryRegionSize));
#elif defined(NUVOTON_LPC)
LpcDataHandler lpcDataHandler(
    LpcMapperNuvoton::createNuvotonMapper(MAPPED_ADDRESS, memoryRegionSize));
#else
#error "You must specify a hardware implementation."
#endif
#endif

#ifdef ENABLE_PCI_BRIDGE
PciDataHandler pciDataHandler(MAPPED_ADDRESS, memoryRegionSize);
#endif

#ifdef ENABLE_NET_BRIDGE
NetDataHandler netDataHandler;
#endif

std::vector<DataHandlerPack> supportedTransports = {
    {FirmwareFlags::UpdateFlags::ipmi, nullptr},
#ifdef ENABLE_PCI_BRIDGE
    {FirmwareFlags::UpdateFlags::p2a, &pciDataHandler},
#endif
#ifdef ENABLE_LPC_BRIDGE
    {FirmwareFlags::UpdateFlags::lpc, &lpcDataHandler},
#endif
#ifdef ENABLE_NET_BRIDGE
    {FirmwareFlags::UpdateFlags::net, &netDataHandler},
#endif
};

/**
 * Given a name and path, create a HandlerPack.
 *
 * @param[in] name - the blob id path for this
 * @param[in] path - the file path to write the contents.
 * @return the HandlerPack.
 */
HandlerPack CreateFileHandlerPack(const std::string& name,
                                  const std::string& path)
{
    return HandlerPack(name, std::make_unique<FileHandler>(path));
}

} // namespace
} // namespace ipmi_flash

extern "C"
{
    std::unique_ptr<blobs::GenericBlobInterface> createHandler();
}

std::unique_ptr<blobs::GenericBlobInterface> createHandler()
{
    ipmi_flash::ActionMap actionPacks = {};

    std::vector<ipmi_flash::HandlerConfig> configsFromJson =
        ipmi_flash::BuildHandlerConfigs(ipmi_flash::jsonConfigurationPath);

    std::vector<ipmi_flash::HandlerPack> supportedFirmware;

    supportedFirmware.push_back(std::move(ipmi_flash::CreateFileHandlerPack(
        ipmi_flash::hashBlobId, HASH_FILENAME)));

    for (auto& config : configsFromJson)
    {
        supportedFirmware.push_back(std::move(
            ipmi_flash::HandlerPack(config.blobId, std::move(config.handler))));
        actionPacks[config.blobId] = std::move(config.actions);

        std::fprintf(stderr, "config loaded: %s\n", config.blobId.c_str());
    }

    auto handler = ipmi_flash::FirmwareBlobHandler::CreateFirmwareBlobHandler(
        std::move(supportedFirmware),
        std::move(ipmi_flash::supportedTransports), std::move(actionPacks));

    if (!handler)
    {
        std::fprintf(stderr, "Firmware Handler has an invalid configuration");
        return nullptr;
    }

    return handler;
}
<commit_msg>bmc: using namespace ipmi_flash simplifies reading<commit_after>/*
 * Copyright 2018 Google Inc.
 *
 * 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.
 */

#include "config.h"

#include "buildjson.hpp"
#include "file_handler.hpp"
#include "firmware_handler.hpp"
#include "flags.hpp"
#include "general_systemd.hpp"
#include "image_handler.hpp"
#include "lpc_aspeed.hpp"
#include "lpc_handler.hpp"
#include "lpc_nuvoton.hpp"
#include "net_handler.hpp"
#include "pci_handler.hpp"
#include "status.hpp"
#include "util.hpp"

#include <sdbusplus/bus.hpp>

#include <cstdint>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

namespace ipmi_flash
{

namespace
{

#ifdef NUVOTON_P2A_MBOX
static constexpr std::size_t memoryRegionSize = 16 * 1024UL;
#elif defined NUVOTON_P2A_VGA
static constexpr std::size_t memoryRegionSize = 4 * 1024 * 1024UL;
#else
/* The maximum external buffer size we expect is 64KB. */
static constexpr std::size_t memoryRegionSize = 64 * 1024UL;
#endif

static constexpr const char* jsonConfigurationPath =
    "/usr/share/phosphor-ipmi-flash/";

#ifdef ENABLE_LPC_BRIDGE
#if defined(ASPEED_LPC)
LpcDataHandler lpcDataHandler(
    LpcMapperAspeed::createAspeedMapper(MAPPED_ADDRESS, memoryRegionSize));
#elif defined(NUVOTON_LPC)
LpcDataHandler lpcDataHandler(
    LpcMapperNuvoton::createNuvotonMapper(MAPPED_ADDRESS, memoryRegionSize));
#else
#error "You must specify a hardware implementation."
#endif
#endif

#ifdef ENABLE_PCI_BRIDGE
PciDataHandler pciDataHandler(MAPPED_ADDRESS, memoryRegionSize);
#endif

#ifdef ENABLE_NET_BRIDGE
NetDataHandler netDataHandler;
#endif

std::vector<DataHandlerPack> supportedTransports = {
    {FirmwareFlags::UpdateFlags::ipmi, nullptr},
#ifdef ENABLE_PCI_BRIDGE
    {FirmwareFlags::UpdateFlags::p2a, &pciDataHandler},
#endif
#ifdef ENABLE_LPC_BRIDGE
    {FirmwareFlags::UpdateFlags::lpc, &lpcDataHandler},
#endif
#ifdef ENABLE_NET_BRIDGE
    {FirmwareFlags::UpdateFlags::net, &netDataHandler},
#endif
};

/**
 * Given a name and path, create a HandlerPack.
 *
 * @param[in] name - the blob id path for this
 * @param[in] path - the file path to write the contents.
 * @return the HandlerPack.
 */
HandlerPack CreateFileHandlerPack(const std::string& name,
                                  const std::string& path)
{
    return HandlerPack(name, std::make_unique<FileHandler>(path));
}

} // namespace
} // namespace ipmi_flash

extern "C"
{
    std::unique_ptr<blobs::GenericBlobInterface> createHandler();
}

std::unique_ptr<blobs::GenericBlobInterface> createHandler()
{
    using namespace ipmi_flash;

    ActionMap actionPacks = {};

    std::vector<HandlerConfig> configsFromJson =
        BuildHandlerConfigs(jsonConfigurationPath);

    std::vector<HandlerPack> supportedFirmware;

    supportedFirmware.push_back(
        std::move(CreateFileHandlerPack(hashBlobId, HASH_FILENAME)));

    for (auto& config : configsFromJson)
    {
        supportedFirmware.push_back(
            std::move(HandlerPack(config.blobId, std::move(config.handler))));
        actionPacks[config.blobId] = std::move(config.actions);

        std::fprintf(stderr, "config loaded: %s\n", config.blobId.c_str());
    }

    auto handler = FirmwareBlobHandler::CreateFirmwareBlobHandler(
        std::move(supportedFirmware), std::move(supportedTransports),
        std::move(actionPacks));

    if (!handler)
    {
        std::fprintf(stderr, "Firmware Handler has an invalid configuration");
        return nullptr;
    }

    return handler;
}
<|endoftext|>


<commit_before>#include "ptreferential.h"

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_lit.hpp>

#include <boost/fusion/include/adapt_struct.hpp>
#include <iostream>
#include "indexes2.h"
#include "where.h"
#include "reflexion.h"
#include "proto/type.pb.h"

#include <google/protobuf/descriptor.h>

namespace qi = boost::spirit::qi;
using namespace navitia::type;
struct Column {
    std::string table;
    std::string column;
};

BOOST_FUSION_ADAPT_STRUCT(
    Column,
    (std::string, table)
    (std::string, column)
)

struct WhereClause{
    Column col;
    std::string op;
    std::string value;
};

BOOST_FUSION_ADAPT_STRUCT(
    WhereClause,
    (Column,col)
    (std::string, op)
    (std::string, value)
)

struct Request {
    std::vector<Column> columns;
    std::vector<std::string> tables;
    std::vector<WhereClause> clauses;
};

BOOST_FUSION_ADAPT_STRUCT(
    Request,
    (std::vector<Column>, columns)
    (std::vector<std::string>, tables)
    (std::vector<WhereClause>, clauses)
)
        template <typename Iterator>
        struct select_r
            : qi::grammar<Iterator, Request(), qi::space_type>
{
    qi::rule<Iterator, std::string(), qi::space_type> txt; // Match une string
    qi::rule<Iterator, Column(), qi::space_type> table_col; // Match une colonne
    qi::rule<Iterator, std::vector<Column>(), qi::space_type> select; // Match toute la section SELECT
    qi::rule<Iterator, std::vector<std::string>(), qi::space_type> from; // Matche la section FROM
    qi::rule<Iterator, Request(), qi::space_type> request; // Toute la requête
    qi::rule<Iterator, std::vector<WhereClause>(), qi::space_type> where;// section Where
    qi::rule<Iterator, std::string(), qi::space_type> bin_op; // Match une operator binaire telle que <, =...

    select_r() : select_r::base_type(request) {
        txt %= qi::lexeme[+(qi::alnum|'_')]; // Match du texte
        bin_op %=  qi::string("<=") | qi::string(">=") | qi::string("<>") | qi::string("<")  | qi::string(">") | qi::string("=") ;
        table_col %= -(txt >> '.') // (Nom de la table suivit de point) optionnel (operateur -)
                     >> txt; // Nom de la table obligatoire
        select  %= qi::lexeme["select"] >> table_col % ',' ; // La liste de table_col séparée par des ,
        from %= qi::lexeme["from"] >> txt % ',';
        where %= qi::lexeme["where"] >> (table_col >> bin_op >> txt) % qi::lexeme["and"];
        request %= select >> from >> -where;
    }

};

template<class T>
WhereWrapper<T> build_clause(std::vector<WhereClause> clauses) {
    WhereWrapper<T> wh(new BaseWhere<T>());
    Operator_e op;
    BOOST_FOREACH(auto clause, clauses) {
        if(clause.op == "=") op = EQ;
        else if(clause.op == "<") op = LT;
        else if(clause.op == "<=") op = LEQ;
        else if(clause.op == ">") op = GT;
        else if(clause.op == ">=") op = GEQ;
        else if(clause.op == "<>") op = NEQ;
        else throw "grrr";

        if(clause.col.column == "id")
            wh = wh && WHERE(ptr_id<T>(), op, clause.value);
        else if(clause.col.column == "idx")
            wh = wh && WHERE(ptr_idx<T>(), op, clause.value);
        else if(clause.col.column == "external_code")
            wh = wh && WHERE(ptr_external_code<T>(), op, clause.value);
    }
    return wh;
}

std::string unpluralize_table(const std::string& table_name){
    if(table_name == "cities"){
        return "city";
    }else{
        return table_name.substr(0, table_name.length() - 1);
    }
}

template<class T>
void set_value(google::protobuf::Message* message, const T& object, const std::string& column){
    const google::protobuf::Reflection* reflection = message->GetReflection();
    const google::protobuf::Descriptor* descriptor = message->GetDescriptor();
    const google::protobuf::FieldDescriptor* field_descriptor = descriptor->FindFieldByName(column);

    if(field_descriptor == NULL){
        throw unknown_member();
    }

    if(field_descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING){
        reflection->SetString(message, field_descriptor, get_string_value(object, column));
    }else if(field_descriptor->type() == google::protobuf::FieldDescriptor::TYPE_INT32){
        reflection->SetInt32(message, field_descriptor, get_int_value(object, column));
    }else{
        throw bad_type();
    }
}

google::protobuf::Message* get_message(pbnavitia::PTreferential* row, const std::string& table){
    const google::protobuf::Reflection* reflection = row->GetReflection();
    const google::protobuf::Descriptor* descriptor = row->GetDescriptor();
    std::string field = unpluralize_table(table);
    const google::protobuf::FieldDescriptor* field_descriptor = descriptor->FindFieldByName(field);
    return reflection->MutableMessage(row, field_descriptor);
}

template<class T>
std::vector< std::vector<col_t> > extract_data(std::vector<T> & rows, const Request & r) {
    pbnavitia::PTRefResponse pb_response;

    std::vector< std::vector<col_t> > result;
    Index2<boost::fusion::vector<T> > filtered(rows, build_clause<T>(r.clauses));
    BOOST_FOREACH(auto item, filtered){
        std::vector<col_t> row;
        pbnavitia::PTreferential * pb_row = pb_response.add_item();

        google::protobuf::Message* pb_message = get_message(pb_row, r.tables.at(0));

        BOOST_FOREACH(const Column & col, r.columns){
            row.push_back(get_value(*(boost::fusion::at_c<0>(item)), col.column));
            set_value(pb_message, *(boost::fusion::at_c<0>(item)), col.column);
        }
        result.push_back(row);
    }
    std::cout << "J'ai généré un protocol buffer de taille " <<     pb_response.ByteSize() << std::endl;
    //std::cout << pb_response.SerializeToOstream(&std::cout) << std::endl;
    return result;
}

struct unknown_table{};
std::vector< std::vector<col_t> > query(std::string request, Data & data){
    std::vector< std::vector<col_t> > result;
    std::string::iterator begin = request.begin();
    Request r;
    select_r<std::string::iterator> s;
    if (qi::phrase_parse(begin, request.end(), s, qi::space, r))
    {
        if(begin != request.end()) {
            std::cout << "Hrrrmmm on a pas tout parsé -_-'" << std::endl;
        }
    }
    else
        std::cout << "Parsage a échoué" << std::endl;

    if(r.tables.size() != 1){
        std::cout << "Pour l'instant on ne supporte que exactement une table" << std::endl;
        return result;
    }
    else {
        std::cout << "Table : " << r.tables[0] << std::endl;
    }

    std::string table = r.tables[0];

    /*if(table == "validity_pattern") {
        return extract_data(data.validity_patterns, r);
    }
    else*/ if(table == "lines") {
        return extract_data(data.lines, r);
    }
    else if(table == "routes") {
        return extract_data(data.routes, r);
    }
    /*else if(table == "vehicle_journey") {
        return extract_data(data.vehicle_journeys, r);
    }*/
    else if(table == "stop_points") {
        return extract_data(data.stop_points, r);
    }
    else if(table == "stop_areas") {
        return extract_data(data.stop_areas, r);
    }
  /*  else if(table == "stop_times"){
        return extract_data(data.stop_times, r);
    }*/

    throw unknown_table();
}

int main(int argc, char** argv){
    std::cout << "Chargement des données..." << std::flush;
    Data d;
    d.load_flz("data.nav.flz");
    std::cout << " effectué" << std::endl << std::endl;

    std::cout
            << "Statistiques :" << std::endl
            << "    Nombre de StopAreas : " << d.stop_areas.size() << std::endl
            << "    Nombre de StopPoints : " << d.stop_points.size() << std::endl
            << "    Nombre de lignes : " << d.lines.size() << std::endl
            << "    Nombre d'horaires : " << d.stop_times.size() << std::endl << std::endl;

    if(argc != 2)
        std::cout << "Il faut exactement un paramètre" << std::endl;
    else {
        auto result = query(argv[1], d);
        std::cout << "Il y a " << result.size() << " lignes de résultat" << std::endl;
        BOOST_FOREACH(auto row, result){
            BOOST_FOREACH(auto col, row){
                std::cout << col << ",\t";
            }
            std::cout << std::endl;
        }
    }
    return 0;
}
<commit_msg>correction d'un include suite a l'ajout de protobuff<commit_after>#include "ptreferential.h"

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_lit.hpp>

#include <boost/fusion/include/adapt_struct.hpp>
#include <iostream>
#include "indexes2.h"
#include "where.h"
#include "reflexion.h"
#include "type.pb.h"

#include <google/protobuf/descriptor.h>

namespace qi = boost::spirit::qi;
using namespace navitia::type;
struct Column {
    std::string table;
    std::string column;
};

BOOST_FUSION_ADAPT_STRUCT(
    Column,
    (std::string, table)
    (std::string, column)
)

struct WhereClause{
    Column col;
    std::string op;
    std::string value;
};

BOOST_FUSION_ADAPT_STRUCT(
    WhereClause,
    (Column,col)
    (std::string, op)
    (std::string, value)
)

struct Request {
    std::vector<Column> columns;
    std::vector<std::string> tables;
    std::vector<WhereClause> clauses;
};

BOOST_FUSION_ADAPT_STRUCT(
    Request,
    (std::vector<Column>, columns)
    (std::vector<std::string>, tables)
    (std::vector<WhereClause>, clauses)
)
        template <typename Iterator>
        struct select_r
            : qi::grammar<Iterator, Request(), qi::space_type>
{
    qi::rule<Iterator, std::string(), qi::space_type> txt; // Match une string
    qi::rule<Iterator, Column(), qi::space_type> table_col; // Match une colonne
    qi::rule<Iterator, std::vector<Column>(), qi::space_type> select; // Match toute la section SELECT
    qi::rule<Iterator, std::vector<std::string>(), qi::space_type> from; // Matche la section FROM
    qi::rule<Iterator, Request(), qi::space_type> request; // Toute la requête
    qi::rule<Iterator, std::vector<WhereClause>(), qi::space_type> where;// section Where
    qi::rule<Iterator, std::string(), qi::space_type> bin_op; // Match une operator binaire telle que <, =...

    select_r() : select_r::base_type(request) {
        txt %= qi::lexeme[+(qi::alnum|'_')]; // Match du texte
        bin_op %=  qi::string("<=") | qi::string(">=") | qi::string("<>") | qi::string("<")  | qi::string(">") | qi::string("=") ;
        table_col %= -(txt >> '.') // (Nom de la table suivit de point) optionnel (operateur -)
                     >> txt; // Nom de la table obligatoire
        select  %= qi::lexeme["select"] >> table_col % ',' ; // La liste de table_col séparée par des ,
        from %= qi::lexeme["from"] >> txt % ',';
        where %= qi::lexeme["where"] >> (table_col >> bin_op >> txt) % qi::lexeme["and"];
        request %= select >> from >> -where;
    }

};

template<class T>
WhereWrapper<T> build_clause(std::vector<WhereClause> clauses) {
    WhereWrapper<T> wh(new BaseWhere<T>());
    Operator_e op;
    BOOST_FOREACH(auto clause, clauses) {
        if(clause.op == "=") op = EQ;
        else if(clause.op == "<") op = LT;
        else if(clause.op == "<=") op = LEQ;
        else if(clause.op == ">") op = GT;
        else if(clause.op == ">=") op = GEQ;
        else if(clause.op == "<>") op = NEQ;
        else throw "grrr";

        if(clause.col.column == "id")
            wh = wh && WHERE(ptr_id<T>(), op, clause.value);
        else if(clause.col.column == "idx")
            wh = wh && WHERE(ptr_idx<T>(), op, clause.value);
        else if(clause.col.column == "external_code")
            wh = wh && WHERE(ptr_external_code<T>(), op, clause.value);
    }
    return wh;
}

std::string unpluralize_table(const std::string& table_name){
    if(table_name == "cities"){
        return "city";
    }else{
        return table_name.substr(0, table_name.length() - 1);
    }
}

template<class T>
void set_value(google::protobuf::Message* message, const T& object, const std::string& column){
    const google::protobuf::Reflection* reflection = message->GetReflection();
    const google::protobuf::Descriptor* descriptor = message->GetDescriptor();
    const google::protobuf::FieldDescriptor* field_descriptor = descriptor->FindFieldByName(column);

    if(field_descriptor == NULL){
        throw unknown_member();
    }

    if(field_descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING){
        reflection->SetString(message, field_descriptor, get_string_value(object, column));
    }else if(field_descriptor->type() == google::protobuf::FieldDescriptor::TYPE_INT32){
        reflection->SetInt32(message, field_descriptor, get_int_value(object, column));
    }else{
        throw bad_type();
    }
}

google::protobuf::Message* get_message(pbnavitia::PTreferential* row, const std::string& table){
    const google::protobuf::Reflection* reflection = row->GetReflection();
    const google::protobuf::Descriptor* descriptor = row->GetDescriptor();
    std::string field = unpluralize_table(table);
    const google::protobuf::FieldDescriptor* field_descriptor = descriptor->FindFieldByName(field);
    return reflection->MutableMessage(row, field_descriptor);
}

template<class T>
std::vector< std::vector<col_t> > extract_data(std::vector<T> & rows, const Request & r) {
    pbnavitia::PTRefResponse pb_response;

    std::vector< std::vector<col_t> > result;
    Index2<boost::fusion::vector<T> > filtered(rows, build_clause<T>(r.clauses));
    BOOST_FOREACH(auto item, filtered){
        std::vector<col_t> row;
        pbnavitia::PTreferential * pb_row = pb_response.add_item();

        google::protobuf::Message* pb_message = get_message(pb_row, r.tables.at(0));

        BOOST_FOREACH(const Column & col, r.columns){
            row.push_back(get_value(*(boost::fusion::at_c<0>(item)), col.column));
            set_value(pb_message, *(boost::fusion::at_c<0>(item)), col.column);
        }
        result.push_back(row);
    }
    std::cout << "J'ai généré un protocol buffer de taille " <<     pb_response.ByteSize() << std::endl;
    //std::cout << pb_response.SerializeToOstream(&std::cout) << std::endl;
    return result;
}

struct unknown_table{};
std::vector< std::vector<col_t> > query(std::string request, Data & data){
    std::vector< std::vector<col_t> > result;
    std::string::iterator begin = request.begin();
    Request r;
    select_r<std::string::iterator> s;
    if (qi::phrase_parse(begin, request.end(), s, qi::space, r))
    {
        if(begin != request.end()) {
            std::cout << "Hrrrmmm on a pas tout parsé -_-'" << std::endl;
        }
    }
    else
        std::cout << "Parsage a échoué" << std::endl;

    if(r.tables.size() != 1){
        std::cout << "Pour l'instant on ne supporte que exactement une table" << std::endl;
        return result;
    }
    else {
        std::cout << "Table : " << r.tables[0] << std::endl;
    }

    std::string table = r.tables[0];

    /*if(table == "validity_pattern") {
        return extract_data(data.validity_patterns, r);
    }
    else*/ if(table == "lines") {
        return extract_data(data.lines, r);
    }
    else if(table == "routes") {
        return extract_data(data.routes, r);
    }
    /*else if(table == "vehicle_journey") {
        return extract_data(data.vehicle_journeys, r);
    }*/
    else if(table == "stop_points") {
        return extract_data(data.stop_points, r);
    }
    else if(table == "stop_areas") {
        return extract_data(data.stop_areas, r);
    }
  /*  else if(table == "stop_times"){
        return extract_data(data.stop_times, r);
    }*/

    throw unknown_table();
}

int main(int argc, char** argv){
    std::cout << "Chargement des données..." << std::flush;
    Data d;
    d.load_flz("data.nav.flz");
    std::cout << " effectué" << std::endl << std::endl;

    std::cout
            << "Statistiques :" << std::endl
            << "    Nombre de StopAreas : " << d.stop_areas.size() << std::endl
            << "    Nombre de StopPoints : " << d.stop_points.size() << std::endl
            << "    Nombre de lignes : " << d.lines.size() << std::endl
            << "    Nombre d'horaires : " << d.stop_times.size() << std::endl << std::endl;

    if(argc != 2)
        std::cout << "Il faut exactement un paramètre" << std::endl;
    else {
        auto result = query(argv[1], d);
        std::cout << "Il y a " << result.size() << " lignes de résultat" << std::endl;
        BOOST_FOREACH(auto row, result){
            BOOST_FOREACH(auto col, row){
                std::cout << col << ",\t";
            }
            std::cout << std::endl;
        }
    }
    return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 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 General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU 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.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Elasticity_test.h"
#include <SofaBaseMechanics/MechanicalObject.h>
#include <SofaDeformable/MeshSpringForceField.h>
#include <SofaBoundaryCondition/AffineMovementConstraint.h>
#include <sofa/defaulttype/VecTypes.h>

namespace sofa {

template <typename _DataTypes>
struct AffineMovementConstraint_test : public Elasticity_test<_DataTypes>
{
    typedef _DataTypes DataTypes;
    typedef typename DataTypes::Coord Coord;
    typedef typename DataTypes::VecCoord VecCoord;
    typedef typename DataTypes::VecDeriv VecDeriv;
    typedef typename DataTypes::Coord Coord;
    typedef typename DataTypes::Deriv Deriv;
    typedef typename DataTypes::CPos CPos;
    typedef typename Coord::value_type Real;
    typedef component::container::MechanicalObject<DataTypes> MechanicalObject;
    typedef typename component::interactionforcefield::MeshSpringForceField<DataTypes> MeshSpringForceField;

    /// Root of the scene graph
    simulation::Node::SPtr root;
    /// Tested simulation
    simulation::Simulation* simulation;
    /// Structure which contains current node and pointers to the mechanical object and the affine constraint
    PatchTestStruct<DataTypes> patchStruct;
    /// Tested Rotation: random rotation matrix
    defaulttype::Mat<3,3,Real> testedRotation;
    /// Tested Translation: random translation
    Coord testedTranslation;
    /// Seed for random value
    long seed;
    // Random generator
    sofa::helper::RandomGenerator randomGenerator;

     // Create the context for the scene
     void SetUp()
     {
        // Init simulation
        sofa::component::init();
        sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation());

         root = simulation::getSimulation()->createNewGraph("root");

         // Init seed with a random value between 0 and 100
         randomGenerator.initSeed( (long)time(0) );
         seed = randomGenerator.random<long>(0,100);

         // Create a scene with a regular grid
         patchStruct = this->createRegularGridScene(
                        root,  // attached to the root node
                        Vec<3,SReal>(0,0,0), // Start point of regular grid
                        Vec<3,SReal>(1,1,0), // End point of regular grid
                        5,5,1,  // Resolution of the regular grid
                        Vec<6,SReal>(-0.1,-0.1,0,1.1,1.1,0), // BoxRoi to find all mesh points
                        Vec<6,SReal>(-0.1,-0.1,0,1.1,1.1,0), // inclusive box of pair box roi
                        Vec<6,SReal>(0.1,0.1,0,0.9,0.9,0)); // included box of pair box roi

        simulation::Node::SPtr SquareNode = patchStruct.SquareNode;

        //Force field for 2D Grid
        typename MeshSpringForceField::SPtr meshSpringForceField = addNew<MeshSpringForceField> (SquareNode,"forceField");
        meshSpringForceField->setStiffness(10);

        // Init seed
        randomGenerator.initSeed(seed);

        // Random Rotation
        SReal x,y,z,w;
        x = 0;
        y = 0;
        z = 1;
        w = randomGenerator.random<SReal>(0.0,360.0);
        Quat quat(x,y,z,w);
        quat.normalize();
        quat.toMatrix(testedRotation);

        patchStruct.affineConstraint->m_rotation.setValue(testedRotation);

        // Random Translation
        for(size_t i=0;i<Coord::total_size;++i)
        {
            testedTranslation[i]=randomGenerator.random<SReal>(-2.0,2.0);
            if(i==2)
                testedTranslation[i]=0;
        }

        patchStruct.affineConstraint->m_translation.setValue(testedTranslation);
        patchStruct.affineConstraint->m_endConstraintTime.setValue(0.1);
    }

     // After simulation compare the positions of points to the theoretical positions.
     bool projectPosition(double convergenceAccuracy, double diffMaxBetweenSimulatedAndTheoreticalPosition)
     {
        // Init simulation
        sofa::simulation::getSimulation()->init(root.get());

        // Compute the theoretical final positions
        VecCoord finalPos;
        patchStruct.affineConstraint->getFinalPositions( finalPos,*patchStruct.dofs->write(core::VecCoordId::position()) );

        // Initialize
        size_t numNodes = finalPos.size();
        VecCoord xprev(numNodes);
        VecDeriv dx(numNodes);
        bool hasConverged = true;

        for (size_t i=0; i<numNodes; i++)
        {
            xprev[i] = CPos(0,0,0);
        }

        // Animate
        do
        {
            hasConverged = true;
            sofa::simulation::getSimulation()->animate(root.get(),0.5);
            typename MechanicalObject::ReadVecCoord x = patchStruct.dofs->readPositions();

            // Compute dx
            for (size_t i=0; i<x.size(); i++)
            {
                dx[i] = x[i]-xprev[i];
                // Test convergence
                if(dx[i].norm()>convergenceAccuracy) hasConverged = false;
            }

            // xprev = x
            for (size_t i=0; i<numNodes; i++)
            {
                xprev[i]=x[i];
            }
        }
        while(!hasConverged); // not converged

        // Get simulated positions
        typename MechanicalObject::WriteVecCoord x = patchStruct.dofs->writePositions();

        // Compare the theoretical positions and the simulated positions
        bool succeed=true;
        for(size_t i=0; i<finalPos.size(); i++ )
        {
            if((finalPos[i]-x[i]).norm()>diffMaxBetweenSimulatedAndTheoreticalPosition)
            {
                succeed = false;
                ADD_FAILURE() << "final Position of point " << i << " is wrong: " << x[i] << std::endl <<"the expected Position is " << finalPos[i] << std::endl
                    << "difference = " <<(finalPos[i]-x[i]).norm() << std::endl <<"rotation = " << testedRotation << std::endl << " translation = " << testedTranslation << std::endl
                    << "seed =" << seed;

            }
        }
        return succeed;
    }

};

// Define the list of DataTypes to instanciate
using testing::Types;
typedef Types<
    defaulttype::Vec3Types
> DataTypes; // the types to instanciate.

// Test suite for all the instanciations
TYPED_TEST_CASE(AffineMovementConstraint_test, DataTypes);
// first test case
TYPED_TEST( AffineMovementConstraint_test , testValue )
{
   ASSERT_TRUE( this->projectPosition(5e-6,5e-5));
}
}// namespace sofa

<commit_msg>FIX: Compilation on linux.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 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 General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU 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.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "Elasticity_test.h"
#include <SofaBaseMechanics/MechanicalObject.h>
#include <SofaDeformable/MeshSpringForceField.h>
#include <SofaBoundaryCondition/AffineMovementConstraint.h>
#include <sofa/defaulttype/VecTypes.h>

namespace sofa {

template <typename _DataTypes>
struct AffineMovementConstraint_test : public Elasticity_test<_DataTypes>
{
    typedef _DataTypes DataTypes;
    typedef typename DataTypes::Coord Coord;
    typedef typename DataTypes::VecCoord VecCoord;
    typedef typename DataTypes::VecDeriv VecDeriv;
    typedef typename DataTypes::Deriv Deriv;
    typedef typename DataTypes::CPos CPos;
    typedef typename Coord::value_type Real;
    typedef component::container::MechanicalObject<DataTypes> MechanicalObject;
    typedef typename component::interactionforcefield::MeshSpringForceField<DataTypes> MeshSpringForceField;

    /// Root of the scene graph
    simulation::Node::SPtr root;
    /// Tested simulation
    simulation::Simulation* simulation;
    /// Structure which contains current node and pointers to the mechanical object and the affine constraint
    PatchTestStruct<DataTypes> patchStruct;
    /// Tested Rotation: random rotation matrix
    defaulttype::Mat<3,3,Real> testedRotation;
    /// Tested Translation: random translation
    Coord testedTranslation;
    /// Seed for random value
    long seed;
    // Random generator
    sofa::helper::RandomGenerator randomGenerator;

     // Create the context for the scene
     void SetUp()
     {
        // Init simulation
        sofa::component::init();
        sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation());

         root = simulation::getSimulation()->createNewGraph("root");

         // Init seed with a random value between 0 and 100
         randomGenerator.initSeed( (long)time(0) );
         seed = randomGenerator.random<long>(0,100);

         // Create a scene with a regular grid
         patchStruct = this->createRegularGridScene(
                        root,  // attached to the root node
                        Vec<3,SReal>(0,0,0), // Start point of regular grid
                        Vec<3,SReal>(1,1,0), // End point of regular grid
                        5,5,1,  // Resolution of the regular grid
                        Vec<6,SReal>(-0.1,-0.1,0,1.1,1.1,0), // BoxRoi to find all mesh points
                        Vec<6,SReal>(-0.1,-0.1,0,1.1,1.1,0), // inclusive box of pair box roi
                        Vec<6,SReal>(0.1,0.1,0,0.9,0.9,0)); // included box of pair box roi

        simulation::Node::SPtr SquareNode = patchStruct.SquareNode;

        //Force field for 2D Grid
        typename MeshSpringForceField::SPtr meshSpringForceField = addNew<MeshSpringForceField> (SquareNode,"forceField");
        meshSpringForceField->setStiffness(10);

        // Init seed
        randomGenerator.initSeed(seed);

        // Random Rotation
        SReal x,y,z,w;
        x = 0;
        y = 0;
        z = 1;
        w = randomGenerator.random<SReal>(0.0,360.0);
        Quat quat(x,y,z,w);
        quat.normalize();
        quat.toMatrix(testedRotation);

        patchStruct.affineConstraint->m_rotation.setValue(testedRotation);

        // Random Translation
        for(size_t i=0;i<Coord::total_size;++i)
        {
            testedTranslation[i]=randomGenerator.random<SReal>(-2.0,2.0);
            if(i==2)
                testedTranslation[i]=0;
        }

        patchStruct.affineConstraint->m_translation.setValue(testedTranslation);
        patchStruct.affineConstraint->m_endConstraintTime.setValue(0.1);
    }

     // After simulation compare the positions of points to the theoretical positions.
     bool projectPosition(double convergenceAccuracy, double diffMaxBetweenSimulatedAndTheoreticalPosition)
     {
        // Init simulation
        sofa::simulation::getSimulation()->init(root.get());

        // Compute the theoretical final positions
        VecCoord finalPos;
        patchStruct.affineConstraint->getFinalPositions( finalPos,*patchStruct.dofs->write(core::VecCoordId::position()) );

        // Initialize
        size_t numNodes = finalPos.size();
        VecCoord xprev(numNodes);
        VecDeriv dx(numNodes);
        bool hasConverged = true;

        for (size_t i=0; i<numNodes; i++)
        {
            xprev[i] = CPos(0,0,0);
        }

        // Animate
        do
        {
            hasConverged = true;
            sofa::simulation::getSimulation()->animate(root.get(),0.5);
            typename MechanicalObject::ReadVecCoord x = patchStruct.dofs->readPositions();

            // Compute dx
            for (size_t i=0; i<x.size(); i++)
            {
                dx[i] = x[i]-xprev[i];
                // Test convergence
                if(dx[i].norm()>convergenceAccuracy) hasConverged = false;
            }

            // xprev = x
            for (size_t i=0; i<numNodes; i++)
            {
                xprev[i]=x[i];
            }
        }
        while(!hasConverged); // not converged

        // Get simulated positions
        typename MechanicalObject::WriteVecCoord x = patchStruct.dofs->writePositions();

        // Compare the theoretical positions and the simulated positions
        bool succeed=true;
        for(size_t i=0; i<finalPos.size(); i++ )
        {
            if((finalPos[i]-x[i]).norm()>diffMaxBetweenSimulatedAndTheoreticalPosition)
            {
                succeed = false;
                ADD_FAILURE() << "final Position of point " << i << " is wrong: " << x[i] << std::endl <<"the expected Position is " << finalPos[i] << std::endl
                    << "difference = " <<(finalPos[i]-x[i]).norm() << std::endl <<"rotation = " << testedRotation << std::endl << " translation = " << testedTranslation << std::endl
                    << "seed =" << seed;

            }
        }
        return succeed;
    }

};

// Define the list of DataTypes to instanciate
using testing::Types;
typedef Types<
    defaulttype::Vec3Types
> DataTypes; // the types to instanciate.

// Test suite for all the instanciations
TYPED_TEST_CASE(AffineMovementConstraint_test, DataTypes);
// first test case
TYPED_TEST( AffineMovementConstraint_test , testValue )
{
   ASSERT_TRUE( this->projectPosition(5e-6,5e-5));
}
}// namespace sofa

<|endoftext|>


<commit_before>// LICENSE/*{{{*/
/*
  sxc - Simple Xmpp Client
  Copyright (C) 2008 Dennis Felsing, Andreas Waidler

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 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 General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*}}}*/

// INCLUDES/*{{{*/

#include <string>

#include "InputDummy.hxx"

/*}}}*/

InputDummy::InputDummy(const std::string &filename)/*{{{*/
: _filename(filename)
{
}

/*}}}*/
std::string InputDummy::_createPath() const/*{{{*/
{
    return _filename;
}

/*}}}*/
const std::string &InputDummy::getLastInput() const/*{{{*/
{
    return _lastInput;
}

/*}}}*/
void InputDummy::_handleInput(const std::string &input)/*{{{*/
{
    _lastInput = input;
}

/*}}}*/

// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker

<commit_msg>tests/File/InputDummy.cxx: Added debug in _handleInput().<commit_after>// LICENSE/*{{{*/
/*
  sxc - Simple Xmpp Client
  Copyright (C) 2008 Dennis Felsing, Andreas Waidler

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 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 General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/*}}}*/

// INCLUDES/*{{{*/

#ifdef HAVE_CONFIG_H
#   include <config.hxx>
#   include <print.hxx>
#endif

#include <string>

#include "InputDummy.hxx"

/*}}}*/

InputDummy::InputDummy(const std::string &filename)/*{{{*/
: _filename(filename)
{
}

/*}}}*/
std::string InputDummy::_createPath() const/*{{{*/
{
    return _filename;
}

/*}}}*/
const std::string &InputDummy::getLastInput() const/*{{{*/
{
    return _lastInput;
}

/*}}}*/
void InputDummy::_handleInput(const std::string &input)/*{{{*/
{
#ifdef DEBUG
    printLog("INPUT: " + input);
#endif
    _lastInput = input;
}

/*}}}*/

// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker

<|endoftext|>


<commit_before>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>

#include "hadesmem/write.hpp"

#include <array>
#include <string>
#include <vector>

#define BOOST_TEST_MODULE write
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/test/unit_test.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"

#include "hadesmem/error.hpp"
#include "hadesmem/process.hpp"

// Boost.Test causes the following warning under GCC:
// error: base class 'struct boost::unit_test::ut_detail::nil_t' has a
// non-virtual destructor [-Werror=effc++]
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)

BOOST_AUTO_TEST_CASE(write_pod)
{
  hadesmem::Process const process(::GetCurrentProcessId());

  struct TestPODType
  {
    int a;
    char* b;
    wchar_t c;
    long long d;
  };

  TestPODType test_pod_type = { 1, 0, L'a', 1234567812345678 };
  TestPODType test_pod_type_2 = { -1, 0, L'x', 9876543210 };
  Write(process, &test_pod_type, test_pod_type_2);
  BOOST_CHECK_EQUAL(std::memcmp(&test_pod_type, &test_pod_type_2,
    sizeof(test_pod_type)), 0);
}

BOOST_AUTO_TEST_CASE(write_string)
{
  hadesmem::Process const process(::GetCurrentProcessId());

  std::string const test_string = "Narrow test string.";
  std::vector<char> test_string_buf(test_string.size() + 1);
  using std::begin;
  using std::end;
  std::copy(begin(test_string), end(test_string),
    test_string_buf.data());
  std::string const test_string_str(test_string_buf.data());
  BOOST_CHECK_EQUAL_COLLECTIONS(begin(test_string), end(test_string),
    begin(test_string_str), end(test_string_str));
  auto const test_string_rev = std::string(test_string.rbegin(),
    test_string.rend());
  WriteString(process, test_string_buf.data(), test_string_rev);
  auto const new_test_string_rev = std::string(test_string_buf.data());
  BOOST_CHECK_EQUAL_COLLECTIONS(new_test_string_rev.cbegin(),
    new_test_string_rev.cend(), test_string_rev.cbegin(), test_string_rev.cend());

}

BOOST_AUTO_TEST_CASE(write_vector)
{
  hadesmem::Process const process(::GetCurrentProcessId());

  std::array<int, 10> int_list = {{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }};
  std::vector<int> int_list_rev(int_list.crbegin(), int_list.crend());
  WriteVector(process, &int_list, int_list_rev);
  BOOST_CHECK_EQUAL_COLLECTIONS(int_list.cbegin(), int_list.cend(),
    int_list_rev.cbegin(), int_list_rev.cend());
}
<commit_msg>* Formatting.<commit_after>// Copyright Joshua Boyce 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// This file is part of HadesMem.
// <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>

#include "hadesmem/write.hpp"

#include <array>
#include <string>
#include <vector>

#define BOOST_TEST_MODULE write
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/test/unit_test.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"

#include "hadesmem/error.hpp"
#include "hadesmem/process.hpp"

// Boost.Test causes the following warning under GCC:
// error: base class 'struct boost::unit_test::ut_detail::nil_t' has a
// non-virtual destructor [-Werror=effc++]
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)

BOOST_AUTO_TEST_CASE(write_pod)
{
  hadesmem::Process const process(::GetCurrentProcessId());

  struct TestPODType
  {
    int a;
    char* b;
    wchar_t c;
    long long d;
  };

  TestPODType test_pod_type = { 1, 0, L'a', 1234567812345678 };
  TestPODType test_pod_type_2 = { -1, 0, L'x', 9876543210 };
  Write(process, &test_pod_type, test_pod_type_2);
  BOOST_CHECK_EQUAL(std::memcmp(&test_pod_type, &test_pod_type_2,
    sizeof(test_pod_type)), 0);
}

BOOST_AUTO_TEST_CASE(write_string)
{
  hadesmem::Process const process(::GetCurrentProcessId());

  std::string const test_string = "Narrow test string.";
  std::vector<char> test_string_buf(test_string.size() + 1);
  using std::begin;
  using std::end;
  std::copy(begin(test_string), end(test_string),
    test_string_buf.data());
  std::string const test_string_str(test_string_buf.data());
  BOOST_CHECK_EQUAL_COLLECTIONS(begin(test_string), end(test_string),
    begin(test_string_str), end(test_string_str));
  auto const test_string_rev = std::string(test_string.rbegin(),
    test_string.rend());
  WriteString(process, test_string_buf.data(), test_string_rev);
  auto const new_test_string_rev = std::string(test_string_buf.data());
  BOOST_CHECK_EQUAL_COLLECTIONS(new_test_string_rev.cbegin(),
    new_test_string_rev.cend(), test_string_rev.cbegin(),
    test_string_rev.cend());

}

BOOST_AUTO_TEST_CASE(write_vector)
{
  hadesmem::Process const process(::GetCurrentProcessId());

  std::array<int, 10> int_list = {{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }};
  std::vector<int> int_list_rev(int_list.crbegin(), int_list.crend());
  WriteVector(process, &int_list, int_list_rev);
  BOOST_CHECK_EQUAL_COLLECTIONS(int_list.cbegin(), int_list.cend(),
    int_list_rev.cbegin(), int_list_rev.cend());
}
<|endoftext|>


<commit_before>// Compare numerically calculated C-V curves with analytic solution
using namespace GeFiCa;
const int n=2001;
// get capacitance based on C=epsilon*A/d
double GetCfromDepletionDepth(double voltage, double thickness)
{
   // calculate fields
   Planar1D detector(n);
   detector.Thickness=thickness;
   detector.V0=voltage; // for bottom electrode
   detector.V1=0*volt; // for top electrode

   TF3 *fi = new TF3("f","-1e10"); // 1/cm3
   detector.SetImpurity(fi);
   detector.Csor=1.999;
   detector.MaxIterations=20000;
   detector.CalculatePotential(kSOR2);
   delete fi;

   //search for depletion depth
   double up=thickness, down=0, depth=thickness;
   while(up-down>1e-3) {
      depth=(down+up)/2;
      if(detector.GetV(depth)>0) down=depth;
      if(detector.GetV(depth)<=0) up=depth;
   }

   double A = 1*cm*1*cm;
   return epsilon*A/depth;
}
//______________________________________________________________________________
// use GefiCa::X::GetC()
double GetCfromGeFiCa(double voltage, double thickness)
{
   // calculate fields
   Planar1D detector(n);
   detector.Thickness=thickness;
   detector.V0=voltage; // for bottom electrode
   detector.V1=0*volt; // for top electrode

   TF3 *fi = new TF3("f","-1e10"); // 1/cm3
   detector.SetImpurity(fi);
   detector.Csor=1.999;
   detector.MaxIterations=20000;
   double c=detector.GetC();
   delete fi;

   return c;
}
//______________________________________________________________________________
//
double GetCanalytically(double voltage, double thickness)
{
   //voltage=ax^2+c2x+c1
   //c1=0, when voltage=0 at x=0
   //c2=-ad, when E=dV/dx=0 at x=0, where just depleted
   //a is rho/epsilon
   //voltage=-ax^2/2, solve voltage when x=depth
   double rho=-1e10/cm3*Qe;
   double depth=TMath::Sqrt(-2*epsilon*voltage/rho);
   if (depth>thickness) depth=thickness;

   double A = 1*cm*1*cm;
   return epsilon*A/depth;
}
//______________________________________________________________________________
//
void verifyCV()
{
   double thickness=1*cm;
   const int np=16;
   Double_t V[np], Cn[np], Ca[np],Cg[np];
   for (Int_t i=0;i<np;i++) {
      V[i] = (i+1)*50*volt; Printf("voltage: %.0f V", V[i]);
      Cn[i] = GetCfromDepletionDepth(V[i],thickness)/pF;
      Cg[i] = GetCfromGeFiCa(V[i],thickness)/pF;
      Ca[i] = GetCanalytically(V[i],thickness)/pF;
   }

   TGraph *gn = new TGraph(np,V,Cn); gn->SetMarkerStyle(22);
   TGraph *gg = new TGraph(np,V,Cg); gg->SetMarkerStyle(24);
   TGraph *ga = new TGraph(np,V,Ca); ga->SetMarkerStyle(25);

   gStyle->SetPadLeftMargin(0.08);
   gStyle->SetPadRightMargin(0.01);
   gStyle->SetTitleOffset(0.75,"y");
   TMultiGraph *gs = new TMultiGraph; gs->Add(gn); gs->Add(gg); gs->Add(ga);
   gs->SetTitle(";Bias [V];Capacitance per cm^{2} [pF]"); gs->Draw("pal");

   TLegend *l = new TLegend(0.5,0.6,0.97,0.97);
   l->AddEntry(ga,"#varepsilon A/d, analytically","pl");
   l->AddEntry(gn,"#varepsilon A/d, numerically","pl");
   l->AddEntry(gg,"GeFiCa::X::GetC()","pl");
   l->Draw();
}
<commit_msg>reduced number of grid points<commit_after>// Compare numerically calculated C-V curves with analytic solution
using namespace GeFiCa;
const int n=401;
// get capacitance based on C=epsilon*A/d
double GetCfromDepletionDepth(double voltage, double thickness)
{
   // calculate fields
   Planar1D detector(n);
   detector.Thickness=thickness;
   detector.V0=voltage; // for bottom electrode
   detector.V1=0*volt; // for top electrode
   detector.SetAverageImpurity(-1e10/cm3);
   detector.CalculatePotential();

   //search for depletion depth
   double up=thickness, down=0, depth=thickness;
   while(up-down>1e-3) {
      depth=(down+up)/2;
      if(detector.GetV(depth)>0) down=depth;
      if(detector.GetV(depth)<=0) up=depth;
   }

   double A = 1*cm*1*cm;
   return epsilon*A/depth;
}
//______________________________________________________________________________
// use GefiCa::X::GetC()
double GetCfromGeFiCa(double voltage, double thickness)
{
   // calculate fields
   Planar1D detector(n);
   detector.Thickness=thickness;
   detector.V0=voltage; // for bottom electrode
   detector.V1=0*volt; // for top electrode
   detector.SetAverageImpurity(-1e10/cm3);
   return detector.GetC();
}
//______________________________________________________________________________
//
double GetCanalytically(double voltage, double thickness)
{
   //voltage=ax^2+c2x+c1
   //c1=0, when voltage=0 at x=0
   //c2=-ad, when E=dV/dx=0 at x=0, where just depleted
   //a is rho/epsilon
   //voltage=-ax^2/2, solve voltage when x=depth
   double rho=-1e10/cm3*Qe;
   double depth=TMath::Sqrt(-2*epsilon*voltage/rho);
   if (depth>thickness) depth=thickness;

   double A = 1*cm*1*cm;
   return epsilon*A/depth;
}
//______________________________________________________________________________
//
void verifyCV()
{
   double thickness=1*cm;
   const int np=16;
   Double_t V[np], Cn[np], Ca[np],Cg[np];
   for (Int_t i=0;i<np;i++) {
      V[i] = (i+2)*50*volt; Printf("voltage: %.0f V", V[i]);
      Cn[i] = GetCfromDepletionDepth(V[i],thickness)/pF;
      Cg[i] = GetCfromGeFiCa(V[i],thickness)/pF;
      Ca[i] = GetCanalytically(V[i],thickness)/pF;
   }

   TGraph *gn = new TGraph(np,V,Cn); gn->SetMarkerStyle(22);
   TGraph *gg = new TGraph(np,V,Cg); gg->SetMarkerStyle(24);
   TGraph *ga = new TGraph(np,V,Ca); ga->SetMarkerStyle(25);

   gStyle->SetPadLeftMargin(0.09);
   gStyle->SetPadRightMargin(0.01);
   gStyle->SetTitleOffset(0.85,"y");
   TMultiGraph *gs = new TMultiGraph; gs->Add(gn); gs->Add(gg); gs->Add(ga);
   gs->SetTitle(";Bias [V];Capacitance per cm^{2} [pF]"); gs->Draw("pal");

   TLegend *l = new TLegend(0.5,0.6,0.97,0.97);
   l->AddEntry(ga,"#varepsilon A/d, analytically","pl");
   l->AddEntry(gn,"#varepsilon A/d, numerically","pl");
   l->AddEntry(gg,"GeFiCa::X::GetC()","pl");
   l->Draw();
}
<|endoftext|>


<commit_before>/**************************************************************************
 *
 * Copyright 2011-2012 Jose Fonseca
 * All Rights Reserved.
 *
 * 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.
 *
 **************************************************************************/

#ifndef _RETRACE_HPP_
#define _RETRACE_HPP_

#include <assert.h>
#include <string.h>
#include <stdint.h>

#include <list>
#include <map>
#include <ostream>

#include "trace_model.hpp"
#include "trace_parser.hpp"

namespace retrace {

extern trace::Parser parser;

/**
 * Handle map.
 *
 * It is just like a regular std::map<T, T> container, but lookups of missing
 * keys return the key instead of default constructor.
 *
 * This is necessary for several GL named objects, where one can either request
 * the implementation to generate an unique name, or pick a value never used
 * before.
 *
 * XXX: In some cases, instead of returning the key, it would make more sense
 * to return an unused data value (e.g., container count).
 */
template <class T>
class map
{
private:
    typedef std::map<T, T> base_type;
    base_type base;

public:

    T & operator[] (const T &key) {
        typename base_type::iterator it;
        it = base.find(key);
        if (it == base.end()) {
            return (base[key] = key);
        }
        return it->second;
    }

    const T & operator[] (const T &key) const {
        typename base_type::const_iterator it;
        it = base.find(key);
        if (it == base.end()) {
            return (base[key] = key);
        }
        return it->second;
    }
};

/**
 * Similar to alloca(), but implemented with malloc.
 */
class ScopedAllocator
{
private:
    uintptr_t next;

public:
    ScopedAllocator() :
        next(0) {
    }

    inline void *
    alloc(size_t size) {
        if (!size) {
            return NULL;
        }

        uintptr_t * buf = static_cast<uintptr_t *>(malloc(sizeof(uintptr_t) + size));
        if (!buf) {
            return NULL;
        }

        *buf = next;
        next = reinterpret_cast<uintptr_t>(buf);
        assert((next & 1) == 0);

        return static_cast<void *>(&buf[1]);
    }

    template< class T >
    inline T *
    alloc(size_t n = 1) {
        return static_cast<T *>(alloc(sizeof(T) * n));
    }

    /**
     * Allocate an array with the same dimensions as the specified value.
     */
    template< class T >
    inline T *
    alloc(const trace::Value *value) {
        const trace::Array *array = dynamic_cast<const trace::Array *>(value);
        if (array) {
            return alloc<T>(array->size());
        }
        const trace::Null *null = dynamic_cast<const trace::Null *>(value);
        if (null) {
            return NULL;
        }
        assert(0);
        return NULL;
    }

    /**
     * Prevent this pointer from being automatically freed.
     */
    template< class T >
    inline void
    bind(T *ptr) {
        if (ptr) {
            reinterpret_cast<uintptr_t *>(ptr)[-1] |= 1;
        }
    }

    inline
    ~ScopedAllocator() {
        while (next) {
            uintptr_t temp = *reinterpret_cast<uintptr_t *>(next);

            bool bind = temp & 1;
            temp &= ~1;

            if (!bind) {
                free(reinterpret_cast<void *>(next));
            }

            next = temp;
        }
    }
};

void
addRegion(unsigned long long address, void *buffer, unsigned long long size);

void
delRegionByPointer(void *ptr);

void *
toPointer(trace::Value &value, bool bind = false);

/**
 * Output verbosity when retracing files.
 */
extern int verbosity;

/**
 * Add profiling data to the dump when retracing.
 */
extern bool profiling;

std::ostream &warning(trace::Call &call);

void ignore(trace::Call &call);
void unsupported(trace::Call &call);

typedef void (*Callback)(trace::Call &call);

struct Entry {
    const char *name;
    Callback callback;
};

struct stringComparer {
  bool operator() (const char *a, const  char *b) const {
    return strcmp(a, b) < 0;
  }
};

extern const Entry stdc_callbacks[];

class Retracer
{
    typedef std::map<const char *, Callback, stringComparer> Map;
    Map map;

    std::vector<Callback> callbacks;

public:
    Retracer() {
        addCallbacks(stdc_callbacks);
    }

    virtual ~Retracer() {}

    void addCallback(const Entry *entry);
    void addCallbacks(const Entry *entries);

    void retrace(trace::Call &call);
};

} /* namespace retrace */

#endif /* _RETRACE_HPP_ */
<commit_msg>Preserve non-NULL arrays, even when length is zero.<commit_after>/**************************************************************************
 *
 * Copyright 2011-2012 Jose Fonseca
 * All Rights Reserved.
 *
 * 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.
 *
 **************************************************************************/

#ifndef _RETRACE_HPP_
#define _RETRACE_HPP_

#include <assert.h>
#include <string.h>
#include <stdint.h>

#include <list>
#include <map>
#include <ostream>

#include "trace_model.hpp"
#include "trace_parser.hpp"

namespace retrace {

extern trace::Parser parser;

/**
 * Handle map.
 *
 * It is just like a regular std::map<T, T> container, but lookups of missing
 * keys return the key instead of default constructor.
 *
 * This is necessary for several GL named objects, where one can either request
 * the implementation to generate an unique name, or pick a value never used
 * before.
 *
 * XXX: In some cases, instead of returning the key, it would make more sense
 * to return an unused data value (e.g., container count).
 */
template <class T>
class map
{
private:
    typedef std::map<T, T> base_type;
    base_type base;

public:

    T & operator[] (const T &key) {
        typename base_type::iterator it;
        it = base.find(key);
        if (it == base.end()) {
            return (base[key] = key);
        }
        return it->second;
    }

    const T & operator[] (const T &key) const {
        typename base_type::const_iterator it;
        it = base.find(key);
        if (it == base.end()) {
            return (base[key] = key);
        }
        return it->second;
    }
};

/**
 * Similar to alloca(), but implemented with malloc.
 */
class ScopedAllocator
{
private:
    uintptr_t next;

public:
    ScopedAllocator() :
        next(0) {
    }

    inline void *
    alloc(size_t size) {
        /* Always return valid address, even when size is zero */
        size = std::max(size, sizeof(uintptr_t));

        uintptr_t * buf = static_cast<uintptr_t *>(malloc(sizeof(uintptr_t) + size));
        if (!buf) {
            return NULL;
        }

        *buf = next;
        next = reinterpret_cast<uintptr_t>(buf);
        assert((next & 1) == 0);

        return static_cast<void *>(&buf[1]);
    }

    template< class T >
    inline T *
    alloc(size_t n = 1) {
        return static_cast<T *>(alloc(sizeof(T) * n));
    }

    /**
     * Allocate an array with the same dimensions as the specified value.
     */
    template< class T >
    inline T *
    alloc(const trace::Value *value) {
        const trace::Array *array = dynamic_cast<const trace::Array *>(value);
        if (array) {
            return alloc<T>(array->size());
        }
        const trace::Null *null = dynamic_cast<const trace::Null *>(value);
        if (null) {
            return NULL;
        }
        assert(0);
        return NULL;
    }

    /**
     * Prevent this pointer from being automatically freed.
     */
    template< class T >
    inline void
    bind(T *ptr) {
        if (ptr) {
            reinterpret_cast<uintptr_t *>(ptr)[-1] |= 1;
        }
    }

    inline
    ~ScopedAllocator() {
        while (next) {
            uintptr_t temp = *reinterpret_cast<uintptr_t *>(next);

            bool bind = temp & 1;
            temp &= ~1;

            if (!bind) {
                free(reinterpret_cast<void *>(next));
            }

            next = temp;
        }
    }
};

void
addRegion(unsigned long long address, void *buffer, unsigned long long size);

void
delRegionByPointer(void *ptr);

void *
toPointer(trace::Value &value, bool bind = false);

/**
 * Output verbosity when retracing files.
 */
extern int verbosity;

/**
 * Add profiling data to the dump when retracing.
 */
extern bool profiling;

std::ostream &warning(trace::Call &call);

void ignore(trace::Call &call);
void unsupported(trace::Call &call);

typedef void (*Callback)(trace::Call &call);

struct Entry {
    const char *name;
    Callback callback;
};

struct stringComparer {
  bool operator() (const char *a, const  char *b) const {
    return strcmp(a, b) < 0;
  }
};

extern const Entry stdc_callbacks[];

class Retracer
{
    typedef std::map<const char *, Callback, stringComparer> Map;
    Map map;

    std::vector<Callback> callbacks;

public:
    Retracer() {
        addCallbacks(stdc_callbacks);
    }

    virtual ~Retracer() {}

    void addCallback(const Entry *entry);
    void addCallbacks(const Entry *entries);

    void retrace(trace::Call &call);
};

} /* namespace retrace */

#endif /* _RETRACE_HPP_ */
<|endoftext|>