<commit_before>/*
   Copyright (c) 2010, The Mineserver Project
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the The Mineserver Project nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 "tracks.h"
//#include <iostream>

enum {
  FLAT_NS = 0,
  FLAT_EW,
  ASCEND_S,
  ASCEND_N,
  ASCEND_E,
  ASCEND_W,
  CORNER_SE,
  CORNER_SW,
  CORNER_NW,
  CORNER_NE
};

void BlockTracks::onStartedDigging(User* user, sint8 status, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onDigging(User* user, sint8 status, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onStoppedDigging(User* user, sint8 status, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onBroken(User* user, sint8 status, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onNeighbourBroken(User* user, sint8 oldblock, sint32 x, sint8 y, sint32 z, sint8 direction)
{
  uint8 block;
  uint8 meta;

  if (!Map::get()->getBlock(x, y, z, &block, &meta))
    return;

  if (this->isBlockEmpty(x, y-1, z))
  {
    // Break torch and spawn torch item
    Map::get()->sendBlockChange(x, y, z, BLOCK_AIR, 0);
    Map::get()->setBlock(x, y, z, BLOCK_AIR, 0);
    this->spawnBlockItem(x, y, z, block);
  }
}

void BlockTracks::onPlace(User* user, sint8 newblock, sint32 x, sint8 y, sint32 z, sint8 direction)
{
  uint8 block;
  uint8 meta;

  if (!Map::get()->getBlock(x, y, z, &block, &meta))
     return;

  /* Check block below allows blocks placed on top */
  if (!this->isBlockStackable(block))
     return;

  /* move the x,y,z coords dependent upon placement direction */
  if (!this->translateDirection(&x,&y,&z,direction))
     return;

  if (!this->isBlockEmpty(x,y,z))
     return;

  uint8 metadata = FLAT_NS;

  // SOUTH
  if(isTrack(x, y, z-1, meta) && isStartPiece(x, y, z-1))
  {
    //std::cout << "SOUTH" << std::endl;
    metadata = FLAT_NS;

    if(isTrack(x+1, y, z, meta) && isStartPiece(x+1, y, z))
    {
      metadata = CORNER_NE;
    }
    if(isTrack(x-1, y, z, meta) && isStartPiece(x-1, y, z))
    {
      metadata = CORNER_NW;
    }

    // Modify previous trackpiece to form corner
    if(isTrack(x-1, y, z-1, meta) && meta != FLAT_NS && meta != CORNER_NW && meta != CORNER_SW)
    {
      Map::get()->setBlock(x, y, z-1, (char)newblock, CORNER_SW);
      Map::get()->sendBlockChange(x, y, z-1, (char)newblock, CORNER_SW);
    }
    else if(isTrack(x+1, y, z-1, meta) && meta != FLAT_NS && meta != CORNER_NE && meta != CORNER_SE)
    {
      Map::get()->setBlock(x, y, z-1, (char)newblock, CORNER_SE);
      Map::get()->sendBlockChange(x, y, z-1, (char)newblock, CORNER_SE);
    }
  }

  // NORTH
  if(isTrack(x, y, z+1, meta) && isStartPiece(x, y, z+1))
  {
    //std::cout << "NORTH" << std::endl;

    metadata = FLAT_NS;

    if(isTrack(x+1, y, z, meta) && isStartPiece(x+1, y, z))
    {
      metadata = CORNER_SE;
    }
    if(isTrack(x-1, y, z, meta) && isStartPiece(x-1, y, z))
    {
      metadata = CORNER_SW;
    }

    // Modify previous trackpiece to form corner
    if(isTrack(x+1, y, z+1, meta) && meta != FLAT_NS && meta != CORNER_NE && meta != CORNER_SE)
    {
      Map::get()->setBlock(x, y, z+1, (char)newblock, CORNER_NE);
      Map::get()->sendBlockChange(x, y, z+1, (char)newblock, CORNER_NE);
    }
    else if(isTrack(x-1, y, z+1, meta) && meta != FLAT_NS && meta != CORNER_NW && meta != CORNER_SW)
    {
      Map::get()->setBlock(x, y, z+1, (char)newblock, CORNER_NW);
      Map::get()->sendBlockChange(x, y, z+1, (char)newblock, CORNER_NW);
    }
  }

  // EAST
  if(isTrack(x-1, y, z, meta) && isStartPiece(x-1, y, z))
  {
    //std::cout << "EAST" << std::endl;
    metadata = FLAT_EW;
    // Change previous block meta
    Map::get()->setBlock(x-1, y, z, (char)newblock, FLAT_EW);
    Map::get()->sendBlockChange(x-1, y, z, (char)newblock, FLAT_EW);

    if(isTrack(x, y, z+1, meta) && isStartPiece(x, y, z+1))
    {
      metadata = CORNER_SW;
    }
    if(isTrack(x, y, z-1, meta) && isStartPiece(x, y, z-1))
    {
      metadata = CORNER_NW;
    }

    // Modify previous trackpiece to form corner
    if(isTrack(x-1, y, z-1, meta) && meta != FLAT_EW && meta != CORNER_NE && meta != CORNER_NW)
    {
      Map::get()->setBlock(x-1, y, z, (char)newblock, CORNER_NE);
      Map::get()->sendBlockChange(x-1, y, z, (char)newblock, CORNER_NE);
    }
    else if(isTrack(x-1, y, z+1, meta) && meta != FLAT_EW && meta != CORNER_SW && meta != CORNER_SE)
    {
      Map::get()->setBlock(x-1, y, z, (char)newblock, CORNER_SE);
      Map::get()->sendBlockChange(x-1, y, z, (char)newblock, CORNER_SE);
    }
  }

  // WEST
  if(isTrack(x+1, y, z, meta) && isStartPiece(x+1, y, z))
  {
    //std::cout << "WEST" << std::endl;
    metadata = FLAT_EW;
    // Change previous block meta

    Map::get()->setBlock(x+1, y, z, (char)newblock, FLAT_EW);
    Map::get()->sendBlockChange(x+1, y, z, (char)newblock, FLAT_EW);

    if(isTrack(x, y, z+1, meta) && isStartPiece(x, y, z+1))
    {
      metadata = CORNER_SE;
    }
    if(isTrack(x, y, z-1, meta) && isStartPiece(x, y, z-1))
    {
      metadata = CORNER_NE;
    }

    // Modify previous trackpiece to form corner
    if(isTrack(x+1, y, z-1, meta) && meta != FLAT_EW && meta != CORNER_NW && meta != CORNER_NE)
    {
      Map::get()->setBlock(x+1, y, z, (char)newblock, CORNER_NW);
      Map::get()->sendBlockChange(x+1, y, z, (char)newblock, CORNER_NW);
    }
    else if(isTrack(x+1, y, z+1, meta) && meta != FLAT_EW && meta != CORNER_SW && meta != CORNER_SE)
    {
      Map::get()->setBlock(x+1, y, z, (char)newblock, CORNER_SW);
      Map::get()->sendBlockChange(x+1, y, z, (char)newblock, CORNER_SW);
    }
  }

  //std::cout << std::endl;
  Map::get()->setBlock(x, y, z, (char)newblock, metadata);
  Map::get()->sendBlockChange(x, y, z, (char)newblock, metadata);
}

void BlockTracks::onNeighbourPlace(User* user, sint8 newblock, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onReplace(User* user, sint8 newblock, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onNeighbourMove(User* user, sint8 oldblock, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

bool BlockTracks::isTrack(sint32 x, sint8 y, sint32 z, uint8& meta)
{
  uint8 block;
  Map::get()->getBlock(x, y, z, &block, &meta);
  return (block == BLOCK_MINECART_TRACKS);
}

bool BlockTracks::isStartPiece(sint32 x, sint8 y, sint32 z)
{
  uint8 block;
  uint8 meta;
  sint32 x1, x2, z1, z2;
  x1 = x2 = x;
  z1 = z2 = z;

  sint8 y1, y2;
  y1 = y2 = y;

  Map::get()->getBlock(x, y, z, &block, &meta);
  switch(meta)
  {
    case FLAT_EW:
      x1--;
      x2++;
      break;
    case FLAT_NS:
      z1--;
      z2++;
      break;
    case CORNER_SE:
      x1++;
      z2++;
      break;
    case CORNER_SW:
      z1++;
      x2--;
      break;
    case CORNER_NE:
      x1++;
      z2--;
      break;
    case CORNER_NW:
      x1--;
      z2--;
      break;
  }

  if((Map::get()->getBlock(x1, y1, z1, &block, &meta) && block != BLOCK_MINECART_TRACKS) ||
     (Map::get()->getBlock(x2, y2, z2, &block, &meta) && block != BLOCK_MINECART_TRACKS))
  {
    return true;
  }
  else
  {
    return false;
  }
}

<commit_msg>Some support for ascending tracks<commit_after>/*
   Copyright (c) 2010, The Mineserver Project
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 * Neither the name of the The Mineserver Project nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 "tracks.h"
#include <iostream>

enum {
  FLAT_NS = 0,
  FLAT_EW,
  ASCEND_W,
  ASCEND_E,
  ASCEND_S,
  ASCEND_N,
  CORNER_SE,
  CORNER_SW,
  CORNER_NW,
  CORNER_NE
};

void BlockTracks::onStartedDigging(User* user, sint8 status, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onDigging(User* user, sint8 status, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onStoppedDigging(User* user, sint8 status, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onBroken(User* user, sint8 status, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onNeighbourBroken(User* user, sint8 oldblock, sint32 x, sint8 y, sint32 z, sint8 direction)
{
  uint8 block;
  uint8 meta;

  if (!Map::get()->getBlock(x, y, z, &block, &meta))
    return;

  if (this->isBlockEmpty(x, y-1, z))
  {
    // Break torch and spawn torch item
    Map::get()->sendBlockChange(x, y, z, BLOCK_AIR, 0);
    Map::get()->setBlock(x, y, z, BLOCK_AIR, 0);
    this->spawnBlockItem(x, y, z, block);
  }
}

void BlockTracks::onPlace(User* user, sint8 newblock, sint32 x, sint8 y, sint32 z, sint8 direction)
{
  uint8 block;
  uint8 meta;

  if (!Map::get()->getBlock(x, y, z, &block, &meta))
     return;

  /* Check block below allows blocks placed on top */
  if (!this->isBlockStackable(block))
     return;

  /* move the x,y,z coords dependent upon placement direction */
  if (!this->translateDirection(&x,&y,&z,direction))
     return;

  if (!this->isBlockEmpty(x,y,z))
     return;

  uint8 metadata = FLAT_NS;

  // SOUTH
  if(isTrack(x, y, z-1, meta) && isStartPiece(x, y, z-1))
  {
    std::cout << "SOUTH" << std::endl;
    metadata = FLAT_NS;

    // Rising & falling tracks
    if(isTrack(x, y+1, z+1, meta) && isStartPiece(x, y+1, z+1))
    {
      metadata = ASCEND_N;
    }

    if(isTrack(x+1, y, z, meta) && isStartPiece(x+1, y, z))
    {
      metadata = CORNER_NE;
    }
    if(isTrack(x-1, y, z, meta) && isStartPiece(x-1, y, z))
    {
      metadata = CORNER_NW;
    }

    // Modify previous trackpiece to form corner
    if(isTrack(x-1, y, z-1, meta) && meta != FLAT_NS && meta != CORNER_NW && meta != CORNER_SW)
    {
      Map::get()->setBlock(x, y, z-1, (char)newblock, CORNER_SW);
      Map::get()->sendBlockChange(x, y, z-1, (char)newblock, CORNER_SW);
    }
    else if(isTrack(x+1, y, z-1, meta) && meta != FLAT_NS && meta != CORNER_NE && meta != CORNER_SE)
    {
      Map::get()->setBlock(x, y, z-1, (char)newblock, CORNER_SE);
      Map::get()->sendBlockChange(x, y, z-1, (char)newblock, CORNER_SE);
    }
  }

  // NORTH
  if(isTrack(x, y, z+1, meta) && isStartPiece(x, y, z+1))
  {
    std::cout << "NORTH" << std::endl;

    metadata = FLAT_NS;
    // Rising & falling tracks
    if(isTrack(x, y+1, z-1, meta) && isStartPiece(x, y+1, z-1))
    {
      metadata = ASCEND_S;
    }

    if(isTrack(x+1, y, z, meta) && isStartPiece(x+1, y, z))
    {
      metadata = CORNER_SE;
    }
    if(isTrack(x-1, y, z, meta) && isStartPiece(x-1, y, z))
    {
      metadata = CORNER_SW;
    }

    // Modify previous trackpiece to form corner
    if(isTrack(x+1, y, z+1, meta) && meta != FLAT_NS && meta != CORNER_NE && meta != CORNER_SE)
    {
      Map::get()->setBlock(x, y, z+1, (char)newblock, CORNER_NE);
      Map::get()->sendBlockChange(x, y, z+1, (char)newblock, CORNER_NE);
    }
    else if(isTrack(x-1, y, z+1, meta) && meta != FLAT_NS && meta != CORNER_NW && meta != CORNER_SW)
    {
      Map::get()->setBlock(x, y, z+1, (char)newblock, CORNER_NW);
      Map::get()->sendBlockChange(x, y, z+1, (char)newblock, CORNER_NW);
    }
  }

  // EAST
  if(isTrack(x-1, y, z, meta) && isStartPiece(x-1, y, z))
  {
    std::cout << "EAST" << std::endl;
    metadata = FLAT_EW;

    // Rising & falling tracks
    if(isTrack(x+1, y+1, z, meta) && isStartPiece(x+1, y+1, z))
    {
      metadata = ASCEND_W;
    }
    else
    {
      // Change previous block meta
      Map::get()->setBlock(x-1, y, z, (char)newblock, FLAT_EW);
      Map::get()->sendBlockChange(x-1, y, z, (char)newblock, FLAT_EW);
    }

    if(isTrack(x, y, z+1, meta) && isStartPiece(x, y, z+1))
    {
      metadata = CORNER_SW;
    }
    if(isTrack(x, y, z-1, meta) && isStartPiece(x, y, z-1))
    {
      metadata = CORNER_NW;
    }

    // Modify previous trackpiece to form corner
    if(isTrack(x-1, y, z-1, meta) && meta != FLAT_EW && meta != CORNER_NE && meta != CORNER_NW)
    {
      Map::get()->setBlock(x-1, y, z, (char)newblock, CORNER_NE);
      Map::get()->sendBlockChange(x-1, y, z, (char)newblock, CORNER_NE);
    }
    else if(isTrack(x-1, y, z+1, meta) && meta != FLAT_EW && meta != CORNER_SW && meta != CORNER_SE)
    {
      Map::get()->setBlock(x-1, y, z, (char)newblock, CORNER_SE);
      Map::get()->sendBlockChange(x-1, y, z, (char)newblock, CORNER_SE);
    }
  }

  // WEST
  if(isTrack(x+1, y, z, meta) && isStartPiece(x+1, y, z))
  {
    std::cout << "WEST" << std::endl;
    metadata = FLAT_EW;
    // Change previous block meta

    // Rising & falling tracks
    if(isTrack(x-1, y+1, z, meta) && isStartPiece(x-1, y+1, z))
    {
      metadata = ASCEND_E;
    }
    else
    {
      Map::get()->setBlock(x+1, y, z, (char)newblock, FLAT_EW);
      Map::get()->sendBlockChange(x+1, y, z, (char)newblock, FLAT_EW);
    }

    if(isTrack(x, y, z+1, meta) && isStartPiece(x, y, z+1))
    {
      metadata = CORNER_SE;
    }
    if(isTrack(x, y, z-1, meta) && isStartPiece(x, y, z-1))
    {
      metadata = CORNER_NE;
    }

    // Modify previous trackpiece to form corner
    if(isTrack(x+1, y, z-1, meta) && meta != FLAT_EW && meta != CORNER_NW && meta != CORNER_NE)
    {
      Map::get()->setBlock(x+1, y, z, (char)newblock, CORNER_NW);
      Map::get()->sendBlockChange(x+1, y, z, (char)newblock, CORNER_NW);
    }
    else if(isTrack(x+1, y, z+1, meta) && meta != FLAT_EW && meta != CORNER_SW && meta != CORNER_SE)
    {
      Map::get()->setBlock(x+1, y, z, (char)newblock, CORNER_SW);
      Map::get()->sendBlockChange(x+1, y, z, (char)newblock, CORNER_SW);
    }
  }

  std::cout << std::endl;
  Map::get()->setBlock(x, y, z, (char)newblock, metadata);
  Map::get()->sendBlockChange(x, y, z, (char)newblock, metadata);
}

void BlockTracks::onNeighbourPlace(User* user, sint8 newblock, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onReplace(User* user, sint8 newblock, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

void BlockTracks::onNeighbourMove(User* user, sint8 oldblock, sint32 x, sint8 y, sint32 z, sint8 direction)
{

}

bool BlockTracks::isTrack(sint32 x, sint8 y, sint32 z, uint8& meta)
{
  uint8 block;
  Map::get()->getBlock(x, y, z, &block, &meta);
  return (block == BLOCK_MINECART_TRACKS);
}

bool BlockTracks::isStartPiece(sint32 x, sint8 y, sint32 z)
{
  uint8 block;
  uint8 meta;
  sint32 x1, x2, z1, z2;
  x1 = x2 = x;
  z1 = z2 = z;

  sint8 y1, y2;
  y1 = y2 = y;

  Map::get()->getBlock(x, y, z, &block, &meta);
  switch(meta)
  {
    case FLAT_EW:
      x1--;
      x2++;
      break;
    case FLAT_NS:
      z1--;
      z2++;
      break;
    case CORNER_SE:
      x1++;
      z2++;
      break;
    case CORNER_SW:
      z1++;
      x2--;
      break;
    case CORNER_NE:
      x1++;
      z2--;
      break;
    case CORNER_NW:
      x1--;
      z2--;
      break;
    case ASCEND_E:
      y1++;
      x1--;
      x2++;
      break;
    case ASCEND_N:
      y1++;
      z1++;
      z2--;
      break;
    case ASCEND_S:
      y1++;
      z1--;
      z2++;
      break;
    case ASCEND_W:
      y1++;
      x1++;
      x2--;
      break;
  }

  if((Map::get()->getBlock(x1, y1, z1, &block, &meta) && block != BLOCK_MINECART_TRACKS) ||
     (Map::get()->getBlock(x2, y2, z2, &block, &meta) && block != BLOCK_MINECART_TRACKS))
  {
    return true;
  }
  else
  {
    return false;
  }
}

<|endoftext|>


<commit_before>#include "gbdt.h"

#include <LightGBM/utils/common.h>

#include <LightGBM/feature.h>
#include <LightGBM/objective_function.h>
#include <LightGBM/metric.h>

#include <ctime>

#include <sstream>
#include <chrono>
#include <string>
#include <vector>

namespace LightGBM {

GBDT::GBDT(const BoostingConfig* config)
  : tree_learner_(nullptr), train_score_updater_(nullptr),
  gradients_(nullptr), hessians_(nullptr),
  out_of_bag_data_indices_(nullptr), bag_data_indices_(nullptr) {
  max_feature_idx_ = 0;
  gbdt_config_ = dynamic_cast<const GBDTConfig*>(config);
  early_stopping_round_ = gbdt_config_->early_stopping_round;
}

GBDT::~GBDT() {
  if (tree_learner_ != nullptr) { delete tree_learner_; }
  if (gradients_ != nullptr) { delete[] gradients_; }
  if (hessians_ != nullptr) { delete[] hessians_; }
  if (out_of_bag_data_indices_ != nullptr) { delete[] out_of_bag_data_indices_; }
  if (bag_data_indices_ != nullptr) { delete[] bag_data_indices_; }
  for (auto& tree : models_) {
    if (tree != nullptr) { delete tree; }
  }
  if (train_score_updater_ != nullptr) { delete train_score_updater_; }
  for (auto& score_tracker : valid_score_updater_) {
    if (score_tracker != nullptr) { delete score_tracker; }
  }
}

void GBDT::Init(const Dataset* train_data, const ObjectiveFunction* object_function,
     const std::vector<const Metric*>& training_metrics, const char* output_model_filename) {
  train_data_ = train_data;
  // create tree learner
  tree_learner_ =
    TreeLearner::CreateTreeLearner(gbdt_config_->tree_learner_type, gbdt_config_->tree_config);
  // init tree learner
  tree_learner_->Init(train_data_);
  object_function_ = object_function;
  // push training metrics
  for (const auto& metric : training_metrics) {
    training_metrics_.push_back(metric);
  }
  // create score tracker
  train_score_updater_ = new ScoreUpdater(train_data_);
  num_data_ = train_data_->num_data();
  // create buffer for gradients and hessians
  gradients_ = new score_t[num_data_];
  hessians_ = new score_t[num_data_];

  // get max feature index
  max_feature_idx_ = train_data_->num_total_features() - 1;

  // if need bagging, create buffer
  if (gbdt_config_->bagging_fraction < 1.0 && gbdt_config_->bagging_freq > 0) {
    out_of_bag_data_indices_ = new data_size_t[num_data_];
    bag_data_indices_ = new data_size_t[num_data_];
  } else {
    out_of_bag_data_cnt_ = 0;
    out_of_bag_data_indices_ = nullptr;
    bag_data_cnt_ = num_data_;
    bag_data_indices_ = nullptr;
  }
  // initialize random generator
  random_ = Random(gbdt_config_->bagging_seed);

  // open model output file
  #ifdef _MSC_VER
  fopen_s(&output_model_file, output_model_filename, "w");
  #else
  output_model_file = fopen(output_model_filename, "w");
  #endif
  // output models
  fprintf(output_model_file, "%s", this->ModelsToString().c_str());
}

void GBDT::AddDataset(const Dataset* valid_data,
         const std::vector<const Metric*>& valid_metrics) {
  // for a validation dataset, we need its score and metric
  valid_score_updater_.push_back(new ScoreUpdater(valid_data));
  valid_metrics_.emplace_back();
  best_iter_.emplace_back();
  best_score_.emplace_back();
  for (const auto& metric : valid_metrics) {
    valid_metrics_.back().push_back(metric);
    best_iter_.back().push_back(0);
    best_score_.back().push_back(-1);
  }
}

void GBDT::Bagging(int iter) {
  // if need bagging
  if (out_of_bag_data_indices_ != nullptr && iter % gbdt_config_->bagging_freq == 0) {
    // if doesn't have query data
    if (train_data_->metadata().query_boundaries() == nullptr) {
      bag_data_cnt_ =
        static_cast<data_size_t>(gbdt_config_->bagging_fraction * num_data_);
      out_of_bag_data_cnt_ = num_data_ - bag_data_cnt_;
      data_size_t cur_left_cnt = 0;
      data_size_t cur_right_cnt = 0;
      // random bagging, minimal unit is one record
      for (data_size_t i = 0; i < num_data_; ++i) {
        double prob =
          (bag_data_cnt_ - cur_left_cnt) / static_cast<double>(num_data_ - i);
        if (random_.NextDouble() < prob) {
          bag_data_indices_[cur_left_cnt++] = i;
        } else {
          out_of_bag_data_indices_[cur_right_cnt++] = i;
        }
      }
    } else {
      // if have query data
      const data_size_t* query_boundaries = train_data_->metadata().query_boundaries();
      data_size_t num_query = train_data_->metadata().num_queries();
      data_size_t bag_query_cnt =
          static_cast<data_size_t>(num_query * gbdt_config_->bagging_fraction);
      data_size_t cur_left_query_cnt = 0;
      data_size_t cur_left_cnt = 0;
      data_size_t cur_right_cnt = 0;
      // random bagging, minimal unit is one query
      for (data_size_t i = 0; i < num_query; ++i) {
        double prob =
            (bag_query_cnt - cur_left_query_cnt) / static_cast<double>(num_query - i);
        if (random_.NextDouble() < prob) {
          for (data_size_t j = query_boundaries[i]; j < query_boundaries[i + 1]; ++j) {
            bag_data_indices_[cur_left_cnt++] = j;
          }
          cur_left_query_cnt++;
        } else {
          for (data_size_t j = query_boundaries[i]; j < query_boundaries[i + 1]; ++j) {
            out_of_bag_data_indices_[cur_right_cnt++] = j;
          }
        }
      }
      bag_data_cnt_ = cur_left_cnt;
      out_of_bag_data_cnt_ = num_data_ - bag_data_cnt_;
    }
    Log::Stdout("re-bagging, using %d data to train", bag_data_cnt_);
    // set bagging data to tree learner
    tree_learner_->SetBaggingData(bag_data_indices_, bag_data_cnt_);
  }
}

void GBDT::UpdateScoreOutOfBag(const Tree* tree) {
  // we need to predict out-of-bag socres of data for boosting
  if (out_of_bag_data_indices_ != nullptr) {
    train_score_updater_->
      AddScore(tree, out_of_bag_data_indices_, out_of_bag_data_cnt_);
  }
}

void GBDT::Train() {
  // training start time
  auto start_time = std::chrono::high_resolution_clock::now();
  for (int iter = 0; iter < gbdt_config_->num_iterations; ++iter) {
    // boosting first
    Boosting();
    // bagging logic
    Bagging(iter);
    // train a new tree
    Tree * new_tree = TrainOneTree();
    // if cannot learn a new tree, then stop
    if (new_tree->num_leaves() <= 1) {
      Log::Stdout("Cannot do any boosting for tree cannot split");
      break;
    }
    // shrinkage by learning rate
    new_tree->Shrinkage(gbdt_config_->learning_rate);
    // update score
    UpdateScore(new_tree);
    UpdateScoreOutOfBag(new_tree);
    // print message for metric
    bool is_early_stopping = OutputMetric(iter + 1);
    // add model
    models_.push_back(new_tree);
    // save model to file per iteration
    if (early_stopping_round_ > 0){
        // if use early stopping, save previous model at (iter - early_stopping_round_) iteration
        if (iter >= early_stopping_round_){
            fprintf(output_model_file, "Tree=%d\n", iter - early_stopping_round_);
            Tree * printing_tree = models_.at(iter - early_stopping_round_);
            fprintf(output_model_file, "%s\n", printing_tree->ToString().c_str());
            fflush(output_model_file);
        }
    }
    else{
        fprintf(output_model_file, "Tree=%d\n", iter);
        fprintf(output_model_file, "%s\n", new_tree->ToString().c_str());
        fflush(output_model_file);
    }
    auto end_time = std::chrono::high_resolution_clock::now();
    // output used time per iteration
    Log::Stdout("%f seconds elapsed, finished %d iteration", std::chrono::duration<double,
                                     std::milli>(end_time - start_time) * 1e-3, iter + 1);
    if (is_early_stopping) {
        // close file with an early-stopping message
        Log::Stdout("early stopping at iteration %d, the best iteration round is %d", iter + 1, iter + 1 - early_stopping_round_);
        fclose(output_model_file);
        return;
    }
  }
  // close file
  if (early_stopping_round_ > 0) {
      // save remaining models
      for (int iter = gbdt_config_->num_iterations - early_stopping_round_; iter < models_.size(); ++iter){
        fprintf(output_model_file, "Tree=%d\n", iter);
        fprintf(output_model_file, "%s\n", models_.at(iter)->ToString().c_str());
      }
      fflush(output_model_file);
  }
  fclose(output_model_file);
}

Tree* GBDT::TrainOneTree() {
  return tree_learner_->Train(gradients_, hessians_);
}

void GBDT::UpdateScore(const Tree* tree) {
  // update training score
  train_score_updater_->AddScore(tree_learner_);
  // update validation score
  for (auto& score_tracker : valid_score_updater_) {
    score_tracker->AddScore(tree);
  }
}

bool GBDT::OutputMetric(int iter) {
  bool ret = false;
  // print training metric
  for (auto& sub_metric : training_metrics_) {
    sub_metric->PrintAndGetLoss(iter, train_score_updater_->score());
  }
  // print validation metric
  for (size_t i = 0; i < valid_metrics_.size(); ++i) {
    for (size_t j = 0; j < valid_metrics_[i].size(); ++j) {
      score_t test_score_ = valid_metrics_[i][j]->PrintAndGetLoss(iter, valid_score_updater_[i]->score());
      if (!ret && early_stopping_round_ > 0){
        bool the_bigger_the_better_ = valid_metrics_[i][j]->the_bigger_the_better;
        if (best_score_[i][j] < 0
            || (!the_bigger_the_better_ && test_score_ < best_score_[i][j])
            || ( the_bigger_the_better_ && test_score_ > best_score_[i][j])){
            best_score_[i][j] = test_score_;
            best_iter_[i][j] = iter;
        }
        else {
          if (iter - best_iter_[i][j] >= early_stopping_round_) ret = true;
        }
      }
    }
  }
  return ret;
}

void GBDT::Boosting() {
  // objective function will calculate gradients and hessians
  object_function_->
    GetGradients(train_score_updater_->score(), gradients_, hessians_);
}

std::string GBDT::ModelsToString() const {
  // serialize this object to string
  std::stringstream ss;
  // output max_feature_idx
  ss << "max_feature_idx=" << max_feature_idx_ << std::endl;
  // output sigmoid parameter
  ss << "sigmoid=" << object_function_->GetSigmoid() << std::endl;
  ss << std::endl;

  // output tree models
  for (size_t i = 0; i < models_.size(); ++i) {
    ss << "Tree=" << i << std::endl;
    ss << models_[i]->ToString() << std::endl;
  }
  return ss.str();
}

void GBDT::ModelsFromString(const std::string& model_str, int num_used_model) {
  // use serialized string to restore this object
  models_.clear();
  std::vector<std::string> lines = Common::Split(model_str.c_str(), '\n');
  size_t i = 0;
  // get max_feature_idx first
  while (i < lines.size()) {
    size_t find_pos = lines[i].find("max_feature_idx=");
    if (find_pos != std::string::npos) {
      std::vector<std::string> strs = Common::Split(lines[i].c_str(), '=');
      Common::Atoi(strs[1].c_str(), &max_feature_idx_);
      ++i;
      break;
    } else {
      ++i;
    }
  }
  if (i == lines.size()) {
    Log::Stderr("The model doesn't contain max_feature_idx");
    return;
  }
  // get sigmoid parameter
  i = 0;
  while (i < lines.size()) {
    size_t find_pos = lines[i].find("sigmoid=");
    if (find_pos != std::string::npos) {
      std::vector<std::string> strs = Common::Split(lines[i].c_str(), '=');
      Common::Atof(strs[1].c_str(), &sigmoid_);
      ++i;
      break;
    } else {
      ++i;
    }
  }
  // if sigmoid doesn't exists
  if (i == lines.size()) {
    sigmoid_ = -1.0;
  }
  // get tree models
  i = 0;
  while (i < lines.size()) {
    size_t find_pos = lines[i].find("Tree=");
    if (find_pos != std::string::npos) {
      ++i;
      int start = static_cast<int>(i);
      while (i < lines.size() && lines[i].find("Tree=") == std::string::npos) { ++i; }
      int end = static_cast<int>(i);
      std::string tree_str = Common::Join(lines, start, end, '\n');
      models_.push_back(new Tree(tree_str));
      if (num_used_model > 0 && models_.size() >= static_cast<size_t>(num_used_model)) {
        break;
      }
    } else {
      ++i;
    }
  }

  Log::Stdout("Loaded %d models\n", models_.size());
}

double GBDT::PredictRaw(const double* value) const {
  double ret = 0.0;
  for (size_t i = 0; i < models_.size(); ++i) {
    ret += models_[i]->Predict(value);
  }
  return ret;
}

double GBDT::Predict(const double* value) const {
  double ret = 0.0;
  for (size_t i = 0; i < models_.size(); ++i) {
    ret += models_[i]->Predict(value);
  }
  // if need sigmoid transform
  if (sigmoid_ > 0) {
    ret = 1.0 / (1.0 + std::exp(- 2.0f * sigmoid_ * ret));
  }
  return ret;
}

}  // namespace LightGBM
<commit_msg>warning fixed<commit_after>#include "gbdt.h"

#include <LightGBM/utils/common.h>

#include <LightGBM/feature.h>
#include <LightGBM/objective_function.h>
#include <LightGBM/metric.h>

#include <ctime>

#include <sstream>
#include <chrono>
#include <string>
#include <vector>

namespace LightGBM {

GBDT::GBDT(const BoostingConfig* config)
  : tree_learner_(nullptr), train_score_updater_(nullptr),
  gradients_(nullptr), hessians_(nullptr),
  out_of_bag_data_indices_(nullptr), bag_data_indices_(nullptr) {
  max_feature_idx_ = 0;
  gbdt_config_ = dynamic_cast<const GBDTConfig*>(config);
  early_stopping_round_ = gbdt_config_->early_stopping_round;
}

GBDT::~GBDT() {
  if (tree_learner_ != nullptr) { delete tree_learner_; }
  if (gradients_ != nullptr) { delete[] gradients_; }
  if (hessians_ != nullptr) { delete[] hessians_; }
  if (out_of_bag_data_indices_ != nullptr) { delete[] out_of_bag_data_indices_; }
  if (bag_data_indices_ != nullptr) { delete[] bag_data_indices_; }
  for (auto& tree : models_) {
    if (tree != nullptr) { delete tree; }
  }
  if (train_score_updater_ != nullptr) { delete train_score_updater_; }
  for (auto& score_tracker : valid_score_updater_) {
    if (score_tracker != nullptr) { delete score_tracker; }
  }
}

void GBDT::Init(const Dataset* train_data, const ObjectiveFunction* object_function,
     const std::vector<const Metric*>& training_metrics, const char* output_model_filename) {
  train_data_ = train_data;
  // create tree learner
  tree_learner_ =
    TreeLearner::CreateTreeLearner(gbdt_config_->tree_learner_type, gbdt_config_->tree_config);
  // init tree learner
  tree_learner_->Init(train_data_);
  object_function_ = object_function;
  // push training metrics
  for (const auto& metric : training_metrics) {
    training_metrics_.push_back(metric);
  }
  // create score tracker
  train_score_updater_ = new ScoreUpdater(train_data_);
  num_data_ = train_data_->num_data();
  // create buffer for gradients and hessians
  gradients_ = new score_t[num_data_];
  hessians_ = new score_t[num_data_];

  // get max feature index
  max_feature_idx_ = train_data_->num_total_features() - 1;

  // if need bagging, create buffer
  if (gbdt_config_->bagging_fraction < 1.0 && gbdt_config_->bagging_freq > 0) {
    out_of_bag_data_indices_ = new data_size_t[num_data_];
    bag_data_indices_ = new data_size_t[num_data_];
  } else {
    out_of_bag_data_cnt_ = 0;
    out_of_bag_data_indices_ = nullptr;
    bag_data_cnt_ = num_data_;
    bag_data_indices_ = nullptr;
  }
  // initialize random generator
  random_ = Random(gbdt_config_->bagging_seed);

  // open model output file
  #ifdef _MSC_VER
  fopen_s(&output_model_file, output_model_filename, "w");
  #else
  output_model_file = fopen(output_model_filename, "w");
  #endif
  // output models
  fprintf(output_model_file, "%s", this->ModelsToString().c_str());
}

void GBDT::AddDataset(const Dataset* valid_data,
         const std::vector<const Metric*>& valid_metrics) {
  // for a validation dataset, we need its score and metric
  valid_score_updater_.push_back(new ScoreUpdater(valid_data));
  valid_metrics_.emplace_back();
  best_iter_.emplace_back();
  best_score_.emplace_back();
  for (const auto& metric : valid_metrics) {
    valid_metrics_.back().push_back(metric);
    best_iter_.back().push_back(0);
    best_score_.back().push_back(-1);
  }
}

void GBDT::Bagging(int iter) {
  // if need bagging
  if (out_of_bag_data_indices_ != nullptr && iter % gbdt_config_->bagging_freq == 0) {
    // if doesn't have query data
    if (train_data_->metadata().query_boundaries() == nullptr) {
      bag_data_cnt_ =
        static_cast<data_size_t>(gbdt_config_->bagging_fraction * num_data_);
      out_of_bag_data_cnt_ = num_data_ - bag_data_cnt_;
      data_size_t cur_left_cnt = 0;
      data_size_t cur_right_cnt = 0;
      // random bagging, minimal unit is one record
      for (data_size_t i = 0; i < num_data_; ++i) {
        double prob =
          (bag_data_cnt_ - cur_left_cnt) / static_cast<double>(num_data_ - i);
        if (random_.NextDouble() < prob) {
          bag_data_indices_[cur_left_cnt++] = i;
        } else {
          out_of_bag_data_indices_[cur_right_cnt++] = i;
        }
      }
    } else {
      // if have query data
      const data_size_t* query_boundaries = train_data_->metadata().query_boundaries();
      data_size_t num_query = train_data_->metadata().num_queries();
      data_size_t bag_query_cnt =
          static_cast<data_size_t>(num_query * gbdt_config_->bagging_fraction);
      data_size_t cur_left_query_cnt = 0;
      data_size_t cur_left_cnt = 0;
      data_size_t cur_right_cnt = 0;
      // random bagging, minimal unit is one query
      for (data_size_t i = 0; i < num_query; ++i) {
        double prob =
            (bag_query_cnt - cur_left_query_cnt) / static_cast<double>(num_query - i);
        if (random_.NextDouble() < prob) {
          for (data_size_t j = query_boundaries[i]; j < query_boundaries[i + 1]; ++j) {
            bag_data_indices_[cur_left_cnt++] = j;
          }
          cur_left_query_cnt++;
        } else {
          for (data_size_t j = query_boundaries[i]; j < query_boundaries[i + 1]; ++j) {
            out_of_bag_data_indices_[cur_right_cnt++] = j;
          }
        }
      }
      bag_data_cnt_ = cur_left_cnt;
      out_of_bag_data_cnt_ = num_data_ - bag_data_cnt_;
    }
    Log::Stdout("re-bagging, using %d data to train", bag_data_cnt_);
    // set bagging data to tree learner
    tree_learner_->SetBaggingData(bag_data_indices_, bag_data_cnt_);
  }
}

void GBDT::UpdateScoreOutOfBag(const Tree* tree) {
  // we need to predict out-of-bag socres of data for boosting
  if (out_of_bag_data_indices_ != nullptr) {
    train_score_updater_->
      AddScore(tree, out_of_bag_data_indices_, out_of_bag_data_cnt_);
  }
}

void GBDT::Train() {
  // training start time
  auto start_time = std::chrono::high_resolution_clock::now();
  for (int iter = 0; iter < gbdt_config_->num_iterations; ++iter) {
    // boosting first
    Boosting();
    // bagging logic
    Bagging(iter);
    // train a new tree
    Tree * new_tree = TrainOneTree();
    // if cannot learn a new tree, then stop
    if (new_tree->num_leaves() <= 1) {
      Log::Stdout("Cannot do any boosting for tree cannot split");
      break;
    }
    // shrinkage by learning rate
    new_tree->Shrinkage(gbdt_config_->learning_rate);
    // update score
    UpdateScore(new_tree);
    UpdateScoreOutOfBag(new_tree);
    // print message for metric
    bool is_early_stopping = OutputMetric(iter + 1);
    // add model
    models_.push_back(new_tree);
    // save model to file per iteration
    if (early_stopping_round_ > 0){
        // if use early stopping, save previous model at (iter - early_stopping_round_) iteration
        if (iter >= early_stopping_round_){
            fprintf(output_model_file, "Tree=%d\n", iter - early_stopping_round_);
            Tree * printing_tree = models_.at(iter - early_stopping_round_);
            fprintf(output_model_file, "%s\n", printing_tree->ToString().c_str());
            fflush(output_model_file);
        }
    }
    else{
        fprintf(output_model_file, "Tree=%d\n", iter);
        fprintf(output_model_file, "%s\n", new_tree->ToString().c_str());
        fflush(output_model_file);
    }
    auto end_time = std::chrono::high_resolution_clock::now();
    // output used time per iteration
    Log::Stdout("%f seconds elapsed, finished %d iteration", std::chrono::duration<double,
                                     std::milli>(end_time - start_time) * 1e-3, iter + 1);
    if (is_early_stopping) {
        // close file with an early-stopping message
        Log::Stdout("early stopping at iteration %d, the best iteration round is %d", iter + 1, iter + 1 - early_stopping_round_);
        fclose(output_model_file);
        return;
    }
  }
  // close file
  if (early_stopping_round_ > 0) {
      // save remaining models
      for (int iter = gbdt_config_->num_iterations - early_stopping_round_; iter < static_cast<int>(models_.size()); ++iter){
        fprintf(output_model_file, "Tree=%d\n", iter);
        fprintf(output_model_file, "%s\n", models_.at(iter)->ToString().c_str());
      }
      fflush(output_model_file);
  }
  fclose(output_model_file);
}

Tree* GBDT::TrainOneTree() {
  return tree_learner_->Train(gradients_, hessians_);
}

void GBDT::UpdateScore(const Tree* tree) {
  // update training score
  train_score_updater_->AddScore(tree_learner_);
  // update validation score
  for (auto& score_tracker : valid_score_updater_) {
    score_tracker->AddScore(tree);
  }
}

bool GBDT::OutputMetric(int iter) {
  bool ret = false;
  // print training metric
  for (auto& sub_metric : training_metrics_) {
    sub_metric->PrintAndGetLoss(iter, train_score_updater_->score());
  }
  // print validation metric
  for (size_t i = 0; i < valid_metrics_.size(); ++i) {
    for (size_t j = 0; j < valid_metrics_[i].size(); ++j) {
      score_t test_score_ = valid_metrics_[i][j]->PrintAndGetLoss(iter, valid_score_updater_[i]->score());
      if (!ret && early_stopping_round_ > 0){
        bool the_bigger_the_better_ = valid_metrics_[i][j]->the_bigger_the_better;
        if (best_score_[i][j] < 0
            || (!the_bigger_the_better_ && test_score_ < best_score_[i][j])
            || ( the_bigger_the_better_ && test_score_ > best_score_[i][j])){
            best_score_[i][j] = test_score_;
            best_iter_[i][j] = iter;
        }
        else {
          if (iter - best_iter_[i][j] >= early_stopping_round_) ret = true;
        }
      }
    }
  }
  return ret;
}

void GBDT::Boosting() {
  // objective function will calculate gradients and hessians
  object_function_->
    GetGradients(train_score_updater_->score(), gradients_, hessians_);
}

std::string GBDT::ModelsToString() const {
  // serialize this object to string
  std::stringstream ss;
  // output max_feature_idx
  ss << "max_feature_idx=" << max_feature_idx_ << std::endl;
  // output sigmoid parameter
  ss << "sigmoid=" << object_function_->GetSigmoid() << std::endl;
  ss << std::endl;

  // output tree models
  for (size_t i = 0; i < models_.size(); ++i) {
    ss << "Tree=" << i << std::endl;
    ss << models_[i]->ToString() << std::endl;
  }
  return ss.str();
}

void GBDT::ModelsFromString(const std::string& model_str, int num_used_model) {
  // use serialized string to restore this object
  models_.clear();
  std::vector<std::string> lines = Common::Split(model_str.c_str(), '\n');
  size_t i = 0;
  // get max_feature_idx first
  while (i < lines.size()) {
    size_t find_pos = lines[i].find("max_feature_idx=");
    if (find_pos != std::string::npos) {
      std::vector<std::string> strs = Common::Split(lines[i].c_str(), '=');
      Common::Atoi(strs[1].c_str(), &max_feature_idx_);
      ++i;
      break;
    } else {
      ++i;
    }
  }
  if (i == lines.size()) {
    Log::Stderr("The model doesn't contain max_feature_idx");
    return;
  }
  // get sigmoid parameter
  i = 0;
  while (i < lines.size()) {
    size_t find_pos = lines[i].find("sigmoid=");
    if (find_pos != std::string::npos) {
      std::vector<std::string> strs = Common::Split(lines[i].c_str(), '=');
      Common::Atof(strs[1].c_str(), &sigmoid_);
      ++i;
      break;
    } else {
      ++i;
    }
  }
  // if sigmoid doesn't exists
  if (i == lines.size()) {
    sigmoid_ = -1.0;
  }
  // get tree models
  i = 0;
  while (i < lines.size()) {
    size_t find_pos = lines[i].find("Tree=");
    if (find_pos != std::string::npos) {
      ++i;
      int start = static_cast<int>(i);
      while (i < lines.size() && lines[i].find("Tree=") == std::string::npos) { ++i; }
      int end = static_cast<int>(i);
      std::string tree_str = Common::Join(lines, start, end, '\n');
      models_.push_back(new Tree(tree_str));
      if (num_used_model > 0 && models_.size() >= static_cast<size_t>(num_used_model)) {
        break;
      }
    } else {
      ++i;
    }
  }

  Log::Stdout("Loaded %d models\n", models_.size());
}

double GBDT::PredictRaw(const double* value) const {
  double ret = 0.0;
  for (size_t i = 0; i < models_.size(); ++i) {
    ret += models_[i]->Predict(value);
  }
  return ret;
}

double GBDT::Predict(const double* value) const {
  double ret = 0.0;
  for (size_t i = 0; i < models_.size(); ++i) {
    ret += models_[i]->Predict(value);
  }
  // if need sigmoid transform
  if (sigmoid_ > 0) {
    ret = 1.0 / (1.0 + std::exp(- 2.0f * sigmoid_ * ret));
  }
  return ret;
}

}  // namespace LightGBM
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestSurfacePlot.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/

#include "vtkChartXYZ.h"
#include "vtkContextMouseEvent.h"
#include "vtkContextView.h"
#include "vtkContextScene.h"
#include "vtkFloatArray.h"
#include "vtkNew.h"
#include "vtkPlotSurface.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTable.h"
#include "vtkRegressionTestImage.h"
#include "vtkUnsignedCharArray.h"
#include "vtkVector.h"

int TestSurfacePlot(int , char * [])
{
  vtkNew<vtkChartXYZ> chart;
  vtkNew<vtkPlotSurface> plot;
  vtkNew<vtkContextView> view;
  view->GetRenderWindow()->SetSize(400, 300);
  view->GetScene()->AddItem(chart.GetPointer());

  chart->SetGeometry(vtkRectf(75.0, 20.0, 250, 260));

  // Create a surface
  vtkNew<vtkTable> table;
  float numPoints = 70;
  float inc = 9.424778 / (numPoints - 1);
  for (float i = 0; i < numPoints; ++i)
    {
    vtkNew<vtkFloatArray> arr;
    table->AddColumn(arr.GetPointer());
    }
  table->SetNumberOfRows(numPoints);
  for (float i = 0; i < numPoints; ++i)
    {
    float x = i * inc;
    for (float j = 0; j < numPoints; ++j)
      {
      float y  = j * inc;
      table->SetValue(i, j, sin(sqrt(x*x + y*y)));
      }
    }

  // Set up the surface plot we wish to visualize and add it to the chart.
  plot->SetXRange(0, 9.424778);
  plot->SetYRange(0, 9.424778);
  plot->SetInputData(table.GetPointer());
  chart->AddPlot(plot.GetPointer());

  view->GetRenderWindow()->SetMultiSamples(0);
  view->GetInteractor()->Initialize();
  view->GetRenderWindow()->Render();

  // rotate
  vtkContextMouseEvent mouseEvent;
  mouseEvent.SetInteractor(view->GetInteractor());
  vtkVector2i pos;
  vtkVector2i lastPos;

  mouseEvent.SetButton(vtkContextMouseEvent::LEFT_BUTTON);
  lastPos.Set(100, 50);
  mouseEvent.SetLastScreenPos(lastPos);
  pos.Set(150, 100);
  mouseEvent.SetScreenPos(pos);
  vtkVector2d sP(pos.Cast<double>().GetData());
  vtkVector2d lSP(lastPos.Cast<double>().GetData());
  vtkVector2d screenPos(mouseEvent.GetScreenPos().Cast<double>().GetData());
  vtkVector2d lastScreenPos(mouseEvent.GetLastScreenPos().Cast<double>().GetData());
  chart->MouseMoveEvent(mouseEvent);

  view->GetInteractor()->Start();

  return EXIT_SUCCESS;
}
<commit_msg>TestSurfacePlot: loop using vtkIdType<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestSurfacePlot.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/

#include "vtkChartXYZ.h"
#include "vtkContextMouseEvent.h"
#include "vtkContextView.h"
#include "vtkContextScene.h"
#include "vtkFloatArray.h"
#include "vtkNew.h"
#include "vtkPlotSurface.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTable.h"
#include "vtkRegressionTestImage.h"
#include "vtkUnsignedCharArray.h"
#include "vtkVector.h"

int TestSurfacePlot(int , char * [])
{
  vtkNew<vtkChartXYZ> chart;
  vtkNew<vtkPlotSurface> plot;
  vtkNew<vtkContextView> view;
  view->GetRenderWindow()->SetSize(400, 300);
  view->GetScene()->AddItem(chart.GetPointer());

  chart->SetGeometry(vtkRectf(75.0, 20.0, 250, 260));

  // Create a surface
  vtkNew<vtkTable> table;
  vtkIdType numPoints = 70;
  float inc = 9.424778 / (numPoints - 1);
  for (vtkIdType i = 0; i < numPoints; ++i)
    {
    vtkNew<vtkFloatArray> arr;
    table->AddColumn(arr.GetPointer());
    }
  table->SetNumberOfRows(numPoints);
  for (vtkIdType i = 0; i < numPoints; ++i)
    {
    float x = i * inc;
    for (vtkIdType j = 0; j < numPoints; ++j)
      {
      float y  = j * inc;
      table->SetValue(i, j, sin(sqrt(x*x + y*y)));
      }
    }

  // Set up the surface plot we wish to visualize and add it to the chart.
  plot->SetXRange(0, 9.424778);
  plot->SetYRange(0, 9.424778);
  plot->SetInputData(table.GetPointer());
  chart->AddPlot(plot.GetPointer());

  view->GetRenderWindow()->SetMultiSamples(0);
  view->GetInteractor()->Initialize();
  view->GetRenderWindow()->Render();

  // rotate
  vtkContextMouseEvent mouseEvent;
  mouseEvent.SetInteractor(view->GetInteractor());
  vtkVector2i pos;
  vtkVector2i lastPos;

  mouseEvent.SetButton(vtkContextMouseEvent::LEFT_BUTTON);
  lastPos.Set(100, 50);
  mouseEvent.SetLastScreenPos(lastPos);
  pos.Set(150, 100);
  mouseEvent.SetScreenPos(pos);
  vtkVector2d sP(pos.Cast<double>().GetData());
  vtkVector2d lSP(lastPos.Cast<double>().GetData());
  vtkVector2d screenPos(mouseEvent.GetScreenPos().Cast<double>().GetData());
  vtkVector2d lastScreenPos(mouseEvent.GetLastScreenPos().Cast<double>().GetData());
  chart->MouseMoveEvent(mouseEvent);

  view->GetInteractor()->Start();

  return EXIT_SUCCESS;
}
<|endoftext|>


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

  Program:   Monteverdi2
  Language:  C++

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

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

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

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

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "Core/mvdStackedLayerModel.h"
#include "Gui/mvdLayerStackItemModel.h"
#include "Gui/mvdLayerStackWidget.h"

namespace mvd
{
/*
  TRANSLATOR mvd::LayerStackController

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

namespace
{
} // end of anonymous namespace.

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
LayerStackController
::LayerStackController( LayerStackWidget * widget, QObject * parent ) :
  AbstractModelController( widget, parent )
{
}

/*******************************************************************************/
LayerStackController
::~LayerStackController()
{
}

/*******************************************************************************/
void
LayerStackController
::ClearWidget()
{
}

/*******************************************************************************/
void
LayerStackController
::Connect( AbstractModel * model )
{
  assert( model==qobject_cast< StackedLayerModel * >( model ) );

  QObject::connect(
    model,
    SIGNAL( CurrentChanged( size_t ) ),
    // to:
    this,
    SLOT( OnStackedLayerCurrentChanged( size_t ) )
  );

  QObject::connect(
    model,
    SIGNAL( ContentChanged() ),
    // to:
    this,
    SLOT( UpdateProjectionMode() )
  );

  QObject::connect(
    model,
    SIGNAL( ContentReset() ),
    // to:
    this,
    SLOT( UpdateProjectionMode() )
  );

  LayerStackWidget * widget = GetWidget< LayerStackWidget >();
  assert( widget!=NULL );

  assert( widget->GetItemModel()!=NULL );

  widget->GetItemModel()->SetStack(
    qobject_cast< StackedLayerModel * >( model )
  );

  QObject::connect(
    widget,
    SIGNAL( SelectionChanged( int ) ),
    // to:
    this,
    SLOT( OnSelectionChanged( int ) )
  );

  QObject::connect(
    widget,
    SIGNAL( ProjectionButtonClicked() ),
    // to:
    this,
    SLOT( OnProjectionButtonClicked() )
  );

  QObject::connect(
    widget,
    SIGNAL( TopButtonClicked() ),
    // to:
    model,
    SLOT( MoveCurrentToTop() )
  );

  QObject::connect(
    widget,
    SIGNAL( BottomButtonClicked() ),
    // to:
    model,
    SLOT( MoveCurrentToBottom() )
  );

  QObject::connect(
    widget,
    SIGNAL( UpButtonClicked() ),
    // to:
    model,
    SLOT( RaiseCurrent() )
  );

  QObject::connect(
    widget,
    SIGNAL( DownButtonClicked() ),
    // to:
    model,
    SLOT( LowerCurrent() )
  );

  QObject::connect(
    widget,
    SIGNAL( DeleteButtonClicked() ),
    // to:
    model,
    SLOT( DeleteCurrent() )
  );
}

/*******************************************************************************/
void
LayerStackController
::Disconnect( AbstractModel * model )
{
  // assert( model==qobject_cast< StackedLayerModel * >( model ) );

  QObject::disconnect(
    model,
    SIGNAL( CurrentChanged( size_t ) ),
    // from:
    this,
    SLOT( OnStackedLayerCurrentChanged( size_t ) )
  );

  QObject::disconnect(
    model,
    SIGNAL( ContentChanged() ),
    // from:
    this,
    SLOT( UpdateProjectionMode() )
  );

  QObject::disconnect(
    model,
    SIGNAL( ContentReset() ),
    // from:
    this,
    SLOT( UpdateProjectionMode() )
  );

  LayerStackWidget * widget = GetWidget< LayerStackWidget >();
  assert( widget!=NULL );

  assert( widget->GetItemModel()!=NULL );

  widget->GetItemModel()->SetStack( NULL );

  QObject::disconnect(
    widget,
    SIGNAL( SelectionChanged( int ) ),
    // from:
    this,
    SLOT( OnSelectionChanged( int ) )
  );

  QObject::disconnect(
    widget,
    SIGNAL( ProjectionButtonClicked() ),
    // from:
    this,
    SLOT( OnProjectionButtonClicked() )
  );

  QObject::disconnect(
    widget,
    SIGNAL( TopButtonClicked() ),
    // from:
    model,
    SLOT( MoveCurrentToTop() )
  );

  QObject::disconnect(
    widget,
    SIGNAL( BottomButtonClicked() ),
    // from:
    model,
    SLOT( MoveCurrentToBottom() )
  );

  QObject::disconnect(
    widget,
    SIGNAL( UpButtonClicked() ),
    // from:
    model,
    SLOT( RaiseCurrent() )
  );

  QObject::disconnect(
    widget,
    SIGNAL( DownButtonClicked() ),
    // from:
    model,
    SLOT( LowerCurrent() )
  );

  QObject::disconnect(
    widget,
    SIGNAL( DeleteButtonClicked() ),
    // from:
    model,
    SLOT( DeleteCurrent() )
  );
}

/*******************************************************************************/
void
LayerStackController
::virtual_ResetWidget()
{
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/
void
LayerStackController
::OnCurrentChanged( int index )
{
  // qDebug() << this << "::OnCurrentChanged(" << index << ")";

  assert( GetModel()==GetModel< StackedLayerModel >() );
  StackedLayerModel * model = GetModel< StackedLayerModel >();
  assert( model!=NULL );

  model->SetCurrent( index );
}

/*******************************************************************************/
void
LayerStackController
::OnProjectionButtonClicked()
{
  qDebug() << this << "::OnProjectionButtonClicked()";

  assert( GetModel()==GetModel< StackedLayerModel >() );
  StackedLayerModel * model = GetModel< StackedLayerModel >();
  assert( model!=NULL );

  model->SetReference( model->GetCurrentIndex() );
}

/*******************************************************************************/
void
LayerStackController
::OnSelectionChanged( int index )
{
  // qDebug() << this << "::OnSelectionChanged(" << index << ")";

  assert( GetModel()==GetModel< StackedLayerModel >() );
  StackedLayerModel * model = GetModel< StackedLayerModel >();
  assert( model!=NULL );

  model->SetCurrent( index );
}

/*******************************************************************************/
void
LayerStackController
::OnStackedLayerCurrentChanged( size_t index )
{
  // qDebug() << this << "::OnStackedLayerCurrentChanged(" << index << ")";

  LayerStackWidget * widget = GetWidget< LayerStackWidget >();
  assert( widget!=NULL );

  assert( widget->GetItemModel()!=NULL );

  bool signalsBlocked = widget->blockSignals( true );
  {
  widget->SetCurrent( index );
  }
  widget->blockSignals( signalsBlocked );
}

/*******************************************************************************/
void
LayerStackController
::UpdateProjectionMode()
{
  assert( GetModel()==GetModel< StackedLayerModel >() );
  StackedLayerModel * model = GetModel< StackedLayerModel >();
  assert( model!=NULL );

  size_t unk = 0;
  size_t gcs = 0;

  model->CountSRT( unk, gcs, gcs, gcs );

  assert( GetWidget()==GetWidget< LayerStackWidget >() );
  LayerStackWidget * widget = GetWidget< LayerStackWidget >();
  assert( widget!=NULL );

  widget->SetProjectionEnabled( unk==0 );
}

} // end namespace 'mvd'
<commit_msg>REFAC: Disabled debug trace.<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

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

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

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

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

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "Core/mvdStackedLayerModel.h"
#include "Gui/mvdLayerStackItemModel.h"
#include "Gui/mvdLayerStackWidget.h"

namespace mvd
{
/*
  TRANSLATOR mvd::LayerStackController

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CONSTANTS                                                                 */

namespace
{
} // end of anonymous namespace.

/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION                                             */

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
LayerStackController
::LayerStackController( LayerStackWidget * widget, QObject * parent ) :
  AbstractModelController( widget, parent )
{
}

/*******************************************************************************/
LayerStackController
::~LayerStackController()
{
}

/*******************************************************************************/
void
LayerStackController
::ClearWidget()
{
}

/*******************************************************************************/
void
LayerStackController
::Connect( AbstractModel * model )
{
  assert( model==qobject_cast< StackedLayerModel * >( model ) );

  QObject::connect(
    model,
    SIGNAL( CurrentChanged( size_t ) ),
    // to:
    this,
    SLOT( OnStackedLayerCurrentChanged( size_t ) )
  );

  QObject::connect(
    model,
    SIGNAL( ContentChanged() ),
    // to:
    this,
    SLOT( UpdateProjectionMode() )
  );

  QObject::connect(
    model,
    SIGNAL( ContentReset() ),
    // to:
    this,
    SLOT( UpdateProjectionMode() )
  );

  LayerStackWidget * widget = GetWidget< LayerStackWidget >();
  assert( widget!=NULL );

  assert( widget->GetItemModel()!=NULL );

  widget->GetItemModel()->SetStack(
    qobject_cast< StackedLayerModel * >( model )
  );

  QObject::connect(
    widget,
    SIGNAL( SelectionChanged( int ) ),
    // to:
    this,
    SLOT( OnSelectionChanged( int ) )
  );

  QObject::connect(
    widget,
    SIGNAL( ProjectionButtonClicked() ),
    // to:
    this,
    SLOT( OnProjectionButtonClicked() )
  );

  QObject::connect(
    widget,
    SIGNAL( TopButtonClicked() ),
    // to:
    model,
    SLOT( MoveCurrentToTop() )
  );

  QObject::connect(
    widget,
    SIGNAL( BottomButtonClicked() ),
    // to:
    model,
    SLOT( MoveCurrentToBottom() )
  );

  QObject::connect(
    widget,
    SIGNAL( UpButtonClicked() ),
    // to:
    model,
    SLOT( RaiseCurrent() )
  );

  QObject::connect(
    widget,
    SIGNAL( DownButtonClicked() ),
    // to:
    model,
    SLOT( LowerCurrent() )
  );

  QObject::connect(
    widget,
    SIGNAL( DeleteButtonClicked() ),
    // to:
    model,
    SLOT( DeleteCurrent() )
  );
}

/*******************************************************************************/
void
LayerStackController
::Disconnect( AbstractModel * model )
{
  // assert( model==qobject_cast< StackedLayerModel * >( model ) );

  QObject::disconnect(
    model,
    SIGNAL( CurrentChanged( size_t ) ),
    // from:
    this,
    SLOT( OnStackedLayerCurrentChanged( size_t ) )
  );

  QObject::disconnect(
    model,
    SIGNAL( ContentChanged() ),
    // from:
    this,
    SLOT( UpdateProjectionMode() )
  );

  QObject::disconnect(
    model,
    SIGNAL( ContentReset() ),
    // from:
    this,
    SLOT( UpdateProjectionMode() )
  );

  LayerStackWidget * widget = GetWidget< LayerStackWidget >();
  assert( widget!=NULL );

  assert( widget->GetItemModel()!=NULL );

  widget->GetItemModel()->SetStack( NULL );

  QObject::disconnect(
    widget,
    SIGNAL( SelectionChanged( int ) ),
    // from:
    this,
    SLOT( OnSelectionChanged( int ) )
  );

  QObject::disconnect(
    widget,
    SIGNAL( ProjectionButtonClicked() ),
    // from:
    this,
    SLOT( OnProjectionButtonClicked() )
  );

  QObject::disconnect(
    widget,
    SIGNAL( TopButtonClicked() ),
    // from:
    model,
    SLOT( MoveCurrentToTop() )
  );

  QObject::disconnect(
    widget,
    SIGNAL( BottomButtonClicked() ),
    // from:
    model,
    SLOT( MoveCurrentToBottom() )
  );

  QObject::disconnect(
    widget,
    SIGNAL( UpButtonClicked() ),
    // from:
    model,
    SLOT( RaiseCurrent() )
  );

  QObject::disconnect(
    widget,
    SIGNAL( DownButtonClicked() ),
    // from:
    model,
    SLOT( LowerCurrent() )
  );

  QObject::disconnect(
    widget,
    SIGNAL( DeleteButtonClicked() ),
    // from:
    model,
    SLOT( DeleteCurrent() )
  );
}

/*******************************************************************************/
void
LayerStackController
::virtual_ResetWidget()
{
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/
void
LayerStackController
::OnCurrentChanged( int index )
{
  // qDebug() << this << "::OnCurrentChanged(" << index << ")";

  assert( GetModel()==GetModel< StackedLayerModel >() );
  StackedLayerModel * model = GetModel< StackedLayerModel >();
  assert( model!=NULL );

  model->SetCurrent( index );
}

/*******************************************************************************/
void
LayerStackController
::OnProjectionButtonClicked()
{
  // qDebug() << this << "::OnProjectionButtonClicked()";

  assert( GetModel()==GetModel< StackedLayerModel >() );
  StackedLayerModel * model = GetModel< StackedLayerModel >();
  assert( model!=NULL );

  model->SetReference( model->GetCurrentIndex() );
}

/*******************************************************************************/
void
LayerStackController
::OnSelectionChanged( int index )
{
  // qDebug() << this << "::OnSelectionChanged(" << index << ")";

  assert( GetModel()==GetModel< StackedLayerModel >() );
  StackedLayerModel * model = GetModel< StackedLayerModel >();
  assert( model!=NULL );

  model->SetCurrent( index );
}

/*******************************************************************************/
void
LayerStackController
::OnStackedLayerCurrentChanged( size_t index )
{
  // qDebug() << this << "::OnStackedLayerCurrentChanged(" << index << ")";

  LayerStackWidget * widget = GetWidget< LayerStackWidget >();
  assert( widget!=NULL );

  assert( widget->GetItemModel()!=NULL );

  bool signalsBlocked = widget->blockSignals( true );
  {
  widget->SetCurrent( index );
  }
  widget->blockSignals( signalsBlocked );
}

/*******************************************************************************/
void
LayerStackController
::UpdateProjectionMode()
{
  assert( GetModel()==GetModel< StackedLayerModel >() );
  StackedLayerModel * model = GetModel< StackedLayerModel >();
  assert( model!=NULL );

  size_t unk = 0;
  size_t gcs = 0;

  model->CountSRT( unk, gcs, gcs, gcs );

  assert( GetWidget()==GetWidget< LayerStackWidget >() );
  LayerStackWidget * widget = GetWidget< LayerStackWidget >();
  assert( widget!=NULL );

  widget->SetProjectionEnabled( unk==0 );
}

} // end namespace 'mvd'
<|endoftext|>


<commit_before>/* This pass is meant to show how one uses the Knowledge Construction Engine
 * (KCE). It's pretty simple. Running this pass requires a lot more work and
 * I'm...heh....working on that.
 * - Joshua Scoggins (8/12/2012)
 */
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/DenseSet.h"
#include "LLVMWrapper.h"
#include "JSEdgeRemoval.h"
#include "PassDependencies.h"
#include "EnvironmentCreationPass.h"
#include "KnowledgeConstructionPass.h"
extern "C" {
#include "clips.h"
}

using namespace llvm;
char nilObject[41] = "(nil of ConstantPointerNull (Pointer 0))";
namespace llvm {
   struct WavefrontScheduling : public FunctionPass {
      static char ID;
      public:
      WavefrontScheduling() : FunctionPass(ID) {
      }
      virtual void getAnalysisUsage(AnalysisUsage &Info) const {
			Info.addRequiredTransitive<KnowledgeConstruction>();
			Info.addRequired<EnvironmentConstruction>();
			Info.addRequired<JSEdgeRemoval>();
      }
      virtual bool runOnFunction(Function& fn) {
         //do not actually wavefront schedule if we only have one block
         if(fn.size() > 1) {
				KnowledgeConstruction &kc = getAnalysis<KnowledgeConstruction>();
				EnvironmentConstruction &env = getAnalysis<EnvironmentConstruction>();
				env.batchStar("Init.clp");
				env.makeInstance(nilObject);
				env.makeInstances((char*)kc.getInstancesAsString().c_str());
				env.reset();
				env.run(-1L);
            return true;
         } else {
            return false;
         }
      }
   };
}
char WavefrontScheduling::ID = 0;
//for opt
static RegisterPass<WavefrontScheduling> wave("wavefront", "Wavefront Scheduling", false, false);
INITIALIZE_PASS_BEGIN(WavefrontScheduling, "wavefront", "Wavefront Scheduling", false, false)
INITIALIZE_PASS_DEPENDENCY(KnowledgeConstruction)
INITIALIZE_PASS_DEPENDENCY(EnvironmentConstruction)
INITIALIZE_PASS_DEPENDENCY(JSEdgeRemoval)
INITIALIZE_PASS_END(WavefrontScheduling, "wavefront", "Wavefront Scheduling", false, false)
<commit_msg>Modified WavefrontScheduling to use the new object layout<commit_after>/* This pass is meant to show how one uses the Knowledge Construction Engine
 * (KCE). It's pretty simple. Running this pass requires a lot more work and
 * I'm...heh....working on that.
 * - Joshua Scoggins (8/12/2012)
 */
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/DenseSet.h"
#include "LLVMWrapper.h"
#include "JSEdgeRemoval.h"
#include "PassDependencies.h"
#include "EnvironmentCreationPass.h"
#include "KnowledgeConstructionPass.h"
extern "C" {
#include "clips.h"
}

using namespace llvm;
char nilObject[41] = "(nil of ConstantPointerNull (Pointer 0))";
namespace llvm {
   struct WavefrontScheduling : public FunctionPass {
      static char ID;
      public:
      WavefrontScheduling() : FunctionPass(ID) {
      }
      virtual void getAnalysisUsage(AnalysisUsage &Info) const {
			Info.addRequired<LoopInfo>();
			Info.addRequired<RegionInfo>();
			Info.addRequired<JSEdgeRemoval>();
      }
      virtual bool runOnFunction(Function& fn) {
         //do not actually wavefront schedule if we only have one block
         if(fn.size() > 1) {

				RegionInfo &ri = getAnalysis<RegionInfo>();
				LoopInfo &li = getAnalysis<LoopInfo>();
				KnowledgeConstruction kc;
				EnvironmentConstruction env;
				kc.route(fn, li, ri);
				env.batchStar("Init.clp");
				env.makeInstance(nilObject);
				env.makeInstances((char*)kc.getInstancesAsString().c_str());
				env.reset();
				env.run(-1L);
            return true;
         } else {
            return false;
         }
      }
   };
}
char WavefrontScheduling::ID = 0;
//for opt
static RegisterPass<WavefrontScheduling> wave("wavefront", "Wavefront Scheduling", false, false);
INITIALIZE_PASS_BEGIN(WavefrontScheduling, "wavefront", "Wavefront Scheduling", false, false)
INITIALIZE_PASS_DEPENDENCY(JSEdgeRemoval)
INITIALIZE_PASS_END(WavefrontScheduling, "wavefront", "Wavefront Scheduling", false, false)
<|endoftext|>


<commit_before>// GTest & unit test Headers
#include <gtest/gtest.h>
#include "MainUnitTestC.h"

// STL Headers`
#include <map>
#include <string>

// MAMA Headers
#include "mama/middleware.h"
#include "mama/msg.h"

class MamaEnumTestsC : public ::testing::Test
{
protected:
   MamaEnumTestsC();
   virtual ~MamaEnumTestsC();

   virtual void SetUp(void);

   virtual void TearDown(void);

   typedef std::pair <mamaPayloadType, std::string> MamaPayloadPair;
   typedef std::map  <mamaPayloadType, std::string> MamaPayloadMapType;

   typedef std::pair <mamaMiddleware,  std::string> MamaMiddlewarePair;
   typedef std::map  <mamaMiddleware,  std::string> MamaMiddlewareMapType;

   MamaPayloadMapType     payloadTestData;
   MamaMiddlewareMapType  middlewareTestData;

private:
   void CreateTestData();

};

MamaEnumTestsC::MamaEnumTestsC() : testing::Test()
{
   CreateTestData();
}

MamaEnumTestsC::~MamaEnumTestsC() {}

void
MamaEnumTestsC::SetUp()
{
}

void
MamaEnumTestsC::TearDown()
{
}

void
MamaEnumTestsC::CreateTestData()
{
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_V5,         "V5"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_AVIS,       "AVIS"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_TICK42BLP,  "TICK42BLP"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_FAST,       "FAST"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_RAI,        "rai"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_UMS,        "UMS"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_TICK42BLP,  "TICK42RMDS"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_QPID,       "QPID"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_TIBRV,      "TIBRV"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_IBMWFO,     "ibmwfo"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_ACTIV,      "activ"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_VULCAN,     "Vulcan"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_WOMBAT_MSG, "WombatMsg"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_EXEGY,      "EXEGY"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_UNKNOWN,    "unknown"));

    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_WMW,       "wmw"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_LBM,       "lbm"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_TIBRV,     "tibrv"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_AVIS,      "AVIS"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_TICK42BLP, "tick42blp"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_SOLACE,    "SOLACE"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_RAI,       "rai"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_QPID,      "QPID"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_EXEGY,     "exegy"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_IBMWFO,    "ibmwfo"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_ACTIV,     "activ"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_TICK42RMDS, "tick42rmds"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_UMS,       "ums"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_VULCAN,    "vulcan"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_UNKNOWN,   "unknown"));
}

TEST_F (MamaEnumTestsC, testPayloadConvertToString)
{
    MamaPayloadMapType::iterator itr;
    bool passed = true;

    for(itr = payloadTestData.begin(); itr != payloadTestData.end(); ++itr) {

       mamaPayloadType payload   = (*itr).first;
       std::string     expected  = (*itr).second;

       std::string actual = mamaPayload_convertToString (payload);

       EXPECT_STREQ(actual.c_str(), expected.c_str());

       if (actual != expected)
           passed = false;
    }

    ASSERT_EQ( passed, true );
}

TEST_F (MamaEnumTestsC, testMiddlewareConvertToString)
{
    MamaMiddlewareMapType::iterator itr;
    bool passed = true;

    for(itr = middlewareTestData.begin(); itr != middlewareTestData.end(); ++itr) {

       mamaMiddleware middleware = (*itr).first;
       std::string    expected   = (*itr).second;

       std::string actual = mamaMiddleware_convertToString (middleware);

       EXPECT_STREQ(actual.c_str(), expected.c_str());

       if (actual != expected)
           passed = false;
    }

    ASSERT_EQ (passed, true);
}

TEST_F (MamaEnumTestsC, testMiddlewareConvertFromString)
{
    MamaMiddlewareMapType::iterator itr;
    bool passed = true;

    for (itr = middlewareTestData.begin(); itr != middlewareTestData.end(); itr++) {

        mamaMiddleware expected    = (*itr).first;
        std::string    middleware  = (*itr).second;

        mamaMiddleware actual      = mamaMiddleware_convertFromString (middleware.c_str());

        EXPECT_EQ (actual, expected);

        if (actual != expected)
            passed = false;
    }

    ASSERT_EQ (passed, true);
}
<commit_msg>UNIT TESTS: Fix issue with payload ID test.<commit_after>// GTest & unit test Headers
#include <gtest/gtest.h>
#include "MainUnitTestC.h"

// STL Headers`
#include <map>
#include <string>

// MAMA Headers
#include "mama/middleware.h"
#include "mama/msg.h"

class MamaEnumTestsC : public ::testing::Test
{
protected:
   MamaEnumTestsC();
   virtual ~MamaEnumTestsC();

   virtual void SetUp(void);

   virtual void TearDown(void);

   typedef std::pair <mamaPayloadType, std::string> MamaPayloadPair;
   typedef std::map  <mamaPayloadType, std::string> MamaPayloadMapType;

   typedef std::pair <mamaMiddleware,  std::string> MamaMiddlewarePair;
   typedef std::map  <mamaMiddleware,  std::string> MamaMiddlewareMapType;

   MamaPayloadMapType     payloadTestData;
   MamaMiddlewareMapType  middlewareTestData;

private:
   void CreateTestData();

};

MamaEnumTestsC::MamaEnumTestsC() : testing::Test()
{
   CreateTestData();
}

MamaEnumTestsC::~MamaEnumTestsC() {}

void
MamaEnumTestsC::SetUp()
{
}

void
MamaEnumTestsC::TearDown()
{
}

void
MamaEnumTestsC::CreateTestData()
{
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_V5,         "V5"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_AVIS,       "AVIS"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_TICK42BLP,  "TICK42BLP"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_FAST,       "FAST"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_RAI,        "rai"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_UMS,        "UMS"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_TICK42RMDS, "TICK42RMDS"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_QPID,       "QPID"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_TIBRV,      "TIBRV"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_IBMWFO,     "ibmwfo"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_ACTIV,      "activ"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_VULCAN,     "Vulcan"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_WOMBAT_MSG, "WombatMsg"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_EXEGY,      "EXEGY"));
    payloadTestData.insert (MamaPayloadPair (MAMA_PAYLOAD_UNKNOWN,    "unknown"));

    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_WMW,       "wmw"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_LBM,       "lbm"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_TIBRV,     "tibrv"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_AVIS,      "AVIS"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_TICK42BLP, "tick42blp"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_SOLACE,    "SOLACE"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_RAI,       "rai"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_QPID,      "QPID"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_EXEGY,     "exegy"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_IBMWFO,    "ibmwfo"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_ACTIV,     "activ"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_TICK42RMDS, "tick42rmds"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_UMS,       "ums"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_VULCAN,    "vulcan"));
    middlewareTestData.insert (MamaMiddlewarePair (MAMA_MIDDLEWARE_UNKNOWN,   "unknown"));
}

TEST_F (MamaEnumTestsC, testPayloadConvertToString)
{
    MamaPayloadMapType::iterator itr;
    bool passed = true;

    for(itr = payloadTestData.begin(); itr != payloadTestData.end(); ++itr) {

       mamaPayloadType payload   = (*itr).first;
       std::string     expected  = (*itr).second;

       std::string actual = mamaPayload_convertToString (payload);

       EXPECT_STREQ(actual.c_str(), expected.c_str());

       if (actual != expected)
           passed = false;
    }

    ASSERT_EQ( passed, true );
}

TEST_F (MamaEnumTestsC, testMiddlewareConvertToString)
{
    MamaMiddlewareMapType::iterator itr;
    bool passed = true;

    for(itr = middlewareTestData.begin(); itr != middlewareTestData.end(); ++itr) {

       mamaMiddleware middleware = (*itr).first;
       std::string    expected   = (*itr).second;

       std::string actual = mamaMiddleware_convertToString (middleware);

       EXPECT_STREQ(actual.c_str(), expected.c_str());

       if (actual != expected)
           passed = false;
    }

    ASSERT_EQ (passed, true);
}

TEST_F (MamaEnumTestsC, testMiddlewareConvertFromString)
{
    MamaMiddlewareMapType::iterator itr;
    bool passed = true;

    for (itr = middlewareTestData.begin(); itr != middlewareTestData.end(); itr++) {

        mamaMiddleware expected    = (*itr).first;
        std::string    middleware  = (*itr).second;

        mamaMiddleware actual      = mamaMiddleware_convertFromString (middleware.c_str());

        EXPECT_EQ (actual, expected);

        if (actual != expected)
            passed = false;
    }

    ASSERT_EQ (passed, true);
}
<|endoftext|>


<commit_before>#include <Common.hpp>
#include <Engine.hpp>
#include <Dispatch.hpp>
#include <MessageProcessor.hpp>

#include <chrono>
#include <functional>
#include <iostream>
#include <sstream>
#include <fstream>

#include <boost/regex.hpp>
#include <boost/thread/thread.hpp>

namespace K3 {

using std::cout;
using std::endl;
using std::bind;
using std::string;
using std::shared_ptr;

Address rendezvous;
Address sender;
std::chrono::system_clock::time_point start, end;

int nodeCounter(0);
int numSent(0);
int desired(0);
bool received_all(false);
bool sent_all(false);
string message;

// "Trigger" Declarations
void join(shared_ptr<Engine> engine, string message_contents) {
  Message m = Message(rendezvous, "register", message);
  engine->send(m);
}

void register2(shared_ptr<Engine> engine, string message_contents) {
  int n = 1;
  nodeCounter += n;
  std::cout << "Length" << message_contents.length() / (1024*1024.0) << "mB. Number:" << nodeCounter<< std::endl;
  if (nodeCounter == desired) {
    Message m = Message(sender, "finished", "()");
    engine->send(m);
    received_all = true;
  }

}
void finished(shared_ptr<Engine> engine, string message_contents) {
  sent_all = true;
  std::cout << "FINISHED!!!" << std::endl;
}

// MP setup
TriggerDispatch buildTable(shared_ptr<Engine> engine) {
  TriggerDispatch table = TriggerDispatch();
  table["join"] = bind(&K3::join, engine, std::placeholders::_1);
  table["register"] = bind(&K3::register2, engine, std::placeholders::_1);
  table["finished"] = bind(&K3::finished, engine, std::placeholders::_1);
  return table;
}

shared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) {
  auto table = buildTable(engine);
  shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table));
  return mp;
}

// Engine setup
shared_ptr<Engine> buildEngine(bool simulation, SystemEnvironment s_env) {
  // Configure engine components
  shared_ptr<InternalCodec> i_cdec = make_shared<LengthHeaderInternalCodec>(LengthHeaderInternalCodec());

  // Construct an engine
  Engine engine = Engine(simulation, s_env, i_cdec);
  return make_shared<Engine>(engine);
}

}

void runReceiver(int num_messages) {
  using boost::thread;
  using boost::thread_group;
  using std::shared_ptr;
  K3::nodeCounter = 0;

  // Create engines
  auto engine1 = K3::buildEngine(false, K3::defaultEnvironment(K3::rendezvous));
  // Create MPs
  auto mp1 = K3::buildMP(engine1);
  // Fork a thread for each engine
  auto service_threads = std::shared_ptr<thread_group>(new thread_group());
  shared_ptr<thread> t1 = engine1->forkEngine(mp1);
  service_threads->add_thread(t1.get());

  // Wait for completion
  while ((!K3::received_all)) {
   continue;
  }

  // Cleanup
  engine1->forceTerminateEngine();
  service_threads->join_all();
  service_threads->remove_thread(t1.get());
}

std::chrono::seconds runSender(int num_messages, int message_len) {
  using boost::thread;
  using boost::thread_group;
  using std::shared_ptr;

  // Build message
  K3::message = "";
  for (int i=0; i< message_len; i++) {
    K3::message += "a";
  }
  // Create engines
  auto engine2 = K3::buildEngine(false, K3::defaultEnvironment(K3::sender));
  // Create MPs
  auto mp2 = K3::buildMP(engine2);

  // Start timer
  K3::start = std::chrono::system_clock::now();

  // Fork a thread for each engine
  auto service_threads = std::shared_ptr<thread_group>(new thread_group());
  shared_ptr<thread> t1 = engine2->forkEngine(mp2);
  service_threads->add_thread(t1.get());

  // Send messages
  K3::Message m2 = K3::Message(K3::sender, "join", "()");
  for (int i = 0; i < num_messages; i++) {
    engine2->send(m2);
  }

  // Wait for completion
  while ((!K3::sent_all)) {
   continue;
  }

  // End timer
  K3::end = std::chrono::system_clock::now();

  // Cleanup
  engine2->forceTerminateEngine();
  service_threads->join_all();
  service_threads->remove_thread(t1.get());

  auto elapsed = K3::end - K3::start;
  return std::chrono::duration_cast<std::chrono::seconds>(elapsed);
}

int main(int argc, char** argv) {

 if (argc < 6) {
  std::cout << "usage: " << argv[0] << " num_messages message_len mode reciever_ip sender_ip";
  return -1;
 }

 int num_messages = std::atoi(argv[1]);
 int message_len = std::atoi(argv[2]);
 std::string mode = argv[3];
 auto receiver_ip = argv[4];
 auto sender_ip = argv[5];

 K3::desired = num_messages;

 K3::rendezvous = K3::make_address(receiver_ip, 3000);
 K3::sender = K3::make_address(sender_ip, 3000);

 if (mode == "receiver") {
   runReceiver(num_messages);
 }
 else {
   // output time in seconds
   std::chrono::seconds t = runSender(num_messages, message_len);
   std::ofstream f;
   f.open("results.txt");
   f << t.count();
   f.close();
 }

 return 0;
}
<commit_msg>Reduce logging in benchmark<commit_after>#include <Common.hpp>
#include <Engine.hpp>
#include <Dispatch.hpp>
#include <MessageProcessor.hpp>

#include <chrono>
#include <functional>
#include <iostream>
#include <sstream>
#include <fstream>

#include <boost/regex.hpp>
#include <boost/thread/thread.hpp>

namespace K3 {

using std::cout;
using std::endl;
using std::bind;
using std::string;
using std::shared_ptr;

Address rendezvous;
Address sender;
std::chrono::system_clock::time_point start, end;

int nodeCounter(0);
int numSent(0);
int desired(0);
bool received_all(false);
bool sent_all(false);
string message;

// "Trigger" Declarations
void join(shared_ptr<Engine> engine, string message_contents) {
  Message m = Message(rendezvous, "register", message);
  engine->send(m);
}

void register2(shared_ptr<Engine> engine, string message_contents) {
  int n = 1;
  nodeCounter += n;
  if (nodeCounter % (desired/100) == 0) {
    std::cout << "received count: " << nodeCounter << "/" << desired << std::endl;
  }
  if (nodeCounter == desired) {
    Message m = Message(sender, "finished", "()");
    engine->send(m);
    received_all = true;
  }

}
void finished(shared_ptr<Engine> engine, string message_contents) {
  sent_all = true;
  std::cout << "FINISHED!!!" << std::endl;
}

// MP setup
TriggerDispatch buildTable(shared_ptr<Engine> engine) {
  TriggerDispatch table = TriggerDispatch();
  table["join"] = bind(&K3::join, engine, std::placeholders::_1);
  table["register"] = bind(&K3::register2, engine, std::placeholders::_1);
  table["finished"] = bind(&K3::finished, engine, std::placeholders::_1);
  return table;
}

shared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) {
  auto table = buildTable(engine);
  shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table));
  return mp;
}

// Engine setup
shared_ptr<Engine> buildEngine(bool simulation, SystemEnvironment s_env) {
  // Configure engine components
  shared_ptr<InternalCodec> i_cdec = make_shared<LengthHeaderInternalCodec>(LengthHeaderInternalCodec());

  // Construct an engine
  Engine engine = Engine(simulation, s_env, i_cdec);
  return make_shared<Engine>(engine);
}

}

void runReceiver(int num_messages) {
  using boost::thread;
  using boost::thread_group;
  using std::shared_ptr;
  K3::nodeCounter = 0;

  // Create engines
  auto engine1 = K3::buildEngine(false, K3::defaultEnvironment(K3::rendezvous));
  // Create MPs
  auto mp1 = K3::buildMP(engine1);
  // Fork a thread for each engine
  auto service_threads = std::shared_ptr<thread_group>(new thread_group());
  shared_ptr<thread> t1 = engine1->forkEngine(mp1);
  service_threads->add_thread(t1.get());

  // Wait for completion
  while ((!K3::received_all)) {
   continue;
  }

  // Cleanup
  engine1->forceTerminateEngine();
  service_threads->join_all();
  service_threads->remove_thread(t1.get());
}

std::chrono::seconds runSender(int num_messages, int message_len) {
  using boost::thread;
  using boost::thread_group;
  using std::shared_ptr;

  // Build message
  K3::message = "";
  for (int i=0; i< message_len; i++) {
    K3::message += "a";
  }
  // Create engines
  auto engine2 = K3::buildEngine(false, K3::defaultEnvironment(K3::sender));
  // Create MPs
  auto mp2 = K3::buildMP(engine2);

  // Start timer
  K3::start = std::chrono::system_clock::now();

  // Fork a thread for each engine
  auto service_threads = std::shared_ptr<thread_group>(new thread_group());
  shared_ptr<thread> t1 = engine2->forkEngine(mp2);
  service_threads->add_thread(t1.get());

  // Send messages
  K3::Message m2 = K3::Message(K3::sender, "join", "()");
  for (int i = 0; i < num_messages; i++) {
    engine2->send(m2);
  }

  // Wait for completion
  while ((!K3::sent_all)) {
   continue;
  }

  // End timer
  K3::end = std::chrono::system_clock::now();

  // Cleanup
  engine2->forceTerminateEngine();
  service_threads->join_all();
  service_threads->remove_thread(t1.get());

  auto elapsed = K3::end - K3::start;
  return std::chrono::duration_cast<std::chrono::seconds>(elapsed);
}

int main(int argc, char** argv) {

 if (argc < 6) {
  std::cout << "usage: " << argv[0] << " num_messages message_len mode reciever_ip sender_ip";
  return -1;
 }

 int num_messages = std::atoi(argv[1]);
 int message_len = std::atoi(argv[2]);
 std::string mode = argv[3];
 auto receiver_ip = argv[4];
 auto sender_ip = argv[5];

 K3::desired = num_messages;

 K3::rendezvous = K3::make_address(receiver_ip, 3000);
 K3::sender = K3::make_address(sender_ip, 3000);

 if (mode == "receiver") {
   runReceiver(num_messages);
 }
 else {
   // output time in seconds
   std::chrono::seconds t = runSender(num_messages, message_len);
   std::ofstream f;
   f.open("results.txt");
   f << t.count();
   f.close();
 }

 return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * 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 "base/logging.h"
#include "entrypoints/entrypoint_utils.h"
#include "mirror/art_method-inl.h"
#include "mirror/object-inl.h"
#include "object_utils.h"
#include "scoped_thread_state_change.h"
#include "thread.h"

namespace art {

// Used by the JNI dlsym stub to find the native method to invoke if none is registered.
extern "C" void* artFindNativeMethod() {
  Thread* self = Thread::Current();
  Locks::mutator_lock_->AssertNotHeld(self);  // We come here as Native.
  ScopedObjectAccess soa(self);

  mirror::ArtMethod* method = self->GetCurrentMethod(NULL);
  DCHECK(method != NULL);

  // Lookup symbol address for method, on failure we'll return NULL with an exception set,
  // otherwise we return the address of the method we found.
  void* native_code = soa.Vm()->FindCodeForNativeMethod(method);
  if (native_code == NULL) {
    DCHECK(self->IsExceptionPending());
    return NULL;
  } else {
    // Register so that future calls don't come here
    method->RegisterNative(self, native_code, false);
    return native_code;
  }
}

static void WorkAroundJniBugsForJobject(intptr_t* arg_ptr) {
  intptr_t value = *arg_ptr;
  mirror::Object** value_as_jni_rep = reinterpret_cast<mirror::Object**>(value);
  mirror::Object* value_as_work_around_rep = value_as_jni_rep != NULL ? *value_as_jni_rep : NULL;
  CHECK(Runtime::Current()->GetHeap()->IsHeapAddress(value_as_work_around_rep))
      << value_as_work_around_rep;
  *arg_ptr = reinterpret_cast<intptr_t>(value_as_work_around_rep);
}

extern "C" const void* artWorkAroundAppJniBugs(Thread* self, intptr_t* sp)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
  DCHECK(Thread::Current() == self);
  // TODO: this code is specific to ARM
  // On entry the stack pointed by sp is:
  // | arg3   | <- Calling JNI method's frame (and extra bit for out args)
  // | LR     |
  // | R3     |    arg2
  // | R2     |    arg1
  // | R1     |    jclass/jobject
  // | R0     |    JNIEnv
  // | unused |
  // | unused |
  // | unused | <- sp
  mirror::ArtMethod* jni_method = self->GetCurrentMethod(NULL);
  DCHECK(jni_method->IsNative()) << PrettyMethod(jni_method);
  intptr_t* arg_ptr = sp + 4;  // pointer to r1 on stack
  // Fix up this/jclass argument
  WorkAroundJniBugsForJobject(arg_ptr);
  arg_ptr++;
  // Fix up jobject arguments
  MethodHelper mh(jni_method);
  int reg_num = 2;  // Current register being processed, -1 for stack arguments.
  for (uint32_t i = 1; i < mh.GetShortyLength(); i++) {
    char shorty_char = mh.GetShorty()[i];
    if (shorty_char == 'L') {
      WorkAroundJniBugsForJobject(arg_ptr);
    }
    if (shorty_char == 'J' || shorty_char == 'D') {
      if (reg_num == 2) {
        arg_ptr = sp + 8;  // skip to out arguments
        reg_num = -1;
      } else if (reg_num == 3) {
        arg_ptr = sp + 10;  // skip to out arguments plus 2 slots as long must be aligned
        reg_num = -1;
      } else {
        DCHECK_EQ(reg_num, -1);
        if ((reinterpret_cast<intptr_t>(arg_ptr) & 7) == 4) {
          arg_ptr += 3;  // unaligned, pad and move through stack arguments
        } else {
          arg_ptr += 2;  // aligned, move through stack arguments
        }
      }
    } else {
      if (reg_num == 2) {
        arg_ptr++;  // move through register arguments
        reg_num++;
      } else if (reg_num == 3) {
        arg_ptr = sp + 8;  // skip to outgoing stack arguments
        reg_num = -1;
      } else {
        DCHECK_EQ(reg_num, -1);
        arg_ptr++;  // move through stack arguments
      }
    }
  }
  // Load expected destination, see Method::RegisterNative
  const void* code = reinterpret_cast<const void*>(jni_method->GetNativeGcMap());
  if (UNLIKELY(code == NULL)) {
    code = GetJniDlsymLookupStub();
    jni_method->RegisterNative(self, code, false);
  }
  return code;
}

}  // namespace art
<commit_msg>am 86904258: am 0f6615fe: Merge "Fix incorrect IsHeapAddress in jni entrypoints."<commit_after>/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * 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 "base/logging.h"
#include "entrypoints/entrypoint_utils.h"
#include "mirror/art_method-inl.h"
#include "mirror/object-inl.h"
#include "object_utils.h"
#include "scoped_thread_state_change.h"
#include "thread.h"

namespace art {

// Used by the JNI dlsym stub to find the native method to invoke if none is registered.
extern "C" void* artFindNativeMethod() {
  Thread* self = Thread::Current();
  Locks::mutator_lock_->AssertNotHeld(self);  // We come here as Native.
  ScopedObjectAccess soa(self);

  mirror::ArtMethod* method = self->GetCurrentMethod(NULL);
  DCHECK(method != NULL);

  // Lookup symbol address for method, on failure we'll return NULL with an exception set,
  // otherwise we return the address of the method we found.
  void* native_code = soa.Vm()->FindCodeForNativeMethod(method);
  if (native_code == NULL) {
    DCHECK(self->IsExceptionPending());
    return NULL;
  } else {
    // Register so that future calls don't come here
    method->RegisterNative(self, native_code, false);
    return native_code;
  }
}

static void WorkAroundJniBugsForJobject(intptr_t* arg_ptr) {
  intptr_t value = *arg_ptr;
  mirror::Object** value_as_jni_rep = reinterpret_cast<mirror::Object**>(value);
  mirror::Object* value_as_work_around_rep = value_as_jni_rep != NULL ? *value_as_jni_rep : NULL;
  CHECK(Runtime::Current()->GetHeap()->IsValidObjectAddress(value_as_work_around_rep))
      << value_as_work_around_rep;
  *arg_ptr = reinterpret_cast<intptr_t>(value_as_work_around_rep);
}

extern "C" const void* artWorkAroundAppJniBugs(Thread* self, intptr_t* sp)
    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
  DCHECK(Thread::Current() == self);
  // TODO: this code is specific to ARM
  // On entry the stack pointed by sp is:
  // | arg3   | <- Calling JNI method's frame (and extra bit for out args)
  // | LR     |
  // | R3     |    arg2
  // | R2     |    arg1
  // | R1     |    jclass/jobject
  // | R0     |    JNIEnv
  // | unused |
  // | unused |
  // | unused | <- sp
  mirror::ArtMethod* jni_method = self->GetCurrentMethod(NULL);
  DCHECK(jni_method->IsNative()) << PrettyMethod(jni_method);
  intptr_t* arg_ptr = sp + 4;  // pointer to r1 on stack
  // Fix up this/jclass argument
  WorkAroundJniBugsForJobject(arg_ptr);
  arg_ptr++;
  // Fix up jobject arguments
  MethodHelper mh(jni_method);
  int reg_num = 2;  // Current register being processed, -1 for stack arguments.
  for (uint32_t i = 1; i < mh.GetShortyLength(); i++) {
    char shorty_char = mh.GetShorty()[i];
    if (shorty_char == 'L') {
      WorkAroundJniBugsForJobject(arg_ptr);
    }
    if (shorty_char == 'J' || shorty_char == 'D') {
      if (reg_num == 2) {
        arg_ptr = sp + 8;  // skip to out arguments
        reg_num = -1;
      } else if (reg_num == 3) {
        arg_ptr = sp + 10;  // skip to out arguments plus 2 slots as long must be aligned
        reg_num = -1;
      } else {
        DCHECK_EQ(reg_num, -1);
        if ((reinterpret_cast<intptr_t>(arg_ptr) & 7) == 4) {
          arg_ptr += 3;  // unaligned, pad and move through stack arguments
        } else {
          arg_ptr += 2;  // aligned, move through stack arguments
        }
      }
    } else {
      if (reg_num == 2) {
        arg_ptr++;  // move through register arguments
        reg_num++;
      } else if (reg_num == 3) {
        arg_ptr = sp + 8;  // skip to outgoing stack arguments
        reg_num = -1;
      } else {
        DCHECK_EQ(reg_num, -1);
        arg_ptr++;  // move through stack arguments
      }
    }
  }
  // Load expected destination, see Method::RegisterNative
  const void* code = reinterpret_cast<const void*>(jni_method->GetNativeGcMap());
  if (UNLIKELY(code == NULL)) {
    code = GetJniDlsymLookupStub();
    jni_method->RegisterNative(self, code, false);
  }
  return code;
}

}  // namespace art
<|endoftext|>