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

#include <cmath>
#include <fstream>
#include <numeric>

#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/common/math/math_utils.h"
#include "modules/prediction/common/prediction_util.h"

namespace apollo {
namespace prediction {

void MLPEvaluator::Clear() {
  obstacle_feature_values_map_.clear();
}

void MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) {
  Clear();
  if (obstacle_ptr == nullptr) {
    AERROR << "Invalid obstacle.";
    return;
  }

  int id = obstacle_ptr->id();
  Feature latest_feature = obstacle_ptr->latest_feature();
  if (!latest_feature.IsInitialized()) {
    ADEBUG << "Obstacle [" << id << "] has no latest feature.";
    return;
  }

  Lane* lane_ptr = latest_feature.mutable_lane();
  if (!latest_feature.has_lane() || lane_ptr == nullptr) {
    ADEBUG << "Obstacle [" << id << "] has no lane feature.";
    return;
  }

  LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph();
  if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) {
    ADEBUG << "Obstacle [" << id << "] has no lane graph.";
    return;
  }

  if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) {
    ADEBUG << "Obstacle [" << id << "] has no lane sequences.";
    return;
  }

  for (int i = 0;
      i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) {
    LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
    CHECK(lane_sequence_ptr != nullptr);
    ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr);
  }
}

void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,
                                        LaneSequence* lane_sequence_ptr) {
  feature_values_.clear();
  int id = obstacle_ptr->id();
  std::vector<double> obstacle_feature_values;
  if (obstacle_feature_values_map_.find(id) ==
      obstacle_feature_values_map_.end()) {
    SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
  } else {
    obstacle_feature_values = obstacle_feature_values_map_[id];
  }

  if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
    ADEBUG << "Obstacle [" << id << "] has fewer than "
           << "expected obstacle feature_values "
           << obstacle_feature_values.size() << ".";
    return;
  }

  std::vector<double> lane_feature_values;
  SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
  if (lane_feature_values.size() != LANE_FEATURE_SIZE) {
    ADEBUG << "Obstacle [" << id << "] has fewer than "
           << "expected lane feature_values"
           << lane_feature_values.size() << ".";
    return;
  }

  feature_values_.insert(feature_values_.end(),
      lane_feature_values.begin(), lane_feature_values.end());
  feature_values_.insert(feature_values_.end(),
      lane_feature_values.begin(), lane_feature_values.end());
}

void MLPEvaluator::SetObstacleFeatureValues(
    Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
  feature_values->clear();
  feature_values->reserve(OBSTACLE_FEATURE_SIZE);

  std::vector<double> thetas;
  std::vector<double> lane_ls;
  std::vector<double> dist_lbs;
  std::vector<double> dist_rbs;
  std::vector<int> lane_types;
  std::vector<double> speeds;
  std::vector<double> timestamps;

  double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration;
  int count = 0;
  for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {
    const Feature& feature = obstacle_ptr->feature(i);
    if (!feature.IsInitialized()) {
      continue;
    }
    if (apollo::common::math::DoubleCompare(
            feature.timestamp(), duration) < 0) {
      break;
    }
    if (feature.has_lane() && feature.lane().has_lane_feature()) {
      thetas.push_back(feature.lane().lane_feature().angle_diff());
      lane_ls.push_back(feature.lane().lane_feature().lane_l());
      dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());
      dist_rbs.push_back(
          feature.lane().lane_feature().dist_to_right_boundary());
      lane_types.push_back(feature.lane().lane_feature().lane_turn_type());
      timestamps.push_back(feature.timestamp());
      if (FLAGS_enable_kf_tracking) {
        speeds.push_back(feature.t_speed());
      } else {
        speeds.push_back(feature.speed());
      }
      ++count;
    }
  }
  if (count <= 0) {
    return;
  }
  double theta_mean =
      std::accumulate(thetas.begin(), thetas.end(), 0.0) / thetas.size();
  double theta_filtered =
      (thetas.size() > 1) ? (thetas[0] + thetas[1]) / 2.0 : thetas[0];
  double lane_l_mean =
      std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) / lane_ls.size();
  double lane_l_filtered =
      (lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) / 2.0 : lane_ls[0];
  double speed_mean =
      std::accumulate(speeds.begin(), speeds.end(), 0.0) / speeds.size();
  double speed_lateral = sin(theta_filtered) * speed_mean;
  double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0;
  double time_to_lb = (abs(speed_lateral) > 0.05)
                          ? dist_lbs[0] / speed_lateral
                          : 20 * dist_lbs[0] * speed_sign;
  double time_to_rb = (abs(speed_lateral) > 0.05)
                          ? -1 * dist_rbs[0] / speed_lateral
                          : -20 * dist_rbs[0] * speed_sign;
  double time_diff = timestamps.front() - timestamps.back();
  double dist_lb_rate = (timestamps.size() > 1)
                            ? (dist_lbs.front() - dist_lbs.back()) / time_diff
                            : 0.0;
  double dist_rb_rate = (timestamps.size() > 1)
                            ? (dist_rbs.front() - dist_rbs.back()) / time_diff
                            : 0.0;
  // setup obstacle feature values
  feature_values->push_back(theta_filtered);
  feature_values->push_back(theta_mean);
  feature_values->push_back(theta_filtered - theta_mean);
  feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1]
                                            : thetas[0]);
  feature_values->push_back(lane_l_filtered);
  feature_values->push_back(lane_l_mean);
  feature_values->push_back(lane_l_filtered - lane_l_mean);
  feature_values->push_back(speed_mean);
  feature_values->push_back(dist_lbs.front());
  feature_values->push_back(dist_lb_rate);
  feature_values->push_back(time_to_lb);
  feature_values->push_back(dist_rbs.front());
  feature_values->push_back(dist_rb_rate);
  feature_values->push_back(time_to_rb);
  // feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0
  //                                                                    : 0.0);
  // feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0
  //                                                                     : 0.0);
  // feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0
  //                                                                   : 0.0);
  // feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0
  //                                                                   : 0.0);
}

void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,
    LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {
  feature_values->clear();
  feature_values->reserve(LANE_FEATURE_SIZE);
  const Feature& feature = obstacle_ptr->latest_feature();
  if (!feature.IsInitialized()) {
    ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature.";
    return;
  } else if (!feature.has_position()) {
    ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
    return;
  }

  double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading()
                                            : feature.theta();
  for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {
    if (feature_values->size() >= LANE_FEATURE_SIZE) {
      break;
    }
    const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);
    for (int j = 0; j < lane_segment.lane_point_size(); ++j) {
      if (feature_values->size() >= LANE_FEATURE_SIZE) {
        break;
      }
      const LanePoint& lane_point = lane_segment.lane_point(j);
      if (!lane_point.has_position()) {
        AERROR << "Lane point has no position.";
        continue;
      }
      double diff_x = lane_point.position().x() - feature.position().x();
      double diff_y = lane_point.position().y() - feature.position().y();
      double angle = std::atan2(diff_x, diff_y);
      feature_values->push_back(std::sin(angle - heading));
      feature_values->push_back(lane_point.relative_l());
      feature_values->push_back(lane_point.heading());
      feature_values->push_back(lane_point.angle_diff());
    }
  }

  std::size_t size = feature_values->size();
  while (size >= 4 && size < LANE_FEATURE_SIZE) {
    double heading_diff = feature_values->operator[](size - 4);
    double lane_l_diff = feature_values->operator[](size - 3);
    double heading = feature_values->operator[](size - 2);
    double angle_diff = feature_values->operator[](size - 1);
    feature_values->push_back(heading_diff);
    feature_values->push_back(lane_l_diff);
    feature_values->push_back(heading);
    feature_values->push_back(angle_diff);
    size = feature_values->size();
  }
}

void MLPEvaluator::LoadModel(const std::string& model_file) {
  model_ptr_.reset(new FnnVehicleModel());
  CHECK(model_ptr_ != nullptr);
  std::fstream file_stream(model_file, std::ios::in | std::ios::binary);
  if (!file_stream.good()) {
    AERROR << "Unable to open the model file: " << model_file << ".";
    return;
  }
  if (!model_ptr_->ParseFromIstream(&file_stream)) {
    AERROR << "Unable to load the model file: " << model_file << ".";
    return;
  }
  ADEBUG << "Succeeded in loading the model file: " << model_file << ".";
}

double MLPEvaluator::ComputeProbability() {
  CHECK(model_ptr_.get() != nullptr);
  double probability = 0.0;

  if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) {
    AERROR << "Model feature size not consistent with model proto definition.";
    return probability;
  }
  std::vector<double> layer_input;
  layer_input.reserve(model_ptr_->dim_input());
  std::vector<double> layer_output;

  // normalization
  for (int i = 0; i < model_ptr_->dim_input(); ++i) {
    double mean = model_ptr_->samples_mean().columns(i);
    double std = model_ptr_->samples_std().columns(i);
    layer_input.push_back(
        apollo::prediction::util::Normalize(feature_values_[i], mean, std));
  }

  for (int i = 0; i < model_ptr_->num_layer(); ++i) {
    if (i > 0) {
      layer_input.clear();
      layer_output.swap(layer_output);
    }
    const Layer& layer = model_ptr_->layer(i);
    for (int col = 0; col < layer.layer_output_dim(); ++col) {
      double neuron_output = layer.layer_bias().columns(col);
      for (int row = 0; row < layer.layer_input_dim(); ++row) {
        double weight = layer.layer_input_weight().rows(row).columns(col);
        neuron_output += (layer_input[row] * weight);
      }
      if (layer.layer_activation_type() == "relu") {
        neuron_output = apollo::prediction::util::Relu(neuron_output);
      } else if (layer.layer_activation_type() == "sigmoid") {
        neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
      } else if (layer.layer_activation_type() == "tanh") {
        neuron_output = std::tanh(neuron_output);
      } else {
        LOG(ERROR) << "Undefined activation func: "
                   << layer.layer_activation_type()
                   << ", and default sigmoid will be used instead.";
        neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
      }
      layer_output.push_back(neuron_output);
    }
  }

  if (layer_output.size() != 1) {
    AERROR << "Model output layer has incorrect # outputs: "
           << layer_output.size();
  } else {
    probability = layer_output[0];
  }

  return probability;
}

}  // namespace prediction
}  // namespace apollo
<commit_msg>add writing back the lane sequence probability to the feature proto<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include <cmath>
#include <fstream>
#include <numeric>

#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/common/math/math_utils.h"
#include "modules/prediction/common/prediction_util.h"

namespace apollo {
namespace prediction {

void MLPEvaluator::Clear() {
  obstacle_feature_values_map_.clear();
}

void MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) {
  Clear();
  if (obstacle_ptr == nullptr) {
    AERROR << "Invalid obstacle.";
    return;
  }

  int id = obstacle_ptr->id();
  Feature latest_feature = obstacle_ptr->latest_feature();
  if (!latest_feature.IsInitialized()) {
    ADEBUG << "Obstacle [" << id << "] has no latest feature.";
    return;
  }

  Lane* lane_ptr = latest_feature.mutable_lane();
  if (!latest_feature.has_lane() || lane_ptr == nullptr) {
    ADEBUG << "Obstacle [" << id << "] has no lane feature.";
    return;
  }

  LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph();
  if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) {
    ADEBUG << "Obstacle [" << id << "] has no lane graph.";
    return;
  }

  if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) {
    ADEBUG << "Obstacle [" << id << "] has no lane sequences.";
    return;
  }

  for (int i = 0;
      i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) {
    LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
    CHECK(lane_sequence_ptr != nullptr);
    ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr);
    double probability = ComputeProbability();
    lane_sequence_ptr->set_probability(probability);
  }
}

void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,
                                        LaneSequence* lane_sequence_ptr) {
  feature_values_.clear();
  int id = obstacle_ptr->id();
  std::vector<double> obstacle_feature_values;
  if (obstacle_feature_values_map_.find(id) ==
      obstacle_feature_values_map_.end()) {
    SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
  } else {
    obstacle_feature_values = obstacle_feature_values_map_[id];
  }

  if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
    ADEBUG << "Obstacle [" << id << "] has fewer than "
           << "expected obstacle feature_values "
           << obstacle_feature_values.size() << ".";
    return;
  }

  std::vector<double> lane_feature_values;
  SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
  if (lane_feature_values.size() != LANE_FEATURE_SIZE) {
    ADEBUG << "Obstacle [" << id << "] has fewer than "
           << "expected lane feature_values"
           << lane_feature_values.size() << ".";
    return;
  }

  feature_values_.insert(feature_values_.end(),
      lane_feature_values.begin(), lane_feature_values.end());
  feature_values_.insert(feature_values_.end(),
      lane_feature_values.begin(), lane_feature_values.end());
}

void MLPEvaluator::SetObstacleFeatureValues(
    Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
  feature_values->clear();
  feature_values->reserve(OBSTACLE_FEATURE_SIZE);

  std::vector<double> thetas;
  std::vector<double> lane_ls;
  std::vector<double> dist_lbs;
  std::vector<double> dist_rbs;
  std::vector<int> lane_types;
  std::vector<double> speeds;
  std::vector<double> timestamps;

  double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration;
  int count = 0;
  for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {
    const Feature& feature = obstacle_ptr->feature(i);
    if (!feature.IsInitialized()) {
      continue;
    }
    if (apollo::common::math::DoubleCompare(
            feature.timestamp(), duration) < 0) {
      break;
    }
    if (feature.has_lane() && feature.lane().has_lane_feature()) {
      thetas.push_back(feature.lane().lane_feature().angle_diff());
      lane_ls.push_back(feature.lane().lane_feature().lane_l());
      dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());
      dist_rbs.push_back(
          feature.lane().lane_feature().dist_to_right_boundary());
      lane_types.push_back(feature.lane().lane_feature().lane_turn_type());
      timestamps.push_back(feature.timestamp());
      if (FLAGS_enable_kf_tracking) {
        speeds.push_back(feature.t_speed());
      } else {
        speeds.push_back(feature.speed());
      }
      ++count;
    }
  }
  if (count <= 0) {
    return;
  }
  double theta_mean =
      std::accumulate(thetas.begin(), thetas.end(), 0.0) / thetas.size();
  double theta_filtered =
      (thetas.size() > 1) ? (thetas[0] + thetas[1]) / 2.0 : thetas[0];
  double lane_l_mean =
      std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) / lane_ls.size();
  double lane_l_filtered =
      (lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) / 2.0 : lane_ls[0];
  double speed_mean =
      std::accumulate(speeds.begin(), speeds.end(), 0.0) / speeds.size();
  double speed_lateral = sin(theta_filtered) * speed_mean;
  double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0;
  double time_to_lb = (abs(speed_lateral) > 0.05)
                          ? dist_lbs[0] / speed_lateral
                          : 20 * dist_lbs[0] * speed_sign;
  double time_to_rb = (abs(speed_lateral) > 0.05)
                          ? -1 * dist_rbs[0] / speed_lateral
                          : -20 * dist_rbs[0] * speed_sign;
  double time_diff = timestamps.front() - timestamps.back();
  double dist_lb_rate = (timestamps.size() > 1)
                            ? (dist_lbs.front() - dist_lbs.back()) / time_diff
                            : 0.0;
  double dist_rb_rate = (timestamps.size() > 1)
                            ? (dist_rbs.front() - dist_rbs.back()) / time_diff
                            : 0.0;
  // setup obstacle feature values
  feature_values->push_back(theta_filtered);
  feature_values->push_back(theta_mean);
  feature_values->push_back(theta_filtered - theta_mean);
  feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1]
                                            : thetas[0]);
  feature_values->push_back(lane_l_filtered);
  feature_values->push_back(lane_l_mean);
  feature_values->push_back(lane_l_filtered - lane_l_mean);
  feature_values->push_back(speed_mean);
  feature_values->push_back(dist_lbs.front());
  feature_values->push_back(dist_lb_rate);
  feature_values->push_back(time_to_lb);
  feature_values->push_back(dist_rbs.front());
  feature_values->push_back(dist_rb_rate);
  feature_values->push_back(time_to_rb);
  // feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0
  //                                                                    : 0.0);
  // feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0
  //                                                                     : 0.0);
  // feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0
  //                                                                   : 0.0);
  // feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0
  //                                                                   : 0.0);
}

void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,
    LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {
  feature_values->clear();
  feature_values->reserve(LANE_FEATURE_SIZE);
  const Feature& feature = obstacle_ptr->latest_feature();
  if (!feature.IsInitialized()) {
    ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature.";
    return;
  } else if (!feature.has_position()) {
    ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
    return;
  }

  double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading()
                                            : feature.theta();
  for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {
    if (feature_values->size() >= LANE_FEATURE_SIZE) {
      break;
    }
    const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);
    for (int j = 0; j < lane_segment.lane_point_size(); ++j) {
      if (feature_values->size() >= LANE_FEATURE_SIZE) {
        break;
      }
      const LanePoint& lane_point = lane_segment.lane_point(j);
      if (!lane_point.has_position()) {
        AERROR << "Lane point has no position.";
        continue;
      }
      double diff_x = lane_point.position().x() - feature.position().x();
      double diff_y = lane_point.position().y() - feature.position().y();
      double angle = std::atan2(diff_x, diff_y);
      feature_values->push_back(std::sin(angle - heading));
      feature_values->push_back(lane_point.relative_l());
      feature_values->push_back(lane_point.heading());
      feature_values->push_back(lane_point.angle_diff());
    }
  }

  std::size_t size = feature_values->size();
  while (size >= 4 && size < LANE_FEATURE_SIZE) {
    double heading_diff = feature_values->operator[](size - 4);
    double lane_l_diff = feature_values->operator[](size - 3);
    double heading = feature_values->operator[](size - 2);
    double angle_diff = feature_values->operator[](size - 1);
    feature_values->push_back(heading_diff);
    feature_values->push_back(lane_l_diff);
    feature_values->push_back(heading);
    feature_values->push_back(angle_diff);
    size = feature_values->size();
  }
}

void MLPEvaluator::LoadModel(const std::string& model_file) {
  model_ptr_.reset(new FnnVehicleModel());
  CHECK(model_ptr_ != nullptr);
  std::fstream file_stream(model_file, std::ios::in | std::ios::binary);
  if (!file_stream.good()) {
    AERROR << "Unable to open the model file: " << model_file << ".";
    return;
  }
  if (!model_ptr_->ParseFromIstream(&file_stream)) {
    AERROR << "Unable to load the model file: " << model_file << ".";
    return;
  }
  ADEBUG << "Succeeded in loading the model file: " << model_file << ".";
}

double MLPEvaluator::ComputeProbability() {
  CHECK(model_ptr_.get() != nullptr);
  double probability = 0.0;

  if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) {
    AERROR << "Model feature size not consistent with model proto definition.";
    return probability;
  }
  std::vector<double> layer_input;
  layer_input.reserve(model_ptr_->dim_input());
  std::vector<double> layer_output;

  // normalization
  for (int i = 0; i < model_ptr_->dim_input(); ++i) {
    double mean = model_ptr_->samples_mean().columns(i);
    double std = model_ptr_->samples_std().columns(i);
    layer_input.push_back(
        apollo::prediction::util::Normalize(feature_values_[i], mean, std));
  }

  for (int i = 0; i < model_ptr_->num_layer(); ++i) {
    if (i > 0) {
      layer_input.clear();
      layer_output.swap(layer_output);
    }
    const Layer& layer = model_ptr_->layer(i);
    for (int col = 0; col < layer.layer_output_dim(); ++col) {
      double neuron_output = layer.layer_bias().columns(col);
      for (int row = 0; row < layer.layer_input_dim(); ++row) {
        double weight = layer.layer_input_weight().rows(row).columns(col);
        neuron_output += (layer_input[row] * weight);
      }
      if (layer.layer_activation_type() == "relu") {
        neuron_output = apollo::prediction::util::Relu(neuron_output);
      } else if (layer.layer_activation_type() == "sigmoid") {
        neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
      } else if (layer.layer_activation_type() == "tanh") {
        neuron_output = std::tanh(neuron_output);
      } else {
        LOG(ERROR) << "Undefined activation func: "
                   << layer.layer_activation_type()
                   << ", and default sigmoid will be used instead.";
        neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
      }
      layer_output.push_back(neuron_output);
    }
  }

  if (layer_output.size() != 1) {
    AERROR << "Model output layer has incorrect # outputs: "
           << layer_output.size();
  } else {
    probability = layer_output[0];
  }

  return probability;
}

}  // namespace prediction
}  // namespace apollo
<|endoftext|>


<commit_before>// @(#)root/graf:$Name:  $:$Id: TPaveStats.cxx,v 1.9 2002/03/16 08:52:43 brun Exp $
// Author: Rene Brun   15/03/99

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "Riostream.h"
#include "TPaveStats.h"
#include "TVirtualPad.h"
#include "TStyle.h"
#include "TFile.h"
#include "TClass.h"
#include "TLatex.h"

ClassImp(TPaveStats)

//______________________________________________________________________________
//  A PaveStats is a PaveText to draw histogram statistics
// The type of information printed in the histogram statistics box
//  can be selected via gStyle->SetOptStat(mode).
//  or by editing an existing TPaveStats object via TPaveStats::SetOptStat(mode).
//  The parameter mode can be = ourmen  (default = 001111)
//    n = 1;  name of histogram is printed
//    e = 1;  number of entries printed
//    m = 1;  mean value printed
//    r = 1;  rms printed
//    u = 1;  number of underflows printed
//    o = 1;  number of overflows printed
//  Example: gStyle->SetOptStat(11);
//           print only name of histogram and number of entries.
//
// The type of information about fit parameters printed in the histogram
// statistics box can be selected via the parameter mode.
//  The parameter mode can be = pcev  (default = 0111)
//    v = 1;  print name/values of parameters
//    e = 1;  print errors (if e=1, v must be 1)
//    c = 1;  print Chisquare/Number of degress of freedom
//    p = 1;  print Probability
//  Example: gStyle->SetOptFit(1011);
//        or this->SetOptFit(1011);
//           print fit probability, parameter names/values and errors.
//

//______________________________________________________________________________
TPaveStats::TPaveStats(): TPaveText()
{
   // TPaveStats default constructor
}

//______________________________________________________________________________
TPaveStats::TPaveStats(Double_t x1, Double_t y1,Double_t x2, Double_t  y2, Option_t *option)
           :TPaveText(x1,y1,x2,y2,option)
{
   // TPaveStats normal constructor

   fOptFit  = gStyle->GetOptFit();
   fOptStat = gStyle->GetOptStat();
   SetFitFormat(gStyle->GetFitFormat());
   SetStatFormat(gStyle->GetStatFormat());
}

//______________________________________________________________________________
TPaveStats::~TPaveStats()
{
   // TPaveStats default destructor
}

//______________________________________________________________________________
void TPaveStats::SaveStyle()
{
   //  Save This TPaveStats options in current style

   gStyle->SetOptFit(fOptFit);
   gStyle->SetOptStat(fOptStat);
   gStyle->SetFitFormat(fFitFormat.Data());
   gStyle->SetStatFormat(fStatFormat.Data());
}

//______________________________________________________________________________
void TPaveStats::SetFitFormat(const char *form)
{
   // Change (i.e. set) the format for printing fit parameters in statistics box

   fFitFormat = form;
}

//______________________________________________________________________________
void TPaveStats::SetStatFormat(const char *form)
{
   // Change (i.e. set) the format for printing statistics

   fStatFormat = form;
}

//______________________________________________________________________________
void TPaveStats::Paint(Option_t *option)
{
   TPave::ConvertNDCtoPad();
   TPave::PaintPave(fX1,fY1,fX2,fY2,GetBorderSize(),option);

   if (!fLines) return;
   Double_t dx = fX2 - fX1;
   Double_t textsize = GetTextSize();
   Int_t nlines = GetSize();
   if (nlines == 0) nlines = 5;

   // Evaluate text size as a function of the number of lines
   Double_t y1       = gPad->GetY1();
   Double_t y2       = gPad->GetY2();
   Float_t margin    = fMargin*(fX2-fX1);
   Double_t yspace   = (fY2 - fY1)/Double_t(nlines);
   Double_t textsave = textsize;
   TObject *line;
   TLatex *latex, *latex_tok;
   TIter next(fLines);
   Double_t longest = 0;
   Double_t w, wtok[2];
   char *st, *sl;
   if (textsize == 0)  {
      textsize = 0.85*yspace/(y2 - y1);
      wtok[0] = 0; wtok[1] = 0;
      while ((line = (TObject*) next())) {
	 if (line->IsA() == TLatex::Class()) {
            latex = (TLatex*)line;
            sl = new char[strlen(latex->GetTitle())+1];
            strcpy(sl, latex->GetTitle());
            if (strpbrk(sl, "=") !=0) {
               st = strtok(sl, "=");
               Int_t itok = 0;
               while ( st !=0 ) {
                  latex_tok = new TLatex(0.,0.,st);
                  latex_tok->SetTextSize(textsize);
                  w = latex_tok->GetXsize();
                  if (w > wtok[itok]) wtok[itok] = w;
                  st = strtok(0, "=");
                  ++itok;
                  delete latex_tok;
               }
            }
         }
      }
      longest = wtok[0]+wtok[1]+2.*margin;
      if (longest > 0.98*dx) textsize *= 0.98*dx/longest;
      SetTextSize(textsize);
   }
   Double_t ytext = fY2 + 0.5*yspace;
   Double_t xtext = 0;

   // Iterate over all lines
   // Copy pavetext attributes to line attributes if line attributes not set
   next.Reset();
   while ((line = (TObject*) next())) {
      if (line->IsA() == TLatex::Class()) {
         latex = (TLatex*)line;
         ytext -= yspace;
         Double_t xl    = latex->GetX();
         Double_t yl    = latex->GetY();
         Short_t talign = latex->GetTextAlign();
         Color_t tcolor = latex->GetTextColor();
         Style_t tfont  = latex->GetTextFont();
         Size_t  tsize  = latex->GetTextSize();
         if (tcolor == 0) latex->SetTextColor(GetTextColor());
         if (tfont  == 0) latex->SetTextFont(GetTextFont());
         if (tsize  == 0) latex->SetTextSize(GetTextSize());

         sl = new char[strlen(latex->GetTitle())+1];
         strcpy(sl, latex->GetTitle());
	 // Draw all the histogram except the 2D under/overflow
         if (strpbrk(sl, "=") !=0) {
           st = strtok(sl, "=");
           Int_t halign = 12;
           while ( st !=0 ) {
              latex->SetTextAlign(halign);
              if (halign == 12) xtext = fX1 + margin;
              if (halign == 32) {
                 xtext = fX2 - margin;
		 // Clean trailing blanks in case of right alignment.
                 char *stc;
		 stc=st+strlen(st)-1;
		 while (*stc == ' ') {
                    *stc = '\0';
                    --stc;
                 }
              }
              latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                            latex->GetTextSize(),
                                            st);
              st = strtok(0, "=");
              halign = 32;
           }
	 // Draw the 2D under/overflow
         } else if (strpbrk(sl, "|") !=0) {
           Double_t Yline1 = ytext+yspace/2.;
           Double_t Yline2 = ytext-yspace/2.;
           Double_t Xline1 = (fX2-fX1)/3+fX1;
           Double_t Xline2 = 2*(fX2-fX1)/3+fX1;
           gPad->PaintLine(fX1,Yline1,fX2,Yline1);
           gPad->PaintLine(Xline1,Yline1,Xline1,Yline2);
           gPad->PaintLine(Xline2,Yline1,Xline2,Yline2);
           st = strtok(sl, "|");
	   Int_t Index = 0;
           while ( st !=0 ) {
              latex->SetTextAlign(22);
	      if (Index == 0) xtext = 0.5*(fX1+Xline1);
	      if (Index == 1) xtext = 0.5*(fX1+fX2);
	      if (Index == 2) xtext = 0.5*(Xline2+fX2);
              latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                            latex->GetTextSize(),
                                            st);
              Index++;
              st = strtok(0, "|");
           }
	 // Draw the histogram identifier
         } else {
           latex->SetTextAlign(22);
           xtext = 0.5*(fX1+fX2);
           latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                         latex->GetTextSize(),
                                         sl);
           gPad->PaintLine(fX1,fY2-yspace,fX2,fY2-yspace);
         }
         delete [] sl;

         latex->SetTextAlign(talign);
         latex->SetTextColor(tcolor);
         latex->SetTextFont(tfont);
         latex->SetTextSize(tsize);
         latex->SetX(xl);  //paintlatex modifies fX and fY
         latex->SetY(yl);
      }
   }
   SetTextSize(textsave);
}

//______________________________________________________________________________
void TPaveStats::Streamer(TBuffer &R__b)
{
   // Stream an object of class TPaveStats.

   if (R__b.IsReading()) {
      UInt_t R__s, R__c;
      Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
      if (R__v > 2) {
         TPaveStats::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);
         return;
      }
      //====process old versions before automatic schema evolution
      TPaveText::Streamer(R__b);
      R__b >> fOptFit;
      R__b >> fOptStat;
      TFile *file = (TFile*)R__b.GetParent();
      if (R__v > 1 || (file && file->GetVersion() == 22304)) {
         fFitFormat.Streamer(R__b);
         fStatFormat.Streamer(R__b);
      } else {
         SetFitFormat();
         SetStatFormat();
      }
      R__b.CheckByteCount(R__s, R__c, TPaveStats::IsA());
      //====end of old versions

   } else {
      TPaveStats::Class()->WriteBuffer(R__b,this);
   }
}
<commit_msg>Improvements by Olivier in TPaveStats::Paint. The size of the histogram name is optimized to always fit in the box.<commit_after>// @(#)root/graf:$Name:  $:$Id: TPaveStats.cxx,v 1.10 2002/03/16 18:41:41 rdm Exp $
// Author: Rene Brun   15/03/99

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "Riostream.h"
#include "TPaveStats.h"
#include "TVirtualPad.h"
#include "TStyle.h"
#include "TFile.h"
#include "TClass.h"
#include "TLatex.h"

ClassImp(TPaveStats)

//______________________________________________________________________________
//  A PaveStats is a PaveText to draw histogram statistics
// The type of information printed in the histogram statistics box
//  can be selected via gStyle->SetOptStat(mode).
//  or by editing an existing TPaveStats object via TPaveStats::SetOptStat(mode).
//  The parameter mode can be = ourmen  (default = 001111)
//    n = 1;  name of histogram is printed
//    e = 1;  number of entries printed
//    m = 1;  mean value printed
//    r = 1;  rms printed
//    u = 1;  number of underflows printed
//    o = 1;  number of overflows printed
//  Example: gStyle->SetOptStat(11);
//           print only name of histogram and number of entries.
//
// The type of information about fit parameters printed in the histogram
// statistics box can be selected via the parameter mode.
//  The parameter mode can be = pcev  (default = 0111)
//    v = 1;  print name/values of parameters
//    e = 1;  print errors (if e=1, v must be 1)
//    c = 1;  print Chisquare/Number of degress of freedom
//    p = 1;  print Probability
//  Example: gStyle->SetOptFit(1011);
//        or this->SetOptFit(1011);
//           print fit probability, parameter names/values and errors.
//

//______________________________________________________________________________
TPaveStats::TPaveStats(): TPaveText()
{
   // TPaveStats default constructor
}

//______________________________________________________________________________
TPaveStats::TPaveStats(Double_t x1, Double_t y1,Double_t x2, Double_t  y2, Option_t *option)
           :TPaveText(x1,y1,x2,y2,option)
{
   // TPaveStats normal constructor

   fOptFit  = gStyle->GetOptFit();
   fOptStat = gStyle->GetOptStat();
   SetFitFormat(gStyle->GetFitFormat());
   SetStatFormat(gStyle->GetStatFormat());
}

//______________________________________________________________________________
TPaveStats::~TPaveStats()
{
   // TPaveStats default destructor
}

//______________________________________________________________________________
void TPaveStats::SaveStyle()
{
   //  Save This TPaveStats options in current style

   gStyle->SetOptFit(fOptFit);
   gStyle->SetOptStat(fOptStat);
   gStyle->SetFitFormat(fFitFormat.Data());
   gStyle->SetStatFormat(fStatFormat.Data());
}

//______________________________________________________________________________
void TPaveStats::SetFitFormat(const char *form)
{
   // Change (i.e. set) the format for printing fit parameters in statistics box

   fFitFormat = form;
}

//______________________________________________________________________________
void TPaveStats::SetStatFormat(const char *form)
{
   // Change (i.e. set) the format for printing statistics

   fStatFormat = form;
}

//______________________________________________________________________________
void TPaveStats::Paint(Option_t *option)
{
   TPave::ConvertNDCtoPad();
   TPave::PaintPave(fX1,fY1,fX2,fY2,GetBorderSize(),option);

   if (!fLines) return;
   Double_t dx = fX2 - fX1;
   Double_t titlesize=0;
   Double_t textsize = GetTextSize();
   Int_t nlines = GetSize();
   if (nlines == 0) nlines = 5;

   // Evaluate text size as a function of the number of lines
   Double_t y1       = gPad->GetY1();
   Double_t y2       = gPad->GetY2();
   Float_t margin    = fMargin*(fX2-fX1);
   Double_t yspace   = (fY2 - fY1)/Double_t(nlines);
   Double_t textsave = textsize;
   TObject *line;
   TLatex *latex, *latex_tok;
   TIter next(fLines);
   Double_t longest = 0, titlelength = 0;
   Double_t w, wtok[2];
   char *st, *sl;
   if (textsize == 0)  {
      textsize = 0.85*yspace/(y2 - y1);
      titlesize = textsize;
      wtok[0] = 0; wtok[1] = 0;
      while ((line = (TObject*) next())) {
	 if (line->IsA() == TLatex::Class()) {
            latex = (TLatex*)line;
            sl = new char[strlen(latex->GetTitle())+1];
            strcpy(sl, latex->GetTitle());
            if (strpbrk(sl, "=") !=0) {
               st = strtok(sl, "=");
               Int_t itok = 0;
               while ( st !=0 ) {
                  latex_tok = new TLatex(0.,0.,st);
                  latex_tok->SetTextSize(textsize);
                  w = latex_tok->GetXsize();
                  if (w > wtok[itok]) wtok[itok] = w;
                  st = strtok(0, "=");
                  ++itok;
                  delete latex_tok;
               }
            } else if (strpbrk(sl, "|") !=0) {
            } else {
               latex->SetTextSize(titlesize);
               titlelength = latex->GetXsize()+2.*margin;
               if (titlelength > 0.98*dx) titlesize *= 0.98*dx/titlelength;
            }
         }
      }
      longest = wtok[0]+wtok[1]+2.*margin;
      if (longest > 0.98*dx) textsize *= 0.98*dx/longest;
      SetTextSize(textsize);
   }
   Double_t ytext = fY2 + 0.5*yspace;
   Double_t xtext = 0;

   // Iterate over all lines
   // Copy pavetext attributes to line attributes if line attributes not set
   next.Reset();
   while ((line = (TObject*) next())) {
      if (line->IsA() == TLatex::Class()) {
         latex = (TLatex*)line;
         ytext -= yspace;
         Double_t xl    = latex->GetX();
         Double_t yl    = latex->GetY();
         Short_t talign = latex->GetTextAlign();
         Color_t tcolor = latex->GetTextColor();
         Style_t tfont  = latex->GetTextFont();
         Size_t  tsize  = latex->GetTextSize();
         if (tcolor == 0) latex->SetTextColor(GetTextColor());
         if (tfont  == 0) latex->SetTextFont(GetTextFont());
         if (tsize  == 0) latex->SetTextSize(GetTextSize());

         sl = new char[strlen(latex->GetTitle())+1];
         strcpy(sl, latex->GetTitle());
         // Draw all the histogram stats except the 2D under/overflow
         if (strpbrk(sl, "=") !=0) {
           st = strtok(sl, "=");
           Int_t halign = 12;
           while ( st !=0 ) {
              latex->SetTextAlign(halign);
              if (halign == 12) xtext = fX1 + margin;
              if (halign == 32) {
                 xtext = fX2 - margin;
		 // Clean trailing blanks in case of right alignment.
                 char *stc;
		 stc=st+strlen(st)-1;
		 while (*stc == ' ') {
                    *stc = '\0';
                    --stc;
                 }
              }
              latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                            latex->GetTextSize(),
                                            st);
              st = strtok(0, "=");
              halign = 32;
           }
	 // Draw the 2D under/overflow
         } else if (strpbrk(sl, "|") !=0) {
           Double_t Yline1 = ytext+yspace/2.;
           Double_t Yline2 = ytext-yspace/2.;
           Double_t Xline1 = (fX2-fX1)/3+fX1;
           Double_t Xline2 = 2*(fX2-fX1)/3+fX1;
           gPad->PaintLine(fX1,Yline1,fX2,Yline1);
           gPad->PaintLine(Xline1,Yline1,Xline1,Yline2);
           gPad->PaintLine(Xline2,Yline1,Xline2,Yline2);
           st = strtok(sl, "|");
	   Int_t Index = 0;
           while ( st !=0 ) {
              latex->SetTextAlign(22);
	      if (Index == 0) xtext = 0.5*(fX1+Xline1);
	      if (Index == 1) xtext = 0.5*(fX1+fX2);
	      if (Index == 2) xtext = 0.5*(Xline2+fX2);
              latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                            latex->GetTextSize(),
                                            st);
              Index++;
              st = strtok(0, "|");
           }
	 // Draw the histogram identifier
         } else {
           latex->SetTextAlign(22);
           xtext = 0.5*(fX1+fX2);
           latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                         titlesize,
                                         sl);
           gPad->PaintLine(fX1,fY2-yspace,fX2,fY2-yspace);
         }
         delete [] sl;

         latex->SetTextAlign(talign);
         latex->SetTextColor(tcolor);
         latex->SetTextFont(tfont);
         latex->SetTextSize(tsize);
         latex->SetX(xl);  //paintlatex modifies fX and fY
         latex->SetY(yl);
      }
   }
   SetTextSize(textsave);
}

//______________________________________________________________________________
void TPaveStats::Streamer(TBuffer &R__b)
{
   // Stream an object of class TPaveStats.

   if (R__b.IsReading()) {
      UInt_t R__s, R__c;
      Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
      if (R__v > 2) {
         TPaveStats::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);
         return;
      }
      //====process old versions before automatic schema evolution
      TPaveText::Streamer(R__b);
      R__b >> fOptFit;
      R__b >> fOptStat;
      TFile *file = (TFile*)R__b.GetParent();
      if (R__v > 1 || (file && file->GetVersion() == 22304)) {
         fFitFormat.Streamer(R__b);
         fStatFormat.Streamer(R__b);
      } else {
         SetFitFormat();
         SetStatFormat();
      }
      R__b.CheckByteCount(R__s, R__c, TPaveStats::IsA());
      //====end of old versions

   } else {
      TPaveStats::Class()->WriteBuffer(R__b,this);
   }
}
<|endoftext|>


<commit_before>// @(#)root/graf:$Name:  $:$Id: TPaveStats.cxx,v 1.8 2002/03/13 17:00:33 rdm Exp $
// Author: Rene Brun   15/03/99

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "Riostream.h"
#include "TPaveStats.h"
#include "TVirtualPad.h"
#include "TStyle.h"
#include "TFile.h"
#include "TClass.h"
#include "TLatex.h"

ClassImp(TPaveStats)

//______________________________________________________________________________
//  A PaveStats is a PaveText to draw histogram statistics
// The type of information printed in the histogram statistics box
//  can be selected via gStyle->SetOptStat(mode).
//  or by editing an existing TPaveStats object via TPaveStats::SetOptStat(mode).
//  The parameter mode can be = ourmen  (default = 001111)
//    n = 1;  name of histogram is printed
//    e = 1;  number of entries printed
//    m = 1;  mean value printed
//    r = 1;  rms printed
//    u = 1;  number of underflows printed
//    o = 1;  number of overflows printed
//  Example: gStyle->SetOptStat(11);
//           print only name of histogram and number of entries.
//
// The type of information about fit parameters printed in the histogram
// statistics box can be selected via the parameter mode.
//  The parameter mode can be = pcev  (default = 0111)
//    v = 1;  print name/values of parameters
//    e = 1;  print errors (if e=1, v must be 1)
//    c = 1;  print Chisquare/Number of degress of freedom
//    p = 1;  print Probability
//  Example: gStyle->SetOptFit(1011);
//        or this->SetOptFit(1011);
//           print fit probability, parameter names/values and errors.
//

//______________________________________________________________________________
TPaveStats::TPaveStats(): TPaveText()
{
   // TPaveStats default constructor
}

//______________________________________________________________________________
TPaveStats::TPaveStats(Double_t x1, Double_t y1,Double_t x2, Double_t  y2, Option_t *option)
           :TPaveText(x1,y1,x2,y2,option)
{
   // TPaveStats normal constructor

   fOptFit  = gStyle->GetOptFit();
   fOptStat = gStyle->GetOptStat();
   SetFitFormat(gStyle->GetFitFormat());
   SetStatFormat(gStyle->GetStatFormat());
}

//______________________________________________________________________________
TPaveStats::~TPaveStats()
{
   // TPaveStats default destructor
}

//______________________________________________________________________________
void TPaveStats::SaveStyle()
{
   //  Save This TPaveStats options in current style

   gStyle->SetOptFit(fOptFit);
   gStyle->SetOptStat(fOptStat);
   gStyle->SetFitFormat(fFitFormat.Data());
   gStyle->SetStatFormat(fStatFormat.Data());
}

//______________________________________________________________________________
void TPaveStats::SetFitFormat(const char *form)
{
   // Change (i.e. set) the format for printing fit parameters in statistics box

   fFitFormat = form;
}

//______________________________________________________________________________
void TPaveStats::SetStatFormat(const char *form)
{
   // Change (i.e. set) the format for printing statistics

   fStatFormat = form;
}

//______________________________________________________________________________
void TPaveStats::Paint(Option_t *option)
{
   TPave::ConvertNDCtoPad();
   TPave::PaintPave(fX1,fY1,fX2,fY2,GetBorderSize(),option);

   if (!fLines) return;
   Double_t dx = fX2 - fX1;
   Double_t dy = fY2 - fY1;
   Double_t textsize = GetTextSize();
   Int_t nlines = GetSize();
   if (nlines == 0) nlines = 5;

   // Evaluate text size as a function of the number of lines
   Double_t y1       = gPad->GetY1();
   Double_t y2       = gPad->GetY2();
   Float_t margin    = fMargin*(fX2-fX1);
   Double_t yspace   = (fY2 - fY1)/Double_t(nlines);
   Double_t textsave = textsize;
   TObject *line;
   TLatex *latex, *latex_tok;
   TIter next(fLines);
   Double_t longest = 0;
   Double_t w, wtok[2];
   char *st, *sl;
   if (textsize == 0)  {
      textsize = 0.85*yspace/(y2 - y1);
      wtok[0] = 0; wtok[1] = 0;
      while ((line = (TObject*) next())) {
	 if (line->IsA() == TLatex::Class()) {
            latex = (TLatex*)line;
            sl = new char[strlen(latex->GetTitle())+1];
            strcpy(sl, latex->GetTitle());
            if (strpbrk(sl, "=") !=0) {
               st = strtok(sl, "=");
               Int_t itok = 0;
               while ( st !=0 ) {
                  latex_tok = new TLatex(0.,0.,st);
                  latex_tok->SetTextSize(textsize);
                  w = latex_tok->GetXsize();
                  if (w > wtok[itok]) wtok[itok] = w;
                  st = strtok(0, "=");
                  ++itok;
                  delete latex_tok;
               }
            }
         }
      }
      longest = wtok[0]+wtok[1]+2.*margin;
      if (longest > 0.98*dx) textsize *= 0.98*dx/longest;
      SetTextSize(textsize);
   }
   Double_t ytext = fY2 + 0.5*yspace;
   Double_t xtext = 0;

   // Iterate over all lines
   // Copy pavetext attributes to line attributes if line attributes not set
   next.Reset();
   while ((line = (TObject*) next())) {
      if (line->IsA() == TLatex::Class()) {
         latex = (TLatex*)line;
         ytext -= yspace;
         Double_t xl    = latex->GetX();
         Double_t yl    = latex->GetY();
         Short_t talign = latex->GetTextAlign();
         Color_t tcolor = latex->GetTextColor();
         Style_t tfont  = latex->GetTextFont();
         Size_t  tsize  = latex->GetTextSize();
         if (tcolor == 0) latex->SetTextColor(GetTextColor());
         if (tfont  == 0) latex->SetTextFont(GetTextFont());
         if (tsize  == 0) latex->SetTextSize(GetTextSize());

         sl = new char[strlen(latex->GetTitle())+1];
         strcpy(sl, latex->GetTitle());
	 // Draw all the histogram except the 2D under/overflow
         if (strpbrk(sl, "=") !=0) {
           st = strtok(sl, "=");
           Int_t halign = 12;
           while ( st !=0 ) {
              latex->SetTextAlign(halign);
              if (halign == 12) xtext = fX1 + margin;
              if (halign == 32) {
                 xtext = fX2 - margin;
		 // Clean trailing blanks in case of right alignment.
                 char *stc;
		 stc=st+strlen(st)-1;
		 while (*stc == ' ') {
                    *stc = '\0';
                    --stc;
                 }
              }
              latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                            latex->GetTextSize(),
                                            st);
              st = strtok(0, "=");
              halign = 32;
           }
	 // Draw the 2D under/overflow
         } else if (strpbrk(sl, "|") !=0) {
           Double_t Yline1 = ytext+yspace/2.;
           Double_t Yline2 = ytext-yspace/2.;
           Double_t Xline1 = (fX2-fX1)/3+fX1;
           Double_t Xline2 = 2*(fX2-fX1)/3+fX1;
           gPad->PaintLine(fX1,Yline1,fX2,Yline1);
           gPad->PaintLine(Xline1,Yline1,Xline1,Yline2);
           gPad->PaintLine(Xline2,Yline1,Xline2,Yline2);
           st = strtok(sl, "|");
	   Int_t Index = 0;
           while ( st !=0 ) {
              latex->SetTextAlign(22);
	      if (Index == 0) xtext = 0.5*(fX1+Xline1);
	      if (Index == 1) xtext = 0.5*(fX1+fX2);
	      if (Index == 2) xtext = 0.5*(Xline2+fX2);
              latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                            latex->GetTextSize(),
                                            st);
              Index++;
              st = strtok(0, "|");
           }
	 // Draw the histogram identifier
         } else {
           latex->SetTextAlign(22);
           xtext = 0.5*(fX1+fX2);
           latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                         latex->GetTextSize(),
                                         sl);
           gPad->PaintLine(fX1,fY2-yspace,fX2,fY2-yspace);
         }
         delete [] sl;

         latex->SetTextAlign(talign);
         latex->SetTextColor(tcolor);
         latex->SetTextFont(tfont);
         latex->SetTextSize(tsize);
         latex->SetX(xl);  //paintlatex modifies fX and fY
         latex->SetY(yl);
      }
   }
   SetTextSize(textsave);
}

//______________________________________________________________________________
void TPaveStats::Streamer(TBuffer &R__b)
{
   // Stream an object of class TPaveStats.

   if (R__b.IsReading()) {
      UInt_t R__s, R__c;
      Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
      if (R__v > 2) {
         TPaveStats::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);
         return;
      }
      //====process old versions before automatic schema evolution
      TPaveText::Streamer(R__b);
      R__b >> fOptFit;
      R__b >> fOptStat;
      TFile *file = (TFile*)R__b.GetParent();
      if (R__v > 1 || (file && file->GetVersion() == 22304)) {
         fFitFormat.Streamer(R__b);
         fStatFormat.Streamer(R__b);
      } else {
         SetFitFormat();
         SetStatFormat();
      }
      R__b.CheckByteCount(R__s, R__c, TPaveStats::IsA());
      //====end of old versions

   } else {
      TPaveStats::Class()->WriteBuffer(R__b,this);
   }
}
<commit_msg>remove unused dy.<commit_after>// @(#)root/graf:$Name:  $:$Id: TPaveStats.cxx,v 1.9 2002/03/16 08:52:43 brun Exp $
// Author: Rene Brun   15/03/99

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "Riostream.h"
#include "TPaveStats.h"
#include "TVirtualPad.h"
#include "TStyle.h"
#include "TFile.h"
#include "TClass.h"
#include "TLatex.h"

ClassImp(TPaveStats)

//______________________________________________________________________________
//  A PaveStats is a PaveText to draw histogram statistics
// The type of information printed in the histogram statistics box
//  can be selected via gStyle->SetOptStat(mode).
//  or by editing an existing TPaveStats object via TPaveStats::SetOptStat(mode).
//  The parameter mode can be = ourmen  (default = 001111)
//    n = 1;  name of histogram is printed
//    e = 1;  number of entries printed
//    m = 1;  mean value printed
//    r = 1;  rms printed
//    u = 1;  number of underflows printed
//    o = 1;  number of overflows printed
//  Example: gStyle->SetOptStat(11);
//           print only name of histogram and number of entries.
//
// The type of information about fit parameters printed in the histogram
// statistics box can be selected via the parameter mode.
//  The parameter mode can be = pcev  (default = 0111)
//    v = 1;  print name/values of parameters
//    e = 1;  print errors (if e=1, v must be 1)
//    c = 1;  print Chisquare/Number of degress of freedom
//    p = 1;  print Probability
//  Example: gStyle->SetOptFit(1011);
//        or this->SetOptFit(1011);
//           print fit probability, parameter names/values and errors.
//

//______________________________________________________________________________
TPaveStats::TPaveStats(): TPaveText()
{
   // TPaveStats default constructor
}

//______________________________________________________________________________
TPaveStats::TPaveStats(Double_t x1, Double_t y1,Double_t x2, Double_t  y2, Option_t *option)
           :TPaveText(x1,y1,x2,y2,option)
{
   // TPaveStats normal constructor

   fOptFit  = gStyle->GetOptFit();
   fOptStat = gStyle->GetOptStat();
   SetFitFormat(gStyle->GetFitFormat());
   SetStatFormat(gStyle->GetStatFormat());
}

//______________________________________________________________________________
TPaveStats::~TPaveStats()
{
   // TPaveStats default destructor
}

//______________________________________________________________________________
void TPaveStats::SaveStyle()
{
   //  Save This TPaveStats options in current style

   gStyle->SetOptFit(fOptFit);
   gStyle->SetOptStat(fOptStat);
   gStyle->SetFitFormat(fFitFormat.Data());
   gStyle->SetStatFormat(fStatFormat.Data());
}

//______________________________________________________________________________
void TPaveStats::SetFitFormat(const char *form)
{
   // Change (i.e. set) the format for printing fit parameters in statistics box

   fFitFormat = form;
}

//______________________________________________________________________________
void TPaveStats::SetStatFormat(const char *form)
{
   // Change (i.e. set) the format for printing statistics

   fStatFormat = form;
}

//______________________________________________________________________________
void TPaveStats::Paint(Option_t *option)
{
   TPave::ConvertNDCtoPad();
   TPave::PaintPave(fX1,fY1,fX2,fY2,GetBorderSize(),option);

   if (!fLines) return;
   Double_t dx = fX2 - fX1;
   Double_t textsize = GetTextSize();
   Int_t nlines = GetSize();
   if (nlines == 0) nlines = 5;

   // Evaluate text size as a function of the number of lines
   Double_t y1       = gPad->GetY1();
   Double_t y2       = gPad->GetY2();
   Float_t margin    = fMargin*(fX2-fX1);
   Double_t yspace   = (fY2 - fY1)/Double_t(nlines);
   Double_t textsave = textsize;
   TObject *line;
   TLatex *latex, *latex_tok;
   TIter next(fLines);
   Double_t longest = 0;
   Double_t w, wtok[2];
   char *st, *sl;
   if (textsize == 0)  {
      textsize = 0.85*yspace/(y2 - y1);
      wtok[0] = 0; wtok[1] = 0;
      while ((line = (TObject*) next())) {
	 if (line->IsA() == TLatex::Class()) {
            latex = (TLatex*)line;
            sl = new char[strlen(latex->GetTitle())+1];
            strcpy(sl, latex->GetTitle());
            if (strpbrk(sl, "=") !=0) {
               st = strtok(sl, "=");
               Int_t itok = 0;
               while ( st !=0 ) {
                  latex_tok = new TLatex(0.,0.,st);
                  latex_tok->SetTextSize(textsize);
                  w = latex_tok->GetXsize();
                  if (w > wtok[itok]) wtok[itok] = w;
                  st = strtok(0, "=");
                  ++itok;
                  delete latex_tok;
               }
            }
         }
      }
      longest = wtok[0]+wtok[1]+2.*margin;
      if (longest > 0.98*dx) textsize *= 0.98*dx/longest;
      SetTextSize(textsize);
   }
   Double_t ytext = fY2 + 0.5*yspace;
   Double_t xtext = 0;

   // Iterate over all lines
   // Copy pavetext attributes to line attributes if line attributes not set
   next.Reset();
   while ((line = (TObject*) next())) {
      if (line->IsA() == TLatex::Class()) {
         latex = (TLatex*)line;
         ytext -= yspace;
         Double_t xl    = latex->GetX();
         Double_t yl    = latex->GetY();
         Short_t talign = latex->GetTextAlign();
         Color_t tcolor = latex->GetTextColor();
         Style_t tfont  = latex->GetTextFont();
         Size_t  tsize  = latex->GetTextSize();
         if (tcolor == 0) latex->SetTextColor(GetTextColor());
         if (tfont  == 0) latex->SetTextFont(GetTextFont());
         if (tsize  == 0) latex->SetTextSize(GetTextSize());

         sl = new char[strlen(latex->GetTitle())+1];
         strcpy(sl, latex->GetTitle());
	 // Draw all the histogram except the 2D under/overflow
         if (strpbrk(sl, "=") !=0) {
           st = strtok(sl, "=");
           Int_t halign = 12;
           while ( st !=0 ) {
              latex->SetTextAlign(halign);
              if (halign == 12) xtext = fX1 + margin;
              if (halign == 32) {
                 xtext = fX2 - margin;
		 // Clean trailing blanks in case of right alignment.
                 char *stc;
		 stc=st+strlen(st)-1;
		 while (*stc == ' ') {
                    *stc = '\0';
                    --stc;
                 }
              }
              latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                            latex->GetTextSize(),
                                            st);
              st = strtok(0, "=");
              halign = 32;
           }
	 // Draw the 2D under/overflow
         } else if (strpbrk(sl, "|") !=0) {
           Double_t Yline1 = ytext+yspace/2.;
           Double_t Yline2 = ytext-yspace/2.;
           Double_t Xline1 = (fX2-fX1)/3+fX1;
           Double_t Xline2 = 2*(fX2-fX1)/3+fX1;
           gPad->PaintLine(fX1,Yline1,fX2,Yline1);
           gPad->PaintLine(Xline1,Yline1,Xline1,Yline2);
           gPad->PaintLine(Xline2,Yline1,Xline2,Yline2);
           st = strtok(sl, "|");
	   Int_t Index = 0;
           while ( st !=0 ) {
              latex->SetTextAlign(22);
	      if (Index == 0) xtext = 0.5*(fX1+Xline1);
	      if (Index == 1) xtext = 0.5*(fX1+fX2);
	      if (Index == 2) xtext = 0.5*(Xline2+fX2);
              latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                            latex->GetTextSize(),
                                            st);
              Index++;
              st = strtok(0, "|");
           }
	 // Draw the histogram identifier
         } else {
           latex->SetTextAlign(22);
           xtext = 0.5*(fX1+fX2);
           latex->PaintLatex(xtext,ytext,latex->GetTextAngle(),
                                         latex->GetTextSize(),
                                         sl);
           gPad->PaintLine(fX1,fY2-yspace,fX2,fY2-yspace);
         }
         delete [] sl;

         latex->SetTextAlign(talign);
         latex->SetTextColor(tcolor);
         latex->SetTextFont(tfont);
         latex->SetTextSize(tsize);
         latex->SetX(xl);  //paintlatex modifies fX and fY
         latex->SetY(yl);
      }
   }
   SetTextSize(textsave);
}

//______________________________________________________________________________
void TPaveStats::Streamer(TBuffer &R__b)
{
   // Stream an object of class TPaveStats.

   if (R__b.IsReading()) {
      UInt_t R__s, R__c;
      Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
      if (R__v > 2) {
         TPaveStats::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);
         return;
      }
      //====process old versions before automatic schema evolution
      TPaveText::Streamer(R__b);
      R__b >> fOptFit;
      R__b >> fOptStat;
      TFile *file = (TFile*)R__b.GetParent();
      if (R__v > 1 || (file && file->GetVersion() == 22304)) {
         fFitFormat.Streamer(R__b);
         fStatFormat.Streamer(R__b);
      } else {
         SetFitFormat();
         SetStatFormat();
      }
      R__b.CheckByteCount(R__s, R__c, TPaveStats::IsA());
      //====end of old versions

   } else {
      TPaveStats::Class()->WriteBuffer(R__b,this);
   }
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "IECorePython/Wrapper.h"
#include "IECorePython/RefCountedBinding.h"
#include "IECorePython/ScopedGILLock.h"

#include "IECore/LevenbergMarquardt.h"
#include "IECorePython/LevenbergMarquardtBinding.h"

using namespace boost::python;
using namespace IECore;

namespace IECorePython
{

template<typename T>
class LevenbergMarquardtErrorFn : public RefCounted
{
	public :

		IE_CORE_DECLAREMEMBERPTR( LevenbergMarquardtErrorFn<T> );

		LevenbergMarquardtErrorFn()
		{
		}

		virtual ~LevenbergMarquardtErrorFn()
		{
		}

		void operator()(
		        typename TypedData< std::vector<T> >::Ptr parameters,
		        typename TypedData< std::vector<T> >::Ptr errors
		)
		{
			computeErrors( parameters, errors );
			assert( errors->readable().size() == numErrors() );
		}

		virtual unsigned numErrors() = 0;

		virtual void computeErrors(
		        typename TypedData< std::vector<T> >::Ptr parameters,
		        typename TypedData< std::vector<T> >::Ptr errors
		) = 0;

};

template<typename T>
class LevenbergMarquardtErrorFnWrapper : public LevenbergMarquardtErrorFn<T>, public Wrapper< LevenbergMarquardtErrorFn<T> >
{
	public:

		IE_CORE_DECLAREMEMBERPTR( LevenbergMarquardtErrorFnWrapper<T> );

		LevenbergMarquardtErrorFnWrapper(PyObject *self ) :  LevenbergMarquardtErrorFn<T>(), Wrapper< LevenbergMarquardtErrorFn<T> >( self, this )
		{
		}

		virtual ~LevenbergMarquardtErrorFnWrapper()
		{
		}

		virtual unsigned numErrors()
		{
			ScopedGILLock gilLock;
			override o = this->get_override( "numErrors" );
			if( o )
			{
				try
				{
            		return o();
				}
				catch ( error_already_set )
				{
					PyErr_Print();
					return 0;
				}
			}
			else
			{
        		throw Exception( "LevenbergMarquardt: Error function does not define 'numErrors' instance method" );
			}
		}

		virtual void computeErrors(
		        typename TypedData< std::vector<T> >::Ptr parameters,
		        typename TypedData< std::vector<T> >::Ptr errors
		)
		{
			ScopedGILLock gilLock;
			override o = this->get_override( "computeErrors" );
			if( o )
			{
				try
				{
    				o( parameters, errors );
				}
				catch ( error_already_set )
				{
					PyErr_Print();
					return;
				}
			}
			else
			{
				throw Exception( "LevenbergMarquardt: Error function does not define 'computeErrors' instance method" );
			}
		}
};

template< typename T>
class LevenbergMarquardtWrapper : public LevenbergMarquardt< T, LevenbergMarquardtErrorFnWrapper<T> >
{
	public:

		tuple getParameters()
		{
			T ftol, xtol, gtol, epsilon, stepBound;
			LevenbergMarquardt< T, LevenbergMarquardtErrorFnWrapper<T> >::getParameters( ftol, xtol, gtol, epsilon, stepBound );
			return make_tuple(ftol, xtol, gtol, epsilon, stepBound);
		}
};

template<typename T>
void bindLevenbergMarquardt( const char *name )
{
	object lm = class_< LevenbergMarquardtWrapper<T>, boost::noncopyable >( name, no_init )
		.def( init<>() )
		.def( "setParameters", &LevenbergMarquardtWrapper<T>::setParameters )
		.def( "getParameters", &LevenbergMarquardtWrapper<T>::getParameters )
		.def( "solve", &LevenbergMarquardtWrapper<T>::solve )
		.def( "setMaxCalls", &LevenbergMarquardtWrapper<T>::setMaxCalls )
		.def( "getMaxCalls", &LevenbergMarquardtWrapper<T>::getMaxCalls )
	;

	{
		scope lmS( lm );

		enum_< typename LevenbergMarquardtWrapper<T>::Status >( "Status" )
			.value( "Success", LevenbergMarquardtWrapper<T>::Success )
		;

		RefCountedClass<LevenbergMarquardtErrorFn<T>, RefCounted, LevenbergMarquardtErrorFnWrapper<T> >( "ErrorFn" )
			.def( init<>() )
			.def( "numErrors", pure_virtual( &LevenbergMarquardtErrorFnWrapper<T>::numErrors ) )
			.def( "computeErrors", pure_virtual( &LevenbergMarquardtErrorFnWrapper<T>::computeErrors ) )
		;
	}
}

void bindLevenbergMarquardt()
{
	bindLevenbergMarquardt< float >( "LevenbergMarquardtf" );
	bindLevenbergMarquardt< double >( "LevenbergMarquardtd" );
}

} // namespace IECorePython
<commit_msg>LevenbergMarquardt Binding : Use RefCountedWrapper<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/python.hpp"

#include "IECorePython/RefCountedBinding.h"
#include "IECorePython/ScopedGILLock.h"

#include "IECore/LevenbergMarquardt.h"
#include "IECorePython/LevenbergMarquardtBinding.h"

using namespace boost::python;
using namespace IECore;

namespace IECorePython
{

template<typename T>
class LevenbergMarquardtErrorFn : public RefCounted
{
	public :

		IE_CORE_DECLAREMEMBERPTR( LevenbergMarquardtErrorFn<T> );

		LevenbergMarquardtErrorFn()
		{
		}

		virtual ~LevenbergMarquardtErrorFn()
		{
		}

		void operator()(
		        typename TypedData< std::vector<T> >::Ptr parameters,
		        typename TypedData< std::vector<T> >::Ptr errors
		)
		{
			computeErrors( parameters, errors );
			assert( errors->readable().size() == numErrors() );
		}

		virtual unsigned numErrors() = 0;

		virtual void computeErrors(
		        typename TypedData< std::vector<T> >::Ptr parameters,
		        typename TypedData< std::vector<T> >::Ptr errors
		) = 0;

};

template<typename T>
class LevenbergMarquardtErrorFnWrapper : public RefCountedWrapper< LevenbergMarquardtErrorFn<T> >
{
	public:

		IE_CORE_DECLAREMEMBERPTR( LevenbergMarquardtErrorFnWrapper<T> );

		LevenbergMarquardtErrorFnWrapper( PyObject *self )
			: RefCountedWrapper< LevenbergMarquardtErrorFn<T> >( self )
		{
		}

		virtual ~LevenbergMarquardtErrorFnWrapper()
		{
		}

		virtual unsigned numErrors()
		{
			ScopedGILLock gilLock;
			object o = this->methodOverride( "numErrors" );
			if( o )
			{
				try
				{
					return extract<unsigned>( o() );
				}
				catch( error_already_set )
				{
					PyErr_Print();
					return 0;
				}
			}
			else
			{
				throw Exception( "LevenbergMarquardt: Error function does not define 'numErrors' instance method" );
			}
		}

		virtual void computeErrors(
		        typename TypedData< std::vector<T> >::Ptr parameters,
		        typename TypedData< std::vector<T> >::Ptr errors
		)
		{
			ScopedGILLock gilLock;
			object o = this->methodOverride( "computeErrors" );
			if( o )
			{
				try
				{
					o( parameters, errors );
				}
				catch( error_already_set )
				{
					PyErr_Print();
					return;
				}
			}
			else
			{
				throw Exception( "LevenbergMarquardt: Error function does not define 'computeErrors' instance method" );
			}
		}
};

template< typename T>
class LevenbergMarquardtWrapper : public LevenbergMarquardt< T, LevenbergMarquardtErrorFnWrapper<T> >
{
	public:

		tuple getParameters()
		{
			T ftol, xtol, gtol, epsilon, stepBound;
			LevenbergMarquardt< T, LevenbergMarquardtErrorFnWrapper<T> >::getParameters( ftol, xtol, gtol, epsilon, stepBound );
			return make_tuple(ftol, xtol, gtol, epsilon, stepBound);
		}
};

template<typename T>
void bindLevenbergMarquardt( const char *name )
{
	object lm = class_< LevenbergMarquardtWrapper<T>, boost::noncopyable >( name, no_init )
		.def( init<>() )
		.def( "setParameters", &LevenbergMarquardtWrapper<T>::setParameters )
		.def( "getParameters", &LevenbergMarquardtWrapper<T>::getParameters )
		.def( "solve", &LevenbergMarquardtWrapper<T>::solve )
		.def( "setMaxCalls", &LevenbergMarquardtWrapper<T>::setMaxCalls )
		.def( "getMaxCalls", &LevenbergMarquardtWrapper<T>::getMaxCalls )
	;

	{
		scope lmS( lm );

		enum_< typename LevenbergMarquardtWrapper<T>::Status >( "Status" )
			.value( "Success", LevenbergMarquardtWrapper<T>::Success )
		;

		RefCountedClass<LevenbergMarquardtErrorFn<T>, RefCounted, LevenbergMarquardtErrorFnWrapper<T> >( "ErrorFn" )
			.def( init<>() )
			.def( "numErrors", pure_virtual( &LevenbergMarquardtErrorFnWrapper<T>::numErrors ) )
			.def( "computeErrors", pure_virtual( &LevenbergMarquardtErrorFnWrapper<T>::computeErrors ) )
		;
	}
}

void bindLevenbergMarquardt()
{
	bindLevenbergMarquardt< float >( "LevenbergMarquardtf" );
	bindLevenbergMarquardt< double >( "LevenbergMarquardtd" );
}

} // namespace IECorePython
<|endoftext|>


<commit_before>#include "ddrawoverlay.h"
#include <detourxs.h>
#include <ddraw.h>

typedef HRESULT(WINAPI *TYPE_DirectDrawCreate) (
	GUID FAR *,
	LPDIRECTDRAW FAR *,
	IUnknown FAR *
	);

TYPE_DirectDrawCreate pDirectDrawCreate;

HRESULT WINAPI DirectDrawCreate_Hook(
	GUID FAR *lpGUID,
	LPDIRECTDRAW FAR *lplpDD,
	IUnknown FAR *pUnkOuter
	)
{
	HRESULT returnValue = 0;

	OutputDebugStringW(L"[OVRENDER] DirectDrawCreate Called!");
	returnValue = pDirectDrawCreate(lpGUID, lplpDD, pUnkOuter);

	return returnValue;
}

DDrawOverlay::DDrawOverlay( OV_RENDER RenderFunction )
{
	HMODULE base;
	DetourXS *detour;
	OutputDebugStringW(L"[OVRENDER] Creating DirectDraw Overlay!");
	base = (HMODULE)LoadLibraryW(L"ddraw.dll");

	detour = new DetourXS(
		GetProcAddress(base, "DirectDrawCreateEx"),
		DirectDrawCreate_Hook
		);

	pDirectDrawCreate = (TYPE_DirectDrawCreate)detour->GetTrampoline();

	UserRenderFunction = RenderFunction;
}

VOID
DDrawOverlay::DrawText(WCHAR* Text)
{
	DrawText(Text, FALSE);
}

VOID DDrawOverlay::DrawText(
	WCHAR* Text,
	DWORD Color
	)
{
	DrawText(Text, 20, Line, Color);

	Line += 15;
}

VOID DDrawOverlay::DrawText(
	WCHAR* Text,
	int X,
	int Y,
	DWORD Color
	)
{

}

VOID
DDrawOverlay::Begin()
{

}

VOID
DDrawOverlay::End()
{

}

VOID*
DDrawOverlay::GetDevice()
{
	return NULL;
}<commit_msg>fixed incorrect calling convention. fixes #51<commit_after>#include "ddrawoverlay.h"
#include <detourxs.h>
#include <ddraw.h>

typedef HRESULT(WINAPI *TYPE_DirectDrawCreate) (
    GUID FAR *,
    LPDIRECTDRAW FAR *,
    IUnknown FAR *
    );

TYPE_DirectDrawCreate pDirectDrawCreate;

HRESULT WINAPI DirectDrawCreate_Hook(
    GUID FAR *lpGUID,
    LPDIRECTDRAW FAR *lplpDD,
    IUnknown FAR *pUnkOuter
    )
{
    HRESULT returnValue = 0;

    OutputDebugStringW(L"[OVRENDER] DirectDrawCreate Called!");
    returnValue = pDirectDrawCreate(lpGUID, lplpDD, pUnkOuter);

    return returnValue;
}

DDrawOverlay::DDrawOverlay( OV_RENDER RenderFunction )
{
    HMODULE base;
    DetourXS *detour;
    OutputDebugStringW(L"[OVRENDER] Creating DirectDraw Overlay!");
    base = (HMODULE)LoadLibraryW(L"ddraw.dll");

    detour = new DetourXS(
        GetProcAddress(base, "DirectDrawCreate"),
        DirectDrawCreate_Hook
        );

    pDirectDrawCreate = (TYPE_DirectDrawCreate)detour->GetTrampoline();

    UserRenderFunction = RenderFunction;
}

VOID
DDrawOverlay::DrawText(WCHAR* Text)
{
    DrawText(Text, FALSE);
}

VOID DDrawOverlay::DrawText(
    WCHAR* Text,
    DWORD Color
    )
{
    DrawText(Text, 20, Line, Color);

    Line += 15;
}

VOID DDrawOverlay::DrawText(
    WCHAR* Text,
    int X,
    int Y,
    DWORD Color
    )
{

}

VOID
DDrawOverlay::Begin()
{

}

VOID
DDrawOverlay::End()
{

}

VOID*
DDrawOverlay::GetDevice()
{
    return NULL;
}<|endoftext|>


<commit_before>#include <iostream>
#include <random>

#include <timeit/timeit.h>

int main()
{
    std::minstd_rand rnd;
    std::cout << timeit::total<std::chrono::nanoseconds>([&rnd](){ rnd(); }, 10000000).count() << " ns" << std::endl;

    return 0;
}<commit_msg>added precise (nanoseconds) example<commit_after>#include <iostream>
#include <string>
#include <random>

#include <timeit/timeit.h>

template <typename Random>
void benchmark(const std::string &engine, size_t iterations)
{
    Random rnd;
    std::cout << engine << " - " << timeit::average<std::chrono::nanoseconds>([&rnd](){ rnd(); }, iterations).count() << " ns" << std::endl;
}

int main()
{
    auto iterations = 1000000;
    benchmark<std::minstd_rand>("minstd_rand");
    benchmark<std::mt19937>("mt19937");
    benchmark<std::ranlux24>("ranlux24");
    benchmark<std::knuth_b>("knuth_b");
    return 0;
}<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>
 *
 * 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/>.
 */

#include <components/screen_butler.hpp>

namespace bookwyrm::tui {

std::shared_ptr<screen_butler> make_with(script_butler &butler, vector<py::module> &sources)
{
    auto tui = std::make_shared<screen_butler>(butler.results());
    butler.set_screens(tui);
    butler.async_search(sources); // Watch out, it's hot!
    return tui;
}

/* ns bookwyrm::tui */
}
<commit_msg>remove unused source file<commit_after><|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 *
 * plan_transformer.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /n-store/src/bridge/plan_transformer.cpp
 *
 *-------------------------------------------------------------------------
 */

#include <cstring>
#include <cassert>

#include "backend/bridge/dml/mapper/mapper.h"

#include "nodes/print.h"
#include "nodes/pprint.h"
#include "utils/lsyscache.h"
#include "executor/executor.h"
#include "parser/parsetree.h"

void printPlanStateTree(const PlanState * planstate);

namespace peloton {
namespace bridge {

extern const ValueArray BuildParams(const ParamListInfo param_list);

/**
 * @brief Pretty print the plan state tree.
 * @return none.
 */
void PlanTransformer::PrintPlanState(const PlanState *plan_state) {
  printPlanStateTree(plan_state);
}

/**
 * @brief Convert Postgres PlanState (tree) into AbstractPlanNode (tree).
 * @return Pointer to the constructed AbstractPlan`Node.
 */
planner::AbstractPlanNode *PlanTransformer::TransformPlan(
    const PlanState *plan_state) {
  assert(plan_state);

  Plan *plan = plan_state->plan;

  if(plan == nullptr)
    return nullptr;

  planner::AbstractPlanNode *plan_node;
  ValueArray params;

  LOG_INFO("planstate %d with #param", nodeTag(plan_state));

  if(plan_state->state != nullptr)
    params = BuildParams(plan_state->state->es_param_list_info);

  switch (nodeTag(plan)) {
    case T_ModifyTable:
      plan_node = PlanTransformer::TransformModifyTable(
          reinterpret_cast<const ModifyTableState *>(plan_state), params);
      break;
    case T_SeqScan:
      plan_node = PlanTransformer::TransformSeqScan(
          reinterpret_cast<const SeqScanState*>(plan_state), params);
      break;
    case T_IndexScan:
      plan_node = PlanTransformer::TransformIndexScan(
          reinterpret_cast<const IndexScanState*>(plan_state), params);
      break;
    case T_IndexOnlyScan:
      plan_node = PlanTransformer::TransformIndexOnlyScan(
          reinterpret_cast<const IndexOnlyScanState*>(plan_state), params);
      break;
    case T_Limit:
      plan_node = PlanTransformer::TransformLimit(
          reinterpret_cast<const LimitState*>(plan_state));
      break;
    default: {
      plan_node = nullptr;
      LOG_ERROR("Unsupported Postgres Plan Tag: %u Plan : %p", nodeTag(plan),
                plan);
      break;
    }
  }

  return plan_node;
}

/**
 * @brief Recursively destroy the nodes in a plan node tree.
 */
bool PlanTransformer::CleanPlanNodeTree(planner::AbstractPlanNode* root) {
  if (!root)
    return false;

  // Clean all children subtrees
  auto children = root->GetChildren();
  for (auto child : children) {
    auto rv = CleanPlanNodeTree(child);
    assert(rv);
  }

  // Clean the root
  delete root;
  return true;
}

inline const ValueArray BuildParams(const ParamListInfo param_list) {
  ValueArray params;
  if (param_list != nullptr) {
    params.Reset(param_list->numParams);
    for (int i = 0; i < params.GetSize(); ++i) {
      ParamExternData param = param_list->params[i];
      params[i] = TupleTransformer::GetValue(param.value, param.ptype);
    }
  }
  LOG_INFO("Built param list of size %d", params.GetSize());
  return params;
}

}  // namespace bridge
}  // namespace peloton

<commit_msg>minor change<commit_after>/*-------------------------------------------------------------------------
 *
 * plan_transformer.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /n-store/src/bridge/plan_transformer.cpp
 *
 *-------------------------------------------------------------------------
 */

#include <cstring>
#include <cassert>

#include "backend/bridge/dml/mapper/mapper.h"

#include "nodes/print.h"
#include "nodes/pprint.h"
#include "utils/lsyscache.h"
#include "executor/executor.h"
#include "parser/parsetree.h"

void printPlanStateTree(const PlanState * planstate);

namespace peloton {
namespace bridge {

extern const ValueArray BuildParams(const ParamListInfo param_list);

/**
 * @brief Pretty print the plan state tree.
 * @return none.
 */
void PlanTransformer::PrintPlanState(const PlanState *plan_state) {
  printPlanStateTree(plan_state);
}

/**
 * @brief Convert Postgres PlanState (tree) into AbstractPlanNode (tree).
 * @return Pointer to the constructed AbstractPlan`Node.
 */
planner::AbstractPlanNode *PlanTransformer::TransformPlan(
    const PlanState *plan_state) {
  assert(plan_state);

  Plan *plan = plan_state->plan;

  if(plan == nullptr)
    return nullptr;

  planner::AbstractPlanNode *plan_node;
  ValueArray params;

  LOG_INFO("planstate %d", nodeTag(plan_state));

  if(plan_state->state != nullptr)
    params = BuildParams(plan_state->state->es_param_list_info);

  switch (nodeTag(plan)) {
    case T_ModifyTable:
      plan_node = PlanTransformer::TransformModifyTable(
          reinterpret_cast<const ModifyTableState *>(plan_state), params);
      break;
    case T_SeqScan:
      plan_node = PlanTransformer::TransformSeqScan(
          reinterpret_cast<const SeqScanState*>(plan_state), params);
      break;
    case T_IndexScan:
      plan_node = PlanTransformer::TransformIndexScan(
          reinterpret_cast<const IndexScanState*>(plan_state), params);
      break;
    case T_IndexOnlyScan:
      plan_node = PlanTransformer::TransformIndexOnlyScan(
          reinterpret_cast<const IndexOnlyScanState*>(plan_state), params);
      break;
    case T_Limit:
      plan_node = PlanTransformer::TransformLimit(
          reinterpret_cast<const LimitState*>(plan_state));
      break;
    default: {
      plan_node = nullptr;
      LOG_ERROR("Unsupported Postgres Plan Tag: %u Plan : %p", nodeTag(plan),
                plan);
      break;
    }
  }

  return plan_node;
}

/**
 * @brief Recursively destroy the nodes in a plan node tree.
 */
bool PlanTransformer::CleanPlanNodeTree(planner::AbstractPlanNode* root) {
  if (!root)
    return false;

  // Clean all children subtrees
  auto children = root->GetChildren();
  for (auto child : children) {
    auto rv = CleanPlanNodeTree(child);
    assert(rv);
  }

  // Clean the root
  delete root;
  return true;
}

inline const ValueArray BuildParams(const ParamListInfo param_list) {
  ValueArray params;
  if (param_list != nullptr) {
    params.Reset(param_list->numParams);
    for (int i = 0; i < params.GetSize(); ++i) {
      ParamExternData param = param_list->params[i];
      params[i] = TupleTransformer::GetValue(param.value, param.ptype);
    }
  }
  LOG_INFO("Built param list of size %d", params.GetSize());
  return params;
}

}  // namespace bridge
}  // namespace peloton

<|endoftext|>