<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetParamManager.cpp
 */

#include "JPetParamManager.h"

#include <TFile.h>
#include <boost/property_tree/xml_parser.hpp>
#include "../JPetOptionsTools/JPetOptionsTools.h"
#include "../JPetParamGetterAscii/JPetParamGetterAscii.h"

std::shared_ptr<JPetParamManager> JPetParamManager::generateParamManager(const std::map<std::string, boost::any>& options)
{
  using namespace jpet_options_tools;
  if (isLocalDB(options)) {
    std::set<ParamObjectType> expectMissing;
    if (FileTypeChecker::getInputFileType(options) == FileTypeChecker::kScope) {
      expectMissing.insert(ParamObjectType::kTRB);
      expectMissing.insert(ParamObjectType::kFEB);
      expectMissing.insert(ParamObjectType::kFrame);
      expectMissing.insert(ParamObjectType::kLayer);
      expectMissing.insert(ParamObjectType::kTOMBChannel);
    }
    return std::make_shared<JPetParamManager>(new JPetParamGetterAscii(getLocalDB(options)), expectMissing);
  } else {
    return std::make_shared<JPetParamManager>();
  }
}

JPetParamManager::~JPetParamManager()
{
  if (fBank) {
    delete fBank;
    fBank = 0;
  }
  if (fParamGetter) {
    delete fParamGetter;
    fParamGetter = 0;
  }
}

std::map<int, JPetTRB*>& JPetParamManager::getTRBs(const int runId)
{
  return getTRBFactory(runId).getTRBs();
}

JPetTRBFactory& JPetParamManager::getTRBFactory(const int runId)
{
  if (fTRBFactories.count(runId) == 0) {
    fTRBFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId));
  }
  return fTRBFactories.at(runId);
}

std::map<int, JPetFEB*>& JPetParamManager::getFEBs(const int runId)
{
  return getFEBFactory(runId).getFEBs();
}

JPetFEBFactory& JPetParamManager::getFEBFactory(const int runId)
{
  if (fFEBFactories.count(runId) == 0) {
    fFEBFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getTRBFactory(runId)));
  }
  return fFEBFactories.at(runId);
}

std::map<int, JPetFrame*>& JPetParamManager::getFrames(const int runId)
{
  return getFrameFactory(runId).getFrames();
}

JPetFrameFactory& JPetParamManager::getFrameFactory(const int runId)
{
  if (fFrameFactories.count(runId) == 0) {
    fFrameFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId));
  }
  return fFrameFactories.at(runId);
}

std::map<int, JPetLayer*>& JPetParamManager::getLayers(const int runId)
{
  return getLayerFactory(runId).getLayers();
}

JPetLayerFactory& JPetParamManager::getLayerFactory(const int runId)
{
  if (fLayerFactories.count(runId) == 0) {
    fLayerFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getFrameFactory(runId)));
  }
  return fLayerFactories.at(runId);
}

std::map<int, JPetBarrelSlot*>& JPetParamManager::getBarrelSlots(const int runId)
{
  return getBarrelSlotFactory(runId).getBarrelSlots();
}

JPetBarrelSlotFactory& JPetParamManager::getBarrelSlotFactory(const int runId)
{
  if (fBarrelSlotFactories.count(runId) == 0) {
    fBarrelSlotFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getLayerFactory(runId)));
  }
  fBarrelSlotFactories.at(runId);
  return fBarrelSlotFactories.at(runId);
}

std::map<int, JPetScin*>& JPetParamManager::getScins(const int runId)
{
  return getScinFactory(runId).getScins();
}

JPetScinFactory& JPetParamManager::getScinFactory(const int runId)
{
  if (fScinFactories.count(runId) == 0) {
    fScinFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getBarrelSlotFactory(runId)));
  }
  return fScinFactories.at(runId);
}

std::map<int, JPetPM*>& JPetParamManager::getPMs(const int runId)
{
  return getPMFactory(runId).getPMs();
}

JPetPMFactory& JPetParamManager::getPMFactory(const int runId)
{
  if (fPMFactories.count(runId) == 0) {
    fPMFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getFEBFactory(runId), getScinFactory(runId), getBarrelSlotFactory(runId)));
  }
  return fPMFactories.at(runId);
}

std::map<int, JPetTOMBChannel*>& JPetParamManager::getTOMBChannels(const int runId)
{
  return getTOMBChannelFactory(runId).getTOMBChannels();
}

JPetTOMBChannelFactory& JPetParamManager::getTOMBChannelFactory(const int runId)
{
  if (fTOMBChannelFactories.count(runId) == 0) {
    fTOMBChannelFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getFEBFactory(runId), getTRBFactory(runId), getPMFactory(runId)));
  }
  return fTOMBChannelFactories.at(runId);
}

void JPetParamManager::fillParameterBank(const int run)
{
  if (fBank) {
    delete fBank;
    fBank = 0;
  }
  fBank = new JPetParamBank();
  if (!fExpectMissing.count(ParamObjectType::kTRB)) {
    for (auto& trbp : getTRBs(run)) {
      auto& trb = *trbp.second;
      fBank->addTRB(trb);
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kFEB)) {
    for (auto& febp : getFEBs(run)) {
      auto& feb = *febp.second;
      fBank->addFEB(feb);
      fBank->getFEB(feb.getID()).setTRB(fBank->getTRB(feb.getTRB().getID()));
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kFrame)) {
    for (auto& framep : getFrames(run)) {
      auto& frame = *framep.second;
      fBank->addFrame(frame);
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kLayer)) {
    for (auto& layerp : getLayers(run)) {
      auto& layer = *layerp.second;
      fBank->addLayer(layer);
      fBank->getLayer(layer.getID()).setFrame(fBank->getFrame(layer.getFrame().getID()));
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kBarrelSlot)) {
    for (auto& barrelSlotp : getBarrelSlots(run)) {
      auto& barrelSlot = *barrelSlotp.second;
      fBank->addBarrelSlot(barrelSlot);
      if (barrelSlot.hasLayer()) {
        fBank->getBarrelSlot(barrelSlot.getID()).setLayer(fBank->getLayer(barrelSlot.getLayer().getID()));
      }
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kScintillator)) {
    for (auto& scinp : getScins(run)) {
      auto& scin = *scinp.second;
      fBank->addScintillator(scin);
      fBank->getScintillator(scin.getID()).setBarrelSlot(fBank->getBarrelSlot(scin.getBarrelSlot().getID()));
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kPM)) {
    for (auto& pmp : getPMs(run)) {
      auto& pm = *pmp.second;
      fBank->addPM(pm);
      if (pm.hasFEB()) {
        fBank->getPM(pm.getID()).setFEB(fBank->getFEB(pm.getFEB().getID()));
      }
      fBank->getPM(pm.getID()).setScin(fBank->getScintillator(pm.getScin().getID()));
      fBank->getPM(pm.getID()).setBarrelSlot(fBank->getBarrelSlot(pm.getBarrelSlot().getID()));
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kTOMBChannel)) {
    for (auto& tombChannelp : getTOMBChannels(run)) {
      auto& tombChannel = *tombChannelp.second;
      fBank->addTOMBChannel(tombChannel);
      fBank->getTOMBChannel(tombChannel.getChannel()).setFEB(fBank->getFEB(tombChannel.getFEB().getID()));
      fBank->getTOMBChannel(tombChannel.getChannel()).setTRB(fBank->getTRB(tombChannel.getTRB().getID()));
      fBank->getTOMBChannel(tombChannel.getChannel()).setPM(fBank->getPM(tombChannel.getPM().getID()));
    }
  }
}

bool JPetParamManager::readParametersFromFile(JPetReader* reader)
{
  assert(reader);
  if (!reader->isOpen()) {
    ERROR("Cannot read parameters from file. The provided JPetReader is closed.");
    return false;
  }
  fBank = static_cast<JPetParamBank*>(reader->getObjectFromFile("ParamBank"));

  if (!fBank) return false;
  return true;
}

bool JPetParamManager::saveParametersToFile(JPetWriter* writer)
{
  assert(writer);
  if (!writer->isOpen()) {
    ERROR("Could not write parameters to file. The provided JPetWriter is closed.");
    return false;
  }
  writer->writeObject(fBank, "ParamBank");
  return true;
}

bool JPetParamManager::readParametersFromFile(std::string filename)
{
  TFile file(filename.c_str(), "READ");
  if (!file.IsOpen()) {
    ERROR("Could not read from file.");
    return false;
  }
  fBank = static_cast<JPetParamBank*>(file.Get("ParamBank"));

  if (!fBank) return false;
  return true;
}

const JPetParamBank& JPetParamManager::getParamBank() const
{
  DEBUG("getParamBank() from JPetParamManager");
  static JPetParamBank DummyResult(true);
  if (fBank) return *fBank;
  else return DummyResult;
}

bool JPetParamManager::saveParametersToFile(std::string filename)
{
  TFile file(filename.c_str(), "UPDATE");
  if (!file.IsOpen()) {
    ERROR("Could not write to file.");
    return false;
  }
  file.cd();
  assert(fBank);
  file.WriteObject(fBank, "ParamBank");
  return true;
}

void JPetParamManager::clearParameters()
{
  assert(fBank);
  fBank->clear();
}

void JPetParamManager::createXMLFile(const std::string& channelDataFileName, int channelOffset, int numberOfChannels)
{
  using boost::property_tree::ptree;
  ptree pt;

  std::string debug = "OFF";
  std::string dataSourceType = "TRB3_S";
  std::string dataSourceTrbNetAddress = "8000";
  std::string dataSourceHubAddress = "8000";
  std::string dataSourceReferenceChannel = "0";
  std::string dataSourceCorrectionFile = "raw";

  pt.put("READOUT.DEBUG", debug);
  pt.put("READOUT.DATA_SOURCE.TYPE", dataSourceType);
  pt.put("READOUT.DATA_SOURCE.TRBNET_ADDRESS", dataSourceTrbNetAddress);
  pt.put("READOUT.DATA_SOURCE.HUB_ADDRESS", dataSourceHubAddress);
  pt.put("READOUT.DATA_SOURCE.REFERENCE_CHANNEL", dataSourceReferenceChannel);
  pt.put("READOUT.DATA_SOURCE.CORRECTION_FILE", dataSourceCorrectionFile);

  ptree& externalNode = pt.add("READOUT.DATA_SOURCE.MODULES", "");

  ptree& internalNode = externalNode.add("MODULE", "");
  internalNode.put("TYPE", "LATTICE_TDC");
  internalNode.put("TRBNET_ADDRESS", "e000");
  internalNode.put("NUMBER_OF_CHANNELS", numberOfChannels);
  internalNode.put("CHANNEL_OFFSET", channelOffset);
  internalNode.put("RESOLUTION", "100");
  internalNode.put("MEASUREMENT_TYPE", "TDC");

  write_xml(channelDataFileName, pt);
}

void JPetParamManager::getTOMBDataAndCreateXMLFile(const int p_run_id)
{
  fillParameterBank(p_run_id);
  int TOMBChannelsSize = fBank->getTOMBChannelsSize();
  int channelOffset = 0;
  int numberOfChannels = 0;

  if (TOMBChannelsSize) {
    for (int i = 0; i < TOMBChannelsSize; ++i) {
      if (i == 0) {
        std::string description = fBank->getTOMBChannel(i).getDescription();
        channelOffset = JPetParamGetter::getTOMBChannelFromDescription(description);
      }
      ++numberOfChannels;
    }
    createXMLFile("conf.xml", channelOffset, numberOfChannels);
    return;
  }
  ERROR("TOMBChannelsSize is equal to zero.");
}
<commit_msg>Update includes<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetParamManager.cpp
 */

#include "JPetParamManager.h"

#include <TFile.h>
#include <boost/property_tree/xml_parser.hpp>
#include "./JPetOptionsTools/JPetOptionsTools.h"
#include "./JPetParamGetterAscii/JPetParamGetterAscii.h"

std::shared_ptr<JPetParamManager> JPetParamManager::generateParamManager(const std::map<std::string, boost::any>& options)
{
  using namespace jpet_options_tools;
  if (isLocalDB(options)) {
    std::set<ParamObjectType> expectMissing;
    if (FileTypeChecker::getInputFileType(options) == FileTypeChecker::kScope) {
      expectMissing.insert(ParamObjectType::kTRB);
      expectMissing.insert(ParamObjectType::kFEB);
      expectMissing.insert(ParamObjectType::kFrame);
      expectMissing.insert(ParamObjectType::kLayer);
      expectMissing.insert(ParamObjectType::kTOMBChannel);
    }
    return std::make_shared<JPetParamManager>(new JPetParamGetterAscii(getLocalDB(options)), expectMissing);
  } else {
    return std::make_shared<JPetParamManager>();
  }
}

JPetParamManager::~JPetParamManager()
{
  if (fBank) {
    delete fBank;
    fBank = 0;
  }
  if (fParamGetter) {
    delete fParamGetter;
    fParamGetter = 0;
  }
}

std::map<int, JPetTRB*>& JPetParamManager::getTRBs(const int runId)
{
  return getTRBFactory(runId).getTRBs();
}

JPetTRBFactory& JPetParamManager::getTRBFactory(const int runId)
{
  if (fTRBFactories.count(runId) == 0) {
    fTRBFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId));
  }
  return fTRBFactories.at(runId);
}

std::map<int, JPetFEB*>& JPetParamManager::getFEBs(const int runId)
{
  return getFEBFactory(runId).getFEBs();
}

JPetFEBFactory& JPetParamManager::getFEBFactory(const int runId)
{
  if (fFEBFactories.count(runId) == 0) {
    fFEBFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getTRBFactory(runId)));
  }
  return fFEBFactories.at(runId);
}

std::map<int, JPetFrame*>& JPetParamManager::getFrames(const int runId)
{
  return getFrameFactory(runId).getFrames();
}

JPetFrameFactory& JPetParamManager::getFrameFactory(const int runId)
{
  if (fFrameFactories.count(runId) == 0) {
    fFrameFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId));
  }
  return fFrameFactories.at(runId);
}

std::map<int, JPetLayer*>& JPetParamManager::getLayers(const int runId)
{
  return getLayerFactory(runId).getLayers();
}

JPetLayerFactory& JPetParamManager::getLayerFactory(const int runId)
{
  if (fLayerFactories.count(runId) == 0) {
    fLayerFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getFrameFactory(runId)));
  }
  return fLayerFactories.at(runId);
}

std::map<int, JPetBarrelSlot*>& JPetParamManager::getBarrelSlots(const int runId)
{
  return getBarrelSlotFactory(runId).getBarrelSlots();
}

JPetBarrelSlotFactory& JPetParamManager::getBarrelSlotFactory(const int runId)
{
  if (fBarrelSlotFactories.count(runId) == 0) {
    fBarrelSlotFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getLayerFactory(runId)));
  }
  fBarrelSlotFactories.at(runId);
  return fBarrelSlotFactories.at(runId);
}

std::map<int, JPetScin*>& JPetParamManager::getScins(const int runId)
{
  return getScinFactory(runId).getScins();
}

JPetScinFactory& JPetParamManager::getScinFactory(const int runId)
{
  if (fScinFactories.count(runId) == 0) {
    fScinFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getBarrelSlotFactory(runId)));
  }
  return fScinFactories.at(runId);
}

std::map<int, JPetPM*>& JPetParamManager::getPMs(const int runId)
{
  return getPMFactory(runId).getPMs();
}

JPetPMFactory& JPetParamManager::getPMFactory(const int runId)
{
  if (fPMFactories.count(runId) == 0) {
    fPMFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getFEBFactory(runId), getScinFactory(runId), getBarrelSlotFactory(runId)));
  }
  return fPMFactories.at(runId);
}

std::map<int, JPetTOMBChannel*>& JPetParamManager::getTOMBChannels(const int runId)
{
  return getTOMBChannelFactory(runId).getTOMBChannels();
}

JPetTOMBChannelFactory& JPetParamManager::getTOMBChannelFactory(const int runId)
{
  if (fTOMBChannelFactories.count(runId) == 0) {
    fTOMBChannelFactories.emplace(std::piecewise_construct, std::forward_as_tuple(runId), std::forward_as_tuple(*fParamGetter, runId, getFEBFactory(runId), getTRBFactory(runId), getPMFactory(runId)));
  }
  return fTOMBChannelFactories.at(runId);
}

void JPetParamManager::fillParameterBank(const int run)
{
  if (fBank) {
    delete fBank;
    fBank = 0;
  }
  fBank = new JPetParamBank();
  if (!fExpectMissing.count(ParamObjectType::kTRB)) {
    for (auto& trbp : getTRBs(run)) {
      auto& trb = *trbp.second;
      fBank->addTRB(trb);
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kFEB)) {
    for (auto& febp : getFEBs(run)) {
      auto& feb = *febp.second;
      fBank->addFEB(feb);
      fBank->getFEB(feb.getID()).setTRB(fBank->getTRB(feb.getTRB().getID()));
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kFrame)) {
    for (auto& framep : getFrames(run)) {
      auto& frame = *framep.second;
      fBank->addFrame(frame);
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kLayer)) {
    for (auto& layerp : getLayers(run)) {
      auto& layer = *layerp.second;
      fBank->addLayer(layer);
      fBank->getLayer(layer.getID()).setFrame(fBank->getFrame(layer.getFrame().getID()));
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kBarrelSlot)) {
    for (auto& barrelSlotp : getBarrelSlots(run)) {
      auto& barrelSlot = *barrelSlotp.second;
      fBank->addBarrelSlot(barrelSlot);
      if (barrelSlot.hasLayer()) {
        fBank->getBarrelSlot(barrelSlot.getID()).setLayer(fBank->getLayer(barrelSlot.getLayer().getID()));
      }
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kScintillator)) {
    for (auto& scinp : getScins(run)) {
      auto& scin = *scinp.second;
      fBank->addScintillator(scin);
      fBank->getScintillator(scin.getID()).setBarrelSlot(fBank->getBarrelSlot(scin.getBarrelSlot().getID()));
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kPM)) {
    for (auto& pmp : getPMs(run)) {
      auto& pm = *pmp.second;
      fBank->addPM(pm);
      if (pm.hasFEB()) {
        fBank->getPM(pm.getID()).setFEB(fBank->getFEB(pm.getFEB().getID()));
      }
      fBank->getPM(pm.getID()).setScin(fBank->getScintillator(pm.getScin().getID()));
      fBank->getPM(pm.getID()).setBarrelSlot(fBank->getBarrelSlot(pm.getBarrelSlot().getID()));
    }
  }
  if (!fExpectMissing.count(ParamObjectType::kTOMBChannel)) {
    for (auto& tombChannelp : getTOMBChannels(run)) {
      auto& tombChannel = *tombChannelp.second;
      fBank->addTOMBChannel(tombChannel);
      fBank->getTOMBChannel(tombChannel.getChannel()).setFEB(fBank->getFEB(tombChannel.getFEB().getID()));
      fBank->getTOMBChannel(tombChannel.getChannel()).setTRB(fBank->getTRB(tombChannel.getTRB().getID()));
      fBank->getTOMBChannel(tombChannel.getChannel()).setPM(fBank->getPM(tombChannel.getPM().getID()));
    }
  }
}

bool JPetParamManager::readParametersFromFile(JPetReader* reader)
{
  assert(reader);
  if (!reader->isOpen()) {
    ERROR("Cannot read parameters from file. The provided JPetReader is closed.");
    return false;
  }
  fBank = static_cast<JPetParamBank*>(reader->getObjectFromFile("ParamBank"));

  if (!fBank) return false;
  return true;
}

bool JPetParamManager::saveParametersToFile(JPetWriter* writer)
{
  assert(writer);
  if (!writer->isOpen()) {
    ERROR("Could not write parameters to file. The provided JPetWriter is closed.");
    return false;
  }
  writer->writeObject(fBank, "ParamBank");
  return true;
}

bool JPetParamManager::readParametersFromFile(std::string filename)
{
  TFile file(filename.c_str(), "READ");
  if (!file.IsOpen()) {
    ERROR("Could not read from file.");
    return false;
  }
  fBank = static_cast<JPetParamBank*>(file.Get("ParamBank"));

  if (!fBank) return false;
  return true;
}

const JPetParamBank& JPetParamManager::getParamBank() const
{
  DEBUG("getParamBank() from JPetParamManager");
  static JPetParamBank DummyResult(true);
  if (fBank) return *fBank;
  else return DummyResult;
}

bool JPetParamManager::saveParametersToFile(std::string filename)
{
  TFile file(filename.c_str(), "UPDATE");
  if (!file.IsOpen()) {
    ERROR("Could not write to file.");
    return false;
  }
  file.cd();
  assert(fBank);
  file.WriteObject(fBank, "ParamBank");
  return true;
}

void JPetParamManager::clearParameters()
{
  assert(fBank);
  fBank->clear();
}

void JPetParamManager::createXMLFile(const std::string& channelDataFileName, int channelOffset, int numberOfChannels)
{
  using boost::property_tree::ptree;
  ptree pt;

  std::string debug = "OFF";
  std::string dataSourceType = "TRB3_S";
  std::string dataSourceTrbNetAddress = "8000";
  std::string dataSourceHubAddress = "8000";
  std::string dataSourceReferenceChannel = "0";
  std::string dataSourceCorrectionFile = "raw";

  pt.put("READOUT.DEBUG", debug);
  pt.put("READOUT.DATA_SOURCE.TYPE", dataSourceType);
  pt.put("READOUT.DATA_SOURCE.TRBNET_ADDRESS", dataSourceTrbNetAddress);
  pt.put("READOUT.DATA_SOURCE.HUB_ADDRESS", dataSourceHubAddress);
  pt.put("READOUT.DATA_SOURCE.REFERENCE_CHANNEL", dataSourceReferenceChannel);
  pt.put("READOUT.DATA_SOURCE.CORRECTION_FILE", dataSourceCorrectionFile);

  ptree& externalNode = pt.add("READOUT.DATA_SOURCE.MODULES", "");

  ptree& internalNode = externalNode.add("MODULE", "");
  internalNode.put("TYPE", "LATTICE_TDC");
  internalNode.put("TRBNET_ADDRESS", "e000");
  internalNode.put("NUMBER_OF_CHANNELS", numberOfChannels);
  internalNode.put("CHANNEL_OFFSET", channelOffset);
  internalNode.put("RESOLUTION", "100");
  internalNode.put("MEASUREMENT_TYPE", "TDC");

  write_xml(channelDataFileName, pt);
}

void JPetParamManager::getTOMBDataAndCreateXMLFile(const int p_run_id)
{
  fillParameterBank(p_run_id);
  int TOMBChannelsSize = fBank->getTOMBChannelsSize();
  int channelOffset = 0;
  int numberOfChannels = 0;

  if (TOMBChannelsSize) {
    for (int i = 0; i < TOMBChannelsSize; ++i) {
      if (i == 0) {
        std::string description = fBank->getTOMBChannel(i).getDescription();
        channelOffset = JPetParamGetter::getTOMBChannelFromDescription(description);
      }
      ++numberOfChannels;
    }
    createXMLFile("conf.xml", channelOffset, numberOfChannels);
    return;
  }
  ERROR("TOMBChannelsSize is equal to zero.");
}
<|endoftext|>


<commit_before>#include "predicator.h"
#include "planning_tool.h"

#include <boost/bind/bind.hpp>

namespace predicator_planning {

  Planner::Planner(PredicateContext *_context, unsigned int _max_iter, unsigned int _children, double _step) :
    context(_context), max_iter(_max_iter), children(_children), step(_step)
  {
    ros::NodeHandle nh;
    planServer = nh.advertiseService <
      predicator_planning::PredicatePlan::Request,
      predicator_planning::PredicatePlan::Response>
        ("/predicator/plan",
         boost::bind(&Planner::plan, *this, _1, _2));
  }

  bool Planner::plan(predicator_planning::PredicatePlan::Request &req,
                     predicator_planning::PredicatePlan::Response &res)
  {

    // get starting states
    // these are the states as recorded in the context
    // they will be updated as we go on if this takes a while -- might be bad
    std::vector<RobotState *> starting_states = context->states;

    // find the index of the current robot state
    for (RobotModelPtr &ptr: context->robots) {
      std::cout << ptr->getName() << std::endl;
    }

    // loop over
    for (unsigned int iter = 0; iter < max_iter; ++iter) {
      // either generate a starting position at random or...
      // step in a direction from a "good" position (as determined by high heuristics)

    }

    return true;
  }

}
<commit_msg> find index<commit_after>#include "predicator.h"
#include "planning_tool.h"

#include <boost/bind/bind.hpp>

namespace predicator_planning {

  Planner::Planner(PredicateContext *_context, unsigned int _max_iter, unsigned int _children, double _step) :
    context(_context), max_iter(_max_iter), children(_children), step(_step)
  {
    ros::NodeHandle nh;
    planServer = nh.advertiseService <
      predicator_planning::PredicatePlan::Request,
      predicator_planning::PredicatePlan::Response>
        ("/predicator/plan",
         boost::bind(&Planner::plan, *this, _1, _2));
  }

  bool Planner::plan(predicator_planning::PredicatePlan::Request &req,
                     predicator_planning::PredicatePlan::Response &res)
  {

    // get starting states
    // these are the states as recorded in the context
    // they will be updated as we go on if this takes a while -- might be bad
    std::vector<RobotState *> starting_states = context->states;

    // find the index of the current robot state
    unsigned int idx = 0;
    for (RobotModelPtr &ptr: context->robots) {
      std::cout << ptr->getName() << std::endl;
      if (ptr->getName().compare(req.robot)) {
          break;
      }
      ++idx;
    }

    // loop over
    for (unsigned int iter = 0; iter < max_iter; ++iter) {
      // either generate a starting position at random or...
      // step in a direction from a "good" position (as determined by high heuristics)

    }

    return true;
  }

}
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "hitcollector.h"
#include <vespa/searchlib/common/bitvector.h>
#include <vespa/searchlib/common/sort.h>

namespace search::queryeval {

void
HitCollector::sortHitsByScore(size_t topn)
{
    topn = std::min(topn, _hits.size());
    if (topn > _scoreOrder.size()) {
        _scoreOrder.clear();
        _scoreOrder.reserve(_hits.size());
        for (size_t i(0); i < _hits.size(); i++) {
            _scoreOrder.push_back(i);
        }
        ShiftBasedRadixSorter<uint32_t, IndirectScoreRadix, IndirectScoreComparator, 56, true>::
           radix_sort(IndirectScoreRadix(&_hits[0]), IndirectScoreComparator(&_hits[0]), &_scoreOrder[0], _scoreOrder.size(), 16, topn);
        _scoreOrder.resize(topn);
    }
}

void
HitCollector::sortHitsByDocId()
{
    if (_hitsSortOrder != SortOrder::DOC_ID) {
        ShiftBasedRadixSorter<Hit, DocIdRadix, DocIdComparator, 24>::
           radix_sort(DocIdRadix(), DocIdComparator(), &_hits[0], _hits.size(), 16);
        _hitsSortOrder = SortOrder::DOC_ID;
        _scoreOrder.clear();
    }
}

HitCollector::HitCollector(uint32_t numDocs,
                           uint32_t maxHitsSize,
                           uint32_t maxReRankHitsSize)
    : _numDocs(numDocs),
      _maxHitsSize(maxHitsSize),
      _maxReRankHitsSize(maxReRankHitsSize),
      _maxDocIdVectorSize((numDocs + 31) / 32),
      _hits(),
      _hitsSortOrder(SortOrder::DOC_ID),
      _unordered(false),
      _docIdVector(),
      _bitVector(),
      _reRankedHits(),
      _scale(1.0),
      _adjust(0),
      _hasReRanked(false),
      _needReScore(false)
{
    if (_maxHitsSize > 0) {
        _collector = std::make_unique<RankedHitCollector>(*this);
    } else {
        _collector = std::make_unique<DocIdCollector<false>>(*this);
    }
    _hits.reserve(maxHitsSize);
}

HitCollector::~HitCollector() = default;

void
HitCollector::RankedHitCollector::collect(uint32_t docId, feature_t score)
{
    HitCollector & hc = this->_hc;
    if (hc._hits.size() < hc._maxHitsSize) {
        if (__builtin_expect(((hc._hits.size() > 0) &&
                              (docId < hc._hits.back().first) &&
                              (hc._hitsSortOrder == SortOrder::DOC_ID)), false))
        {
            hc._hitsSortOrder = SortOrder::NONE;
            hc._unordered = true;
        }
        hc._hits.push_back(std::make_pair(docId, score));
    } else {
        collectAndChangeCollector(docId, score);
    }
}

template <bool CollectRankedHit>
void
HitCollector::BitVectorCollector<CollectRankedHit>::collect(uint32_t docId, feature_t score) {
    this->_hc._bitVector->setBit(docId);
    if (CollectRankedHit) {
        this->considerForHitVector(docId, score);
    }
}

void
HitCollector::CollectorBase::replaceHitInVector(uint32_t docId, feature_t score) {
    // replace lowest scored hit in hit vector
    std::pop_heap(_hc._hits.begin(), _hc._hits.end(), ScoreComparator());
    _hc._hits.back().first = docId;
    _hc._hits.back().second = score;
    std::push_heap(_hc._hits.begin(), _hc._hits.end(), ScoreComparator());
}

void
HitCollector::RankedHitCollector::collectAndChangeCollector(uint32_t docId, feature_t score)
{
    HitCollector & hc = this->_hc;
    Collector::UP newCollector;
    if (hc._maxDocIdVectorSize > hc._maxHitsSize) {
        // start using docid vector
        hc._docIdVector.reserve(hc._maxDocIdVectorSize);
        uint32_t iSize = hc._hits.size();
        for (uint32_t i = 0; i < iSize; ++i) {
            hc._docIdVector.push_back(hc._hits[i].first);
        }
        hc._docIdVector.push_back(docId);
        newCollector = std::make_unique<DocIdCollector<true>>(hc);
    } else {
        // start using bit vector
        hc._bitVector = BitVector::create(hc._numDocs);
        hc._bitVector->invalidateCachedCount();
        uint32_t iSize = hc._hits.size();
        for (uint32_t i = 0; i < iSize; ++i) {
            hc._bitVector->setBit(hc._hits[i].first);
        }
        hc._bitVector->setBit(docId);
        newCollector = std::make_unique<BitVectorCollector<true>>(hc);
    }
    // treat hit vector as a heap
    std::make_heap(hc._hits.begin(), hc._hits.end(), ScoreComparator());
    hc._hitsSortOrder = SortOrder::HEAP;
    this->considerForHitVector(docId, score);
    hc._collector = std::move(newCollector);
}

template<bool CollectRankedHit>
void
HitCollector::DocIdCollector<CollectRankedHit>::collect(uint32_t docId, feature_t score)
{
    if (CollectRankedHit) {
        this->considerForHitVector(docId, score);
    }
    HitCollector & hc = this->_hc;
    if (hc._docIdVector.size() < hc._maxDocIdVectorSize) {
        if (__builtin_expect(((hc._docIdVector.size() > 0) &&
                              (docId < hc._docIdVector.back()) &&
                              (hc._unordered == false)), false))
        {
            hc._unordered = true;
        }
        hc._docIdVector.push_back(docId);
    } else {
        collectAndChangeCollector(docId);
    }
}

template<bool CollectRankedHit>
void
HitCollector::DocIdCollector<CollectRankedHit>::collectAndChangeCollector(uint32_t docId)
{
    HitCollector & hc = this->_hc;
    // start using bit vector instead of docid array.
    hc._bitVector = BitVector::create(hc._numDocs);
    hc._bitVector->invalidateCachedCount();
    uint32_t iSize = static_cast<uint32_t>(hc._docIdVector.size());
    for (uint32_t i = 0; i < iSize; ++i) {
        hc._bitVector->setBit(hc._docIdVector[i]);
    }
    std::vector<uint32_t> emptyVector;
    emptyVector.swap(hc._docIdVector);
    hc._bitVector->setBit(docId);
    hc._collector = std::make_unique<BitVectorCollector<CollectRankedHit>>(hc); // note - self-destruct.
}

std::vector<feature_t>
HitCollector::getSortedHeapScores()
{
    std::vector<feature_t> scores;
    size_t scoresToReturn = std::min(_hits.size(), static_cast<size_t>(_maxReRankHitsSize));
    scores.reserve(scoresToReturn);
    sortHitsByScore(scoresToReturn);
    for (size_t i = 0; i < scoresToReturn; ++i) {
        scores.push_back(_hits[_scoreOrder[i]].second);
    }
    return scores;
}

std::vector<HitCollector::Hit>
HitCollector::getSortedHeapHits()
{
    std::vector<Hit> scores;
    size_t scoresToReturn = std::min(_hits.size(), static_cast<size_t>(_maxReRankHitsSize));
    scores.reserve(scoresToReturn);
    sortHitsByScore(scoresToReturn);
    for (size_t i = 0; i < scoresToReturn; ++i) {
        scores.push_back(_hits[_scoreOrder[i]]);
    }
    return scores;
}

size_t
HitCollector::reRank(DocumentScorer &scorer)
{
    return reRank(scorer, _maxReRankHitsSize);
}

size_t
HitCollector::reRank(DocumentScorer &scorer, size_t count)
{
    size_t hitsToReRank = std::min(_hits.size(), count);
    if (_hasReRanked || hitsToReRank == 0) {
        return 0;
    }
    sortHitsByScore(hitsToReRank);
    std::vector<Hit> hits;
    hits.reserve(hitsToReRank);
    for (size_t i(0); i < hitsToReRank; i++) {
        hits.push_back(_hits[_scoreOrder[i]]);
    }
    return reRank(scorer, std::move(hits));
}

size_t
HitCollector::reRank(DocumentScorer &scorer, std::vector<Hit> hits) {
    size_t hitsToReRank = hits.size();
    if (_reRankedHits.empty()) {
        _reRankedHits = std::move(hits);
    } else {
        _reRankedHits.insert(_reRankedHits.end(), hits.begin(), hits.end());
    }
    Scores &initScores = _ranges.first;
    Scores &finalScores = _ranges.second;
    initScores = Scores(_reRankedHits.back().second, _reRankedHits.front().second);
    finalScores = Scores(std::numeric_limits<feature_t>::max(),
                         -std::numeric_limits<feature_t>::max());

    std::sort(_reRankedHits.begin(), _reRankedHits.end()); // sort on docId
    for (auto &hit : _reRankedHits) {
        hit.second = scorer.score(hit.first);
        finalScores.low = std::min(finalScores.low, hit.second);
        finalScores.high = std::max(finalScores.high, hit.second);
    }
    _hasReRanked = true;
    return hitsToReRank;
}

std::pair<Scores, Scores>
HitCollector::getRanges() const
{
    return _ranges;
}

void
HitCollector::setRanges(const std::pair<Scores, Scores> &ranges)
{
    _ranges = ranges;
}

namespace {

void
mergeHitsIntoResultSet(const std::vector<HitCollector::Hit> &hits, ResultSet &result)
{
    RankedHit *rhIter = result.getArray();
    RankedHit *rhEnd = rhIter + result.getArrayUsed();
    for (const auto &hit : hits) {
        while (rhIter != rhEnd && rhIter->_docId != hit.first) {
            // just set the iterators right
            ++rhIter;
        }
        assert(rhIter != rhEnd); // the hits should be a subset of the hits in ranked hit array.
        rhIter->_rankValue = hit.second;
    }
}

}

std::unique_ptr<ResultSet>
HitCollector::getResultSet(HitRank default_value)
{
    Scores &initHeapScores = _ranges.first;
    Scores &finalHeapScores = _ranges.second;
    if (initHeapScores.low > finalHeapScores.low) {
        // scale and adjust the score according to the range
        // of the initial and final heap score values to avoid that
        // a score from the first phase is larger than finalHeapScores.low
        feature_t initRange = initHeapScores.high - initHeapScores.low;
        if (initRange < 1.0) initRange = 1.0f;
        feature_t finalRange = finalHeapScores.high - finalHeapScores.low;
        if (finalRange < 1.0) finalRange = 1.0f;
        _scale = finalRange / initRange;
        _adjust = initHeapScores.low * _scale - finalHeapScores.low;
        _needReScore = true;
    }

    // destroys the heap property or score sort order
    sortHitsByDocId();

    std::unique_ptr<ResultSet> rs(new ResultSet());
    if ( ! _collector->isDocIdCollector() ) {
        unsigned int iSize = _hits.size();
        rs->allocArray(iSize);
        RankedHit * rh = rs->getArray();
        if (_needReScore) {
            for (uint32_t i = 0; i < iSize; ++i) {
                rh[i]._docId = _hits[i].first;
                rh[i]._rankValue = getReScore(_hits[i].second);
            }
        } else {
            for (uint32_t i = 0; i < iSize; ++i) {
                rh[i]._docId = _hits[i].first;
                rh[i]._rankValue = _hits[i].second;
            }
        }
        rs->setArrayUsed(iSize);
    } else {
        if (_unordered) {
            std::sort(_docIdVector.begin(), _docIdVector.end());
        }
        unsigned int iSize = _hits.size();
        unsigned int jSize = _docIdVector.size();
        rs->allocArray(jSize);
        RankedHit * rh = rs->getArray();
        uint32_t i = 0;
        if (_needReScore) {
            for (uint32_t j = 0; j < jSize; ++j) {
                uint32_t docId = _docIdVector[j];
                rh[j]._docId = docId;
                if (i < iSize && docId == _hits[i].first) {
                    rh[j]._rankValue = getReScore(_hits[i].second);
                    ++i;
                } else {
                    rh[j]._rankValue = default_value;
                }
            }
        } else {
            for (uint32_t j = 0; j < jSize; ++j) {
                uint32_t docId = _docIdVector[j];
                rh[j]._docId = docId;
                if (i < iSize && docId == _hits[i].first) {
                    rh[j]._rankValue = _hits[i].second;
                    ++i;
                } else {
                    rh[j]._rankValue = default_value;
                }
            }
        }
        rs->setArrayUsed(jSize);
    }

    if (_hasReRanked) {
        mergeHitsIntoResultSet(_reRankedHits, *rs.get());
    }

    if (_bitVector != NULL) {
        rs->setBitOverflow(std::move(_bitVector));
    }

    return rs;
}

}
<commit_msg>Simplify since reRank i snot incremental.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "hitcollector.h"
#include <vespa/searchlib/common/bitvector.h>
#include <vespa/searchlib/common/sort.h>

namespace search::queryeval {

void
HitCollector::sortHitsByScore(size_t topn)
{
    topn = std::min(topn, _hits.size());
    if (topn > _scoreOrder.size()) {
        _scoreOrder.clear();
        _scoreOrder.reserve(_hits.size());
        for (size_t i(0); i < _hits.size(); i++) {
            _scoreOrder.push_back(i);
        }
        ShiftBasedRadixSorter<uint32_t, IndirectScoreRadix, IndirectScoreComparator, 56, true>::
           radix_sort(IndirectScoreRadix(&_hits[0]), IndirectScoreComparator(&_hits[0]), &_scoreOrder[0], _scoreOrder.size(), 16, topn);
        _scoreOrder.resize(topn);
    }
}

void
HitCollector::sortHitsByDocId()
{
    if (_hitsSortOrder != SortOrder::DOC_ID) {
        ShiftBasedRadixSorter<Hit, DocIdRadix, DocIdComparator, 24>::
           radix_sort(DocIdRadix(), DocIdComparator(), &_hits[0], _hits.size(), 16);
        _hitsSortOrder = SortOrder::DOC_ID;
        _scoreOrder.clear();
    }
}

HitCollector::HitCollector(uint32_t numDocs,
                           uint32_t maxHitsSize,
                           uint32_t maxReRankHitsSize)
    : _numDocs(numDocs),
      _maxHitsSize(maxHitsSize),
      _maxReRankHitsSize(maxReRankHitsSize),
      _maxDocIdVectorSize((numDocs + 31) / 32),
      _hits(),
      _hitsSortOrder(SortOrder::DOC_ID),
      _unordered(false),
      _docIdVector(),
      _bitVector(),
      _reRankedHits(),
      _scale(1.0),
      _adjust(0),
      _hasReRanked(false),
      _needReScore(false)
{
    if (_maxHitsSize > 0) {
        _collector = std::make_unique<RankedHitCollector>(*this);
    } else {
        _collector = std::make_unique<DocIdCollector<false>>(*this);
    }
    _hits.reserve(maxHitsSize);
}

HitCollector::~HitCollector() = default;

void
HitCollector::RankedHitCollector::collect(uint32_t docId, feature_t score)
{
    HitCollector & hc = this->_hc;
    if (hc._hits.size() < hc._maxHitsSize) {
        if (__builtin_expect(((hc._hits.size() > 0) &&
                              (docId < hc._hits.back().first) &&
                              (hc._hitsSortOrder == SortOrder::DOC_ID)), false))
        {
            hc._hitsSortOrder = SortOrder::NONE;
            hc._unordered = true;
        }
        hc._hits.push_back(std::make_pair(docId, score));
    } else {
        collectAndChangeCollector(docId, score);
    }
}

template <bool CollectRankedHit>
void
HitCollector::BitVectorCollector<CollectRankedHit>::collect(uint32_t docId, feature_t score) {
    this->_hc._bitVector->setBit(docId);
    if (CollectRankedHit) {
        this->considerForHitVector(docId, score);
    }
}

void
HitCollector::CollectorBase::replaceHitInVector(uint32_t docId, feature_t score) {
    // replace lowest scored hit in hit vector
    std::pop_heap(_hc._hits.begin(), _hc._hits.end(), ScoreComparator());
    _hc._hits.back().first = docId;
    _hc._hits.back().second = score;
    std::push_heap(_hc._hits.begin(), _hc._hits.end(), ScoreComparator());
}

void
HitCollector::RankedHitCollector::collectAndChangeCollector(uint32_t docId, feature_t score)
{
    HitCollector & hc = this->_hc;
    Collector::UP newCollector;
    if (hc._maxDocIdVectorSize > hc._maxHitsSize) {
        // start using docid vector
        hc._docIdVector.reserve(hc._maxDocIdVectorSize);
        uint32_t iSize = hc._hits.size();
        for (uint32_t i = 0; i < iSize; ++i) {
            hc._docIdVector.push_back(hc._hits[i].first);
        }
        hc._docIdVector.push_back(docId);
        newCollector = std::make_unique<DocIdCollector<true>>(hc);
    } else {
        // start using bit vector
        hc._bitVector = BitVector::create(hc._numDocs);
        hc._bitVector->invalidateCachedCount();
        uint32_t iSize = hc._hits.size();
        for (uint32_t i = 0; i < iSize; ++i) {
            hc._bitVector->setBit(hc._hits[i].first);
        }
        hc._bitVector->setBit(docId);
        newCollector = std::make_unique<BitVectorCollector<true>>(hc);
    }
    // treat hit vector as a heap
    std::make_heap(hc._hits.begin(), hc._hits.end(), ScoreComparator());
    hc._hitsSortOrder = SortOrder::HEAP;
    this->considerForHitVector(docId, score);
    hc._collector = std::move(newCollector);
}

template<bool CollectRankedHit>
void
HitCollector::DocIdCollector<CollectRankedHit>::collect(uint32_t docId, feature_t score)
{
    if (CollectRankedHit) {
        this->considerForHitVector(docId, score);
    }
    HitCollector & hc = this->_hc;
    if (hc._docIdVector.size() < hc._maxDocIdVectorSize) {
        if (__builtin_expect(((hc._docIdVector.size() > 0) &&
                              (docId < hc._docIdVector.back()) &&
                              (hc._unordered == false)), false))
        {
            hc._unordered = true;
        }
        hc._docIdVector.push_back(docId);
    } else {
        collectAndChangeCollector(docId);
    }
}

template<bool CollectRankedHit>
void
HitCollector::DocIdCollector<CollectRankedHit>::collectAndChangeCollector(uint32_t docId)
{
    HitCollector & hc = this->_hc;
    // start using bit vector instead of docid array.
    hc._bitVector = BitVector::create(hc._numDocs);
    hc._bitVector->invalidateCachedCount();
    uint32_t iSize = static_cast<uint32_t>(hc._docIdVector.size());
    for (uint32_t i = 0; i < iSize; ++i) {
        hc._bitVector->setBit(hc._docIdVector[i]);
    }
    std::vector<uint32_t> emptyVector;
    emptyVector.swap(hc._docIdVector);
    hc._bitVector->setBit(docId);
    hc._collector = std::make_unique<BitVectorCollector<CollectRankedHit>>(hc); // note - self-destruct.
}

std::vector<feature_t>
HitCollector::getSortedHeapScores()
{
    std::vector<feature_t> scores;
    size_t scoresToReturn = std::min(_hits.size(), static_cast<size_t>(_maxReRankHitsSize));
    scores.reserve(scoresToReturn);
    sortHitsByScore(scoresToReturn);
    for (size_t i = 0; i < scoresToReturn; ++i) {
        scores.push_back(_hits[_scoreOrder[i]].second);
    }
    return scores;
}

std::vector<HitCollector::Hit>
HitCollector::getSortedHeapHits()
{
    std::vector<Hit> scores;
    size_t scoresToReturn = std::min(_hits.size(), static_cast<size_t>(_maxReRankHitsSize));
    scores.reserve(scoresToReturn);
    sortHitsByScore(scoresToReturn);
    for (size_t i = 0; i < scoresToReturn; ++i) {
        scores.push_back(_hits[_scoreOrder[i]]);
    }
    return scores;
}

size_t
HitCollector::reRank(DocumentScorer &scorer)
{
    return reRank(scorer, _maxReRankHitsSize);
}

size_t
HitCollector::reRank(DocumentScorer &scorer, size_t count)
{
    size_t hitsToReRank = std::min(_hits.size(), count);
    if (_hasReRanked || hitsToReRank == 0) {
        return 0;
    }
    sortHitsByScore(hitsToReRank);
    std::vector<Hit> hits;
    hits.reserve(hitsToReRank);
    for (size_t i(0); i < hitsToReRank; i++) {
        hits.push_back(_hits[_scoreOrder[i]]);
    }
    return reRank(scorer, std::move(hits));
}

size_t
HitCollector::reRank(DocumentScorer &scorer, std::vector<Hit> hits) {
    size_t hitsToReRank = hits.size();
    Scores &initScores = _ranges.first;
    Scores &finalScores = _ranges.second;
    initScores = Scores(hits.back().second, hits.front().second);
    finalScores = Scores(std::numeric_limits<feature_t>::max(),
                         -std::numeric_limits<feature_t>::max());

    std::sort(hits.begin(), hits.end()); // sort on docId
    for (auto &hit : hits) {
        hit.second = scorer.score(hit.first);
        finalScores.low = std::min(finalScores.low, hit.second);
        finalScores.high = std::max(finalScores.high, hit.second);
    }
    _reRankedHits = std::move(hits);
    _hasReRanked = true;
    return hitsToReRank;
}

std::pair<Scores, Scores>
HitCollector::getRanges() const
{
    return _ranges;
}

void
HitCollector::setRanges(const std::pair<Scores, Scores> &ranges)
{
    _ranges = ranges;
}

namespace {

void
mergeHitsIntoResultSet(const std::vector<HitCollector::Hit> &hits, ResultSet &result)
{
    RankedHit *rhIter = result.getArray();
    RankedHit *rhEnd = rhIter + result.getArrayUsed();
    for (const auto &hit : hits) {
        while (rhIter != rhEnd && rhIter->_docId != hit.first) {
            // just set the iterators right
            ++rhIter;
        }
        assert(rhIter != rhEnd); // the hits should be a subset of the hits in ranked hit array.
        rhIter->_rankValue = hit.second;
    }
}

}

std::unique_ptr<ResultSet>
HitCollector::getResultSet(HitRank default_value)
{
    Scores &initHeapScores = _ranges.first;
    Scores &finalHeapScores = _ranges.second;
    if (initHeapScores.low > finalHeapScores.low) {
        // scale and adjust the score according to the range
        // of the initial and final heap score values to avoid that
        // a score from the first phase is larger than finalHeapScores.low
        feature_t initRange = initHeapScores.high - initHeapScores.low;
        if (initRange < 1.0) initRange = 1.0f;
        feature_t finalRange = finalHeapScores.high - finalHeapScores.low;
        if (finalRange < 1.0) finalRange = 1.0f;
        _scale = finalRange / initRange;
        _adjust = initHeapScores.low * _scale - finalHeapScores.low;
        _needReScore = true;
    }

    // destroys the heap property or score sort order
    sortHitsByDocId();

    std::unique_ptr<ResultSet> rs(new ResultSet());
    if ( ! _collector->isDocIdCollector() ) {
        unsigned int iSize = _hits.size();
        rs->allocArray(iSize);
        RankedHit * rh = rs->getArray();
        if (_needReScore) {
            for (uint32_t i = 0; i < iSize; ++i) {
                rh[i]._docId = _hits[i].first;
                rh[i]._rankValue = getReScore(_hits[i].second);
            }
        } else {
            for (uint32_t i = 0; i < iSize; ++i) {
                rh[i]._docId = _hits[i].first;
                rh[i]._rankValue = _hits[i].second;
            }
        }
        rs->setArrayUsed(iSize);
    } else {
        if (_unordered) {
            std::sort(_docIdVector.begin(), _docIdVector.end());
        }
        unsigned int iSize = _hits.size();
        unsigned int jSize = _docIdVector.size();
        rs->allocArray(jSize);
        RankedHit * rh = rs->getArray();
        uint32_t i = 0;
        if (_needReScore) {
            for (uint32_t j = 0; j < jSize; ++j) {
                uint32_t docId = _docIdVector[j];
                rh[j]._docId = docId;
                if (i < iSize && docId == _hits[i].first) {
                    rh[j]._rankValue = getReScore(_hits[i].second);
                    ++i;
                } else {
                    rh[j]._rankValue = default_value;
                }
            }
        } else {
            for (uint32_t j = 0; j < jSize; ++j) {
                uint32_t docId = _docIdVector[j];
                rh[j]._docId = docId;
                if (i < iSize && docId == _hits[i].first) {
                    rh[j]._rankValue = _hits[i].second;
                    ++i;
                } else {
                    rh[j]._rankValue = default_value;
                }
            }
        }
        rs->setArrayUsed(jSize);
    }

    if (_hasReRanked) {
        mergeHitsIntoResultSet(_reRankedHits, *rs.get());
    }

    if (_bitVector != NULL) {
        rs->setBitOverflow(std::move(_bitVector));
    }

    return rs;
}

}
<|endoftext|>


<commit_before>// FRAGMENT(includes)
#include <iostream>
#include <seqan/graph_algorithms.h>
using namespace seqan;

// FRAGMENT(typedefs)
int main() {
	typedef Graph<Directed<> > TGraph;
	typedef VertexDescriptor<TGraph>::Type TVertexDescriptor;
	typedef EdgeDescriptor<TGraph>::Type TEdgeDescriptor;
	typedef Size<TGraph>::Type TSize;

// FRAGMENT(main-graph-construction)
	TSize numEdges = 14;
	TVertexDescriptor edges[] = {1,0, 0,4, 2,1, 4,1, 5,1, 6,2, 3,2, 2,3, 7,3, 5,4, 6,5, 5,6, 7,6, 7,7};
	TGraph g;
	addEdges(g, edges, numEdges);
	::std::cout << g << ::std::endl;

// FRAGMENT(vertex-map)
	String<char> nameMap;
	char names[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
	resizeVertexMap(g,nameMap, names);

// FRAGMENT(connected-components)
	String<unsigned int> component;
	strongly_connected_components(g, component);

// FRAGMENT(output-connected-components)
	::std::cout << "Strongly Connected Components: " << ::std::endl;
	typedef Iterator<TGraph, VertexIterator>::Type TVertexIterator;
	TVertexIterator it(g);
	while(!atEnd(it)) {
		::std::cout << "Vertex " << getProperty(nameMap, getValue(it)) << ": ";
		::std::cout << "Component = " << getProperty(component, getValue(it)) << ::std::endl;
		goNext(it);
    }
	return 0;
}
<commit_msg>dfs iterator added in connected components example<commit_after>// FRAGMENT(includes)
#include <iostream>
#include <seqan/graph_algorithms.h>
using namespace seqan;

// FRAGMENT(typedefs)
int main() {
	typedef Graph<Directed<> > TGraph;
	typedef VertexDescriptor<TGraph>::Type TVertexDescriptor;
	typedef EdgeDescriptor<TGraph>::Type TEdgeDescriptor;
	typedef Size<TGraph>::Type TSize;

// FRAGMENT(main-graph-construction)
	TSize numEdges = 14;
	TVertexDescriptor edges[] = {1,0, 0,4, 2,1, 4,1, 5,1, 6,2, 3,2, 2,3, 7,3, 5,4, 6,5, 5,6, 7,6, 7,7};
	TGraph g;
	addEdges(g, edges, numEdges);
	::std::cout << g << ::std::endl;

// FRAGMENT(vertex-map)
	String<char> nameMap;
	char names[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
	resizeVertexMap(g,nameMap, names);

// FRAGMENT(iterate-dfs)
    TVertexDescriptor start = 0;
    typedef Iterator<TGraph, DfsPreorder>::Type TDfsIterator;
    TDfsIterator dfsIt(g, start);

    ::std::cout << "Iterate from " << getProperty(nameMap, start) << " in depth-first-search ordering: ";
    while(!atEnd(dfsIt)) {
        ::std::cout << getProperty(nameMap, getValue(dfsIt)) << ", ";
        goNext(dfsIt);
    }
    ::std::cout << ::std::endl;

// FRAGMENT(connected-components)
	String<unsigned int> component;
	strongly_connected_components(g, component);

// FRAGMENT(output-connected-components)
	::std::cout << "Strongly Connected Components: " << ::std::endl;
	typedef Iterator<TGraph, VertexIterator>::Type TVertexIterator;
	TVertexIterator it(g);
	while(!atEnd(it)) {
		::std::cout << "Vertex " << getProperty(nameMap, getValue(it)) << ": ";
		::std::cout << "Component = " << getProperty(component, getValue(it)) << ::std::endl;
		goNext(it);
    }
	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dp_parceldesc.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:34:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "dp_parceldesc.hxx"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

using ::rtl::OUString;

namespace css = ::com::sun::star;
namespace dp_registry
{
namespace backend
{
namespace sfwk
{

// XDocumentHandler
void SAL_CALL
ParcelDescDocHandler::startDocument()
throw ( xml::sax::SAXException, RuntimeException )
{
    m_bIsParsed = false;
}

void SAL_CALL
ParcelDescDocHandler::endDocument()
throw ( xml::sax::SAXException, RuntimeException )
{
    m_bIsParsed = true;
}

void SAL_CALL
ParcelDescDocHandler::characters( const OUString & aChars )
    throw ( xml::sax::SAXException, RuntimeException )
{
}

void SAL_CALL
ParcelDescDocHandler::ignorableWhitespace( const OUString & aWhitespaces )
    throw ( xml::sax::SAXException, RuntimeException )
{
}

void SAL_CALL
ParcelDescDocHandler::processingInstruction(
    const OUString & aTarget, const OUString & aData )
        throw ( xml::sax::SAXException, RuntimeException )
{
}

void SAL_CALL
ParcelDescDocHandler::setDocumentLocator(
    const Reference< xml::sax::XLocator >& xLocator )
        throw ( xml::sax::SAXException, RuntimeException )
{
}

void SAL_CALL
ParcelDescDocHandler::startElement( const OUString& aName,
    const Reference< xml::sax::XAttributeList > & xAttribs )
        throw ( xml::sax::SAXException,
            RuntimeException )
{
    OSL_TRACE("ParcelDescDocHandler::startElement() for %s",
        rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
    if ( !skipIndex )
    {
        if ( aName.equals( OUString::createFromAscii( "parcel" ) ) )
        {
            m_sLang = xAttribs->getValueByName( OUString::createFromAscii( "language" ) );
        }
        ++skipIndex;
    }
    else
    {
        OSL_TRACE("ParcelDescDocHandler::startElement() skipping for %s",
            rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
    }

}

void SAL_CALL ParcelDescDocHandler::endElement( const OUString & aName )
   throw ( xml::sax::SAXException, RuntimeException )
{
    if ( skipIndex )
    {
        --skipIndex;
        OSL_TRACE("ParcelDescDocHandler::endElement() skipping for %s",
            rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
    }
}

}
}
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.4.222); FILE MERGED 2006/09/01 17:25:15 kaib 1.4.222.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dp_parceldesc.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 09:44:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_parceldesc.hxx"

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

using ::rtl::OUString;

namespace css = ::com::sun::star;
namespace dp_registry
{
namespace backend
{
namespace sfwk
{

// XDocumentHandler
void SAL_CALL
ParcelDescDocHandler::startDocument()
throw ( xml::sax::SAXException, RuntimeException )
{
    m_bIsParsed = false;
}

void SAL_CALL
ParcelDescDocHandler::endDocument()
throw ( xml::sax::SAXException, RuntimeException )
{
    m_bIsParsed = true;
}

void SAL_CALL
ParcelDescDocHandler::characters( const OUString & aChars )
    throw ( xml::sax::SAXException, RuntimeException )
{
}

void SAL_CALL
ParcelDescDocHandler::ignorableWhitespace( const OUString & aWhitespaces )
    throw ( xml::sax::SAXException, RuntimeException )
{
}

void SAL_CALL
ParcelDescDocHandler::processingInstruction(
    const OUString & aTarget, const OUString & aData )
        throw ( xml::sax::SAXException, RuntimeException )
{
}

void SAL_CALL
ParcelDescDocHandler::setDocumentLocator(
    const Reference< xml::sax::XLocator >& xLocator )
        throw ( xml::sax::SAXException, RuntimeException )
{
}

void SAL_CALL
ParcelDescDocHandler::startElement( const OUString& aName,
    const Reference< xml::sax::XAttributeList > & xAttribs )
        throw ( xml::sax::SAXException,
            RuntimeException )
{
    OSL_TRACE("ParcelDescDocHandler::startElement() for %s",
        rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
    if ( !skipIndex )
    {
        if ( aName.equals( OUString::createFromAscii( "parcel" ) ) )
        {
            m_sLang = xAttribs->getValueByName( OUString::createFromAscii( "language" ) );
        }
        ++skipIndex;
    }
    else
    {
        OSL_TRACE("ParcelDescDocHandler::startElement() skipping for %s",
            rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
    }

}

void SAL_CALL ParcelDescDocHandler::endElement( const OUString & aName )
   throw ( xml::sax::SAXException, RuntimeException )
{
    if ( skipIndex )
    {
        --skipIndex;
        OSL_TRACE("ParcelDescDocHandler::endElement() skipping for %s",
            rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
    }
}

}
}
}

<|endoftext|>


<commit_before>/*! \file MemoryRaceDetector.cpp
	\date Wednesday March 24, 2010
	\author Gregory Diamos <gregory.diamos@gatech.edu>
	\brief The source file for the MemoryRaceDetector class.
*/

#ifndef MEMORY_RACE_DETECTOR_CPP_INCLUDED
#define MEMORY_RACE_DETECTOR_CPP_INCLUDED

// Ocelot includes
#include <ocelot/trace/interface/MemoryRaceDetector.h>
#include <ocelot/trace/interface/TraceEvent.h>
#include <ocelot/executive/interface/EmulatedKernel.h>
#include <ocelot/executive/interface/Device.h>

// hydrazine includes
#include <hydrazine/implementation/Exception.h>
#include <hydrazine/implementation/debug.h>

namespace trace
{
	static std::string prefix( unsigned int thread, const ir::Dim3& dim,
		const TraceEvent& e )
	{
		const unsigned int cta = e.blockId.x + e.blockId.y * dim.x
			+ dim.x * dim.y * e.blockId.z;

		std::stringstream stream;
		stream << "[PC " << e.PC << "] ";
		stream << "[thread " << thread << "] ";
		stream << "[cta " << cta << "] ";
		stream << e.instruction->toString() << " - ";

		return stream.str();
	}

	void MemoryRaceDetector::_write( const TraceEvent& event )
	{
		TraceEvent::U64Vector::const_iterator
			address = event.memory_addresses.begin();
		int threads = event.active.size();
		for( int thread = 0; thread < threads; ++thread )
		{
			if( !event.active[ thread ] ) continue;
			for( ir::PTXU64 byte = *address;
				byte < *address + event.memory_size; ++byte )
			{
				if( _writers[ byte ] != -1 && _writers[ byte ] != thread )
				{
					std::stringstream stream;
					stream << prefix( thread, _dim, event );
					stream << "Shared memory race condition, address "
						<< (void*)byte << " was previously written by thread "
						<< _writers[ byte ]
						<< " without a memory barrier in between.";
					stream << "\n";
					stream << "Near " << _kernel->location( event.PC ) << "\n";
					throw hydrazine::Exception( stream.str() );
				}
				else if( _readers[ byte ] != -1 && _readers[ byte ] != thread )
				{
					std::stringstream stream;
					stream << prefix( thread, _dim, event );
					stream << "Shared memory race condition, address "
						<< (void*)byte << " was previously read by thread "
						<< _readers[ byte ]
						<< " without a memory barrier in between.";
					stream << "\n";
					stream << "Near " << _kernel->location( event.PC ) << "\n";
					throw hydrazine::Exception( stream.str() );
				}
				else
				{
					_writers[ byte ] = thread;
				}
			}
			++address;
		}
	}

	void MemoryRaceDetector::_read( const TraceEvent& event )
	{
		TraceEvent::U64Vector::const_iterator
			address = event.memory_addresses.begin();
		int threads = event.active.size();
		for( int thread = 0; thread < threads; ++thread )
		{
			if( !event.active[ thread ] ) continue;
			for( ir::PTXU64 byte = *address;
				byte < *address + event.memory_size; ++byte )
			{
				if( _writers[ byte ] != -1 && _writers[ byte ] != thread )
				{
					std::stringstream stream;
					stream << prefix( thread, _dim, event );
					stream << "Shared memory race condition, address "
						<< (void*)byte << " was previously written by thread "
						<< _writers[byte]
						<< " without a memory barrier in between.";
					stream << "\n";
					stream << "Near " << _kernel->location( event.PC ) << "\n";
					throw hydrazine::Exception( stream.str() );
				}
				else
				{
					_readers[ byte ] = thread;
				}
			}
			++address;
		}
	}

	void MemoryRaceDetector::_barrier()
	{
		_writers.assign( _writers.size(), -1 );
		_readers.assign( _readers.size(), -1 );
	}

	MemoryRaceDetector::MemoryRaceDetector()
	{

	}

	void MemoryRaceDetector::initialize(
		const executive::ExecutableKernel& kernel )
	{
		_dim = kernel.blockDim();

		_writers.assign( kernel.totalSharedMemorySize(), -1 );
		_readers.assign( kernel.totalSharedMemorySize(), -1 );

		_kernel = static_cast< const executive::EmulatedKernel* >( &kernel );
	}

	void MemoryRaceDetector::event( const TraceEvent& event )
	{
		if( event.instruction->addressSpace == ir::PTXInstruction::Shared )
		{
			report( "Checking instruction " << event.instruction->toString() );
			if( event.instruction->opcode == ir::PTXInstruction::Ld )
			{
				_read( event );
			}
			else if( event.instruction->opcode == ir::PTXInstruction::St )
			{
				_write( event );
			}
		}
		else if( event.instruction->opcode == ir::PTXInstruction::Bar )
		{
			_barrier();
		}
	}

	void MemoryRaceDetector::finish()
	{

	}
}

#endif

<commit_msg>BUG: Potential bug in the race detector.  Conflicting writes to shared memory across cta boundaries are not actually errors.<commit_after>/*! \file MemoryRaceDetector.cpp
	\date Wednesday March 24, 2010
	\author Gregory Diamos <gregory.diamos@gatech.edu>
	\brief The source file for the MemoryRaceDetector class.
*/

#ifndef MEMORY_RACE_DETECTOR_CPP_INCLUDED
#define MEMORY_RACE_DETECTOR_CPP_INCLUDED

// Ocelot includes
#include <ocelot/trace/interface/MemoryRaceDetector.h>
#include <ocelot/trace/interface/TraceEvent.h>
#include <ocelot/executive/interface/EmulatedKernel.h>
#include <ocelot/executive/interface/Device.h>

// hydrazine includes
#include <hydrazine/implementation/Exception.h>
#include <hydrazine/implementation/debug.h>

namespace trace
{
	static std::string prefix( unsigned int thread, const ir::Dim3& dim,
		const TraceEvent& e )
	{
		const unsigned int cta = e.blockId.x + e.blockId.y * dim.x
			+ dim.x * dim.y * e.blockId.z;

		std::stringstream stream;
		stream << "[PC " << e.PC << "] ";
		stream << "[thread " << thread << "] ";
		stream << "[cta " << cta << "] ";
		stream << e.instruction->toString() << " - ";

		return stream.str();
	}

	void MemoryRaceDetector::_write( const TraceEvent& event )
	{
		TraceEvent::U64Vector::const_iterator
			address = event.memory_addresses.begin();
		int threads = event.active.size();
		for( int thread = 0; thread < threads; ++thread )
		{
			if( !event.active[ thread ] ) continue;
			for( ir::PTXU64 byte = *address;
				byte < *address + event.memory_size; ++byte )
			{
				if( _writers[ byte ] != -1 && _writers[ byte ] != thread )
				{
					std::stringstream stream;
					stream << prefix( thread, _dim, event );
					stream << "Shared memory race condition, address "
						<< (void*)byte << " was previously written by thread "
						<< _writers[ byte ]
						<< " without a memory barrier in between.";
					stream << "\n";
					stream << "Near " << _kernel->location( event.PC ) << "\n";
					throw hydrazine::Exception( stream.str() );
				}
				else if( _readers[ byte ] != -1 && _readers[ byte ] != thread )
				{
					std::stringstream stream;
					stream << prefix( thread, _dim, event );
					stream << "Shared memory race condition, address "
						<< (void*)byte << " was previously read by thread "
						<< _readers[ byte ]
						<< " without a memory barrier in between.";
					stream << "\n";
					stream << "Near " << _kernel->location( event.PC ) << "\n";
					throw hydrazine::Exception( stream.str() );
				}
				else
				{
					_writers[ byte ] = thread;
				}
			}
			++address;
		}
	}

	void MemoryRaceDetector::_read( const TraceEvent& event )
	{
		TraceEvent::U64Vector::const_iterator
			address = event.memory_addresses.begin();
		int threads = event.active.size();
		for( int thread = 0; thread < threads; ++thread )
		{
			if( !event.active[ thread ] ) continue;
			for( ir::PTXU64 byte = *address;
				byte < *address + event.memory_size; ++byte )
			{
				if( _writers[ byte ] != -1 && _writers[ byte ] != thread )
				{
					std::stringstream stream;
					stream << prefix( thread, _dim, event );
					stream << "Shared memory race condition, address "
						<< (void*)byte << " was previously written by thread "
						<< _writers[byte]
						<< " without a memory barrier in between.";
					stream << "\n";
					stream << "Near " << _kernel->location( event.PC ) << "\n";
					throw hydrazine::Exception( stream.str() );
				}
				else
				{
					_readers[ byte ] = thread;
				}
			}
			++address;
		}
	}

	void MemoryRaceDetector::_barrier()
	{
		_writers.assign( _writers.size(), -1 );
		_readers.assign( _readers.size(), -1 );
	}

	MemoryRaceDetector::MemoryRaceDetector()
	{

	}

	void MemoryRaceDetector::initialize(
		const executive::ExecutableKernel& kernel )
	{
		_dim = kernel.blockDim();

		_writers.assign( kernel.totalSharedMemorySize(), -1 );
		_readers.assign( kernel.totalSharedMemorySize(), -1 );

		_kernel = static_cast< const executive::EmulatedKernel* >( &kernel );
	}

	void MemoryRaceDetector::event( const TraceEvent& event )
	{
		if( event.instruction->addressSpace == ir::PTXInstruction::Shared )
		{
			report( "Checking instruction " << event.instruction->toString() );
			if( event.instruction->opcode == ir::PTXInstruction::Ld )
			{
				_read( event );
			}
			else if( event.instruction->opcode == ir::PTXInstruction::St )
			{
				_write( event );
			}
		}
		else if( event.instruction->opcode == ir::PTXInstruction::Bar
			|| event.instruction->opcode == ir::PTXInstruction::Exit )
		{
			_barrier();
		}
	}

	void MemoryRaceDetector::finish()
	{

	}
}

#endif

<|endoftext|>


<commit_before>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#pragma once

#include "aliceVision/feature/RegionsPerView.hpp"
#include "aliceVision/matching/IndMatch.hpp"
#include "aliceVision/matchingImageCollection/GeometricFilterMatrix.hpp"
#include "aliceVision/matchingImageCollection/geometricFilterUtils.hpp"
#include "aliceVision/sfm/SfMData.hpp"

#include <Eigen/Geometry>
#include <boost/filesystem.hpp>

#include <cmath>

namespace aliceVision {
namespace matchingImageCollection {

struct GrowParameters
{
    GrowParameters() = default;

    GrowParameters(double similarityTolerance,
                   double affinityTolerance,
                   double homographyTolerance,
                   std::size_t minInliersToRefine,
                   std::size_t nbRefiningIterations,
                   double maxFractionPlanarMatches)
            : _similarityTolerance(similarityTolerance),
              _affinityTolerance(affinityTolerance),
              _homographyTolerance(homographyTolerance),
              _minInliersToRefine(minInliersToRefine),
              _nbRefiningIterations(nbRefiningIterations),
              _maxFractionPlanarMatches(maxFractionPlanarMatches)
    {
      assert(_maxFractionPlanarMatches >= 0 && _maxFractionPlanarMatches <= 1);
    }

    /// The maximal reprojection (pixel) error for matches estimated
    /// from a Similarity transformation.
    double _similarityTolerance{20};

    /// The maximal reprojection (pixel) error for matches estimated
    /// from an Affine transformation.
    double _affinityTolerance{10};

    /// The maximal reprojection (pixel) error for matches estimated
    /// from a Homography.
    double _homographyTolerance{5};

    /// Minimum number of inliers to continue in further refining.
    std::size_t _minInliersToRefine{6};

    /// Number of refine iterations that should be done to a transformation.
    /// 1st iteration is estimated using key coordinates, scale and orientation.
    /// 2-4th iterations are affinities
    /// 5+th iterations are homographies
    std::size_t _nbRefiningIterations{8};

    /// Value in [0,1]. If there is this fraction of inliers found the
    /// refine phase is terminated.
    double _maxFractionPlanarMatches{0.7};
};

bool growHomography(const std::vector<feature::SIOPointFeature> &featuresI,
                    const std::vector<feature::SIOPointFeature> &featuresJ,
                    const matching::IndMatches &matches,
                    const IndexT &seedMatchId,
                    std::set<IndexT> &planarMatchesIndices, Mat3 &transformation,
                    const GrowParameters& param);

struct HGrowingFilteringParam
{
    HGrowingFilteringParam() = default;
    HGrowingFilteringParam(std::size_t maxNbHomographies, std::size_t minNbMatchesPerH, const GrowParameters& growParam)
            : _maxNbHomographies(maxNbHomographies),
              _minNbMatchesPerH(minNbMatchesPerH),
              _growParam(growParam) {} ;

    /// Max. number of homographies to estimate.
    std::size_t _maxNbHomographies{10};

    /// Min. number of matches corresponding to a homography.
    /// The homography-growing is interrupted when the value is reached.
    std::size_t _minNbMatchesPerH{20};

    /// Parameters for the growing algorithm
    GrowParameters _growParam{};
};

void filterMatchesByHGrowing(const std::vector<feature::SIOPointFeature>& siofeatures_I,
                             const std::vector<feature::SIOPointFeature>& siofeatures_J,
                             const matching::IndMatches& putativeMatches,
                             std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches,
                             matching::IndMatches& outGeometricInliers,
                             const HGrowingFilteringParam& param);

void drawHomographyMatches(const std::string& outFilename,
                      const sfm::View & viewI,
                      const sfm::View & viewJ,
                      const std::vector<feature::SIOPointFeature>& siofeatures_I,
                      const std::vector<feature::SIOPointFeature>& siofeatures_J,
                      const std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches,
                      const matching::IndMatches& putativeMatches);
//-- Multiple homography matrices estimation template functor, based on homography growing, used for filter pair of putative correspondences
struct GeometricFilterMatrix_HGrowing : public GeometricFilterMatrix
{
    explicit GeometricFilterMatrix_HGrowing(
          double dPrecision = std::numeric_limits<double>::infinity(),
          size_t iteration = 1024)
              : GeometricFilterMatrix(dPrecision, std::numeric_limits<double>::infinity(), iteration)
  { }

  /**
   * @brief Given two sets of image points, it estimates the homography matrix
   * relating them using a robust method (like A Contrario Ransac).
   * @details It return matches grouped by estimated homographies.
   * Example:
   * - Putative matches id:         [0 1 2 3 4 5 6 7]
   * - Estimated homographies:      [0(h0) 1(h2) 2(h1) 3(nan) 4(h2) 5(h0) 6(h1) 7(nan)]
   * - Sorted matches               [0(h0) 5(h0) 2(h1) 6(h1) 1(h2) 4(h2)]
   * - out_geometricInliersPerType  [0 5 2 6 1 4]
   */
  template<typename Regions_or_Features_ProviderT>
  EstimationStatus geometricEstimation(const sfm::SfMData * sfmData,
                                       const Regions_or_Features_ProviderT &regionsPerView,
                                       const Pair &pairIndex,
                                       const matching::MatchesPerDescType &putativeMatchesPerType,
                                       matching::MatchesPerDescType &out_geometricInliersPerType)
  {
    using namespace aliceVision::feature;
    using namespace aliceVision::matching;

    out_geometricInliersPerType.clear();

    // ------------------------
    // To draw & save matches groups into .svg images:
    //    enter an existing folder in the following variable ('outputSvgDir').
    // File format: <nbHMatches>hmatches_<viewId_I>_<viewId_J>_<descType>.svg
    // * Little white dots = putative matches
    // * Colored dots = geometrically verified matches (1 color per estimated plane)
    std::string outputSvgDir;
    // ------------------------

    const std::vector<feature::EImageDescriberType> descTypes = regionsPerView.getCommonDescTypes(pairIndex);
    if(descTypes.empty())
      return EstimationStatus(false, false);

#if ALICEVISION_IS_DEFINED(ALICEVISION_HAVE_CCTAG)
    if (std::find(descTypes.begin(), descTypes.end(),feature::EImageDescriberType::CCTAG3) != descTypes.end() ||
        std::find(descTypes.begin(), descTypes.end(),feature::EImageDescriberType::CCTAG4) != descTypes.end())
    {
      ALICEVISION_LOG_ERROR("Geometric filtering by Homography Growing cannot handle CCTAG descriptors.");
      return EstimationStatus(false, false);
    }
#endif

    // Get back corresponding view index
    const IndexT viewId_I = pairIndex.first;
    const IndexT viewId_J = pairIndex.second;

    const sfm::View & viewI = *(sfmData->GetViews().at(viewId_I));
    const sfm::View & viewJ = *(sfmData->GetViews().at(viewId_J));

    for (const EImageDescriberType& descType : descTypes)
    {
      if(!putativeMatchesPerType.count(descType))
      {
        continue;
      } // we may have 0 feature for some descriptor types

      const Regions & regions_I = regionsPerView.getRegions(viewId_I, descType);
      const Regions & regions_J = regionsPerView.getRegions(viewId_J, descType);
      const std::vector<SIOPointFeature>& siofeatures_I = getSIOPointFeatures(regions_I);
      const std::vector<SIOPointFeature>& siofeatures_J = getSIOPointFeatures(regions_J);

      std::vector<std::pair<Mat3, matching::IndMatches>> homographiesAndMatches;
      matching::IndMatches outGeometricInliers;
      filterMatchesByHGrowing(siofeatures_I,
                              siofeatures_J,
                              putativeMatchesPerType.at(descType),
                              homographiesAndMatches,
                              outGeometricInliers,
                              _parameters);

      out_geometricInliersPerType.emplace(descType, outGeometricInliers);
      _HsAndMatchesPerDesc.emplace(descType, homographiesAndMatches);

      if (outputSvgDir.empty())
      {
        continue;
      }

      if (boost::filesystem::exists(outputSvgDir))
      {
        const std::size_t nbMatches = outGeometricInliers.size();
        const std::string name = std::to_string(nbMatches) + "hmatches_" + std::to_string(viewI.getViewId()) + "_" +
                                 std::to_string(viewJ.getViewId()) +
                                 "_" + EImageDescriberType_enumToString(descType) + ".svg";
        // @FIXME not worth it having boost::filesystem in a header
        const std::string outFilename = (boost::filesystem::path(outputSvgDir) / boost::filesystem::path(name)).string();
        drawHomographyMatches(outFilename,
                              viewI,
                              viewJ,
                              siofeatures_I,
                              siofeatures_J,
                              homographiesAndMatches,
                              putativeMatchesPerType.at(descType));
      }
      else
      {
        ALICEVISION_LOG_WARNING("Cannot save homography-growing matches into '" << outputSvgDir << "': folder does not exist.");
      }

    } // 'descriptor'

    // Check if resection has strong support
    if (out_geometricInliersPerType.empty())
      return EstimationStatus(true, false);
    else
      return EstimationStatus(true, true);
  }

  /**
   * @brief Geometry_guided_matching
   * @param sfm_data
   * @param regionsPerView
   * @param pairIndex
   * @param dDistanceRatio
   * @param matches
   * @return
   */
  bool Geometry_guided_matching(const sfm::SfMData *sfmData,
                                const feature::RegionsPerView &regionsPerView,
                                const Pair imageIdsPair,
                                const double dDistanceRatio,
                                matching::MatchesPerDescType &matches) override
  {

    /* ... */
    return matches.getNbAllMatches() != 0;
  }

  /**
   * @brief Get the number of descriptor types including verified matches by the
   * homography growing method.
   * @return The number of descriptor types
   */
  inline std::size_t getNbDescTypes() const {return _HsAndMatchesPerDesc.size();}

  /**
   * @brief The number of estimated homographies for the given descriptor.
   * @param[in] descType The wished descriptor type
   * @return The number of estimated homographies (= planes). Return 0 if there is
   * no homography or if the descriptor type does not exist.
   */
  std::size_t getNbHomographies(const feature::EImageDescriberType & descType) const;

  /**
   * @brief Get the number of matches associated to the given descriptor type & homography index.
   * @param[in] descType Descriptor type.
   * @param[in] homographyId The id. of the wished homography / plane.
   * @return The number of matches. Return 0 if the descriptor type or the homography
   * index do not exist in the result.
   */
  std::size_t getNbVerifiedMatches(const feature::EImageDescriberType & descType, IndexT homographyId) const;

  /**
   * @brief Get the number of verified matches for every descriptor and associated homographies.
   * @return The nb of verified matches
   */
  std::size_t getNbAllVerifiedMatches() const;

  /**
   * @brief Get a copy of the matches for a given desc. type & homography index.
   * @param[in] descType The descriptor type.
   * @param[in] homographyId The id. of the wished homography / plane.
   * @param[in] matches Contains the matches.
   * @return true the number of matches is up to 0.
   */
  bool getMatches(const feature::EImageDescriberType & descType, const IndexT homographyId, matching::IndMatches & matches) const;

private:

  // -- Results container

  /// The estimated homographies and their associated planar matches,
  /// for each descriptor type.
  std::map<feature::EImageDescriberType, std::vector<std::pair<Mat3, matching::IndMatches>>>
  _HsAndMatchesPerDesc;

  //-- Parameters
  HGrowingFilteringParam _parameters{};

}; // struct GeometricFilterMatrix_HGrowing

} // namespace matchingImageCollection
} // namespace aliceVision

<commit_msg>[matchingImageCollection] add doc<commit_after>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

#pragma once

#include "aliceVision/feature/RegionsPerView.hpp"
#include "aliceVision/matching/IndMatch.hpp"
#include "aliceVision/matchingImageCollection/GeometricFilterMatrix.hpp"
#include "aliceVision/matchingImageCollection/geometricFilterUtils.hpp"
#include "aliceVision/sfm/SfMData.hpp"

#include <Eigen/Geometry>
#include <boost/filesystem.hpp>

#include <cmath>

namespace aliceVision {
namespace matchingImageCollection {

struct GrowParameters
{
    GrowParameters() = default;

    GrowParameters(double similarityTolerance,
                   double affinityTolerance,
                   double homographyTolerance,
                   std::size_t minInliersToRefine,
                   std::size_t nbRefiningIterations,
                   double maxFractionPlanarMatches)
            : _similarityTolerance(similarityTolerance),
              _affinityTolerance(affinityTolerance),
              _homographyTolerance(homographyTolerance),
              _minInliersToRefine(minInliersToRefine),
              _nbRefiningIterations(nbRefiningIterations),
              _maxFractionPlanarMatches(maxFractionPlanarMatches)
    {
      assert(_maxFractionPlanarMatches >= 0 && _maxFractionPlanarMatches <= 1);
    }

    /// The maximal reprojection (pixel) error for matches estimated
    /// from a Similarity transformation.
    double _similarityTolerance{20};

    /// The maximal reprojection (pixel) error for matches estimated
    /// from an Affine transformation.
    double _affinityTolerance{10};

    /// The maximal reprojection (pixel) error for matches estimated
    /// from a Homography.
    double _homographyTolerance{5};

    /// Minimum number of inliers to continue in further refining.
    std::size_t _minInliersToRefine{6};

    /// Number of refine iterations that should be done to a transformation.
    /// 1st iteration is estimated using key coordinates, scale and orientation.
    /// 2-4th iterations are affinities
    /// 5+th iterations are homographies
    std::size_t _nbRefiningIterations{8};

    /// Value in [0,1]. If there is this fraction of inliers found the
    /// refine phase is terminated.
    double _maxFractionPlanarMatches{0.7};
};

/**
 * @brief Return all the matches in the same plane as the match \c seedMatchId with the corresponding homography.
 * @details This algorithm is detailed in [F.Srajer, 2016] algo. 1, p. 20.
 * @param[in] featuresI The features of the first view.
 * @param[in] featuresJ The features of the second view.
 * @param[in] matches All the putative planar matches.
 * @param[in] seedMatchId The match used to estimate the plane and the corresponding matches.
 * @param[out] planarMatchesIndices The indices (in the \c matches vector) of the really planar matches.
 * @param[out] transformation The homography associated to the plane.
 * @param[in] param The parameters of the algorihm.
 * @return true if the \c transformation is different than the identity matrix.
 */
bool growHomography(const std::vector<feature::SIOPointFeature> &featuresI,
                    const std::vector<feature::SIOPointFeature> &featuresJ,
                    const matching::IndMatches &matches,
                    const IndexT &seedMatchId,
                    std::set<IndexT> &planarMatchesIndices,
                    Mat3 &transformation,
                    const GrowParameters& param);

struct HGrowingFilteringParam
{
    HGrowingFilteringParam() = default;
    HGrowingFilteringParam(std::size_t maxNbHomographies, std::size_t minNbMatchesPerH, const GrowParameters& growParam)
            : _maxNbHomographies(maxNbHomographies),
              _minNbMatchesPerH(minNbMatchesPerH),
              _growParam(growParam) {} ;

    /// Max. number of homographies to estimate.
    std::size_t _maxNbHomographies{10};

    /// Min. number of matches corresponding to a homography.
    /// The homography-growing is interrupted when the value is reached.
    std::size_t _minNbMatchesPerH{20};

    /// Parameters for the growing algorithm
    GrowParameters _growParam{};
};

/**
 * @brief Filter the matches between two images using a growing homography approach.
 * @param[in] featuresI The features of the first view.
 * @param[in] featuresJ The features of the second view.
 * @param[in] putativeMatches The putative matches.
 * @param[out] homographiesAndMatches Contains each found homography and the relevant supporting matches.
 * @param[out] outGeometricInliers All the matches that supports one of the found homographies.
 * @param[in] param The parameters of the algorithm.
 */
void filterMatchesByHGrowing(const std::vector<feature::SIOPointFeature>& siofeatures_I,
                             const std::vector<feature::SIOPointFeature>& siofeatures_J,
                             const matching::IndMatches& putativeMatches,
                             std::vector<std::pair<Mat3,
                             matching::IndMatches>>& homographiesAndMatches,
                             matching::IndMatches& outGeometricInliers,
                             const HGrowingFilteringParam& param);

/**
 * @brief Generate a svg file with the two images and the matches grouped in different color
 * according to their supporting homography.
 * @param[in] outFilename The filename of the svg file to generate.
 * @param[in] viewI The first view.
 * @param[in] viewJ The second view.
 * @param[in] featuresI The features of the first view.
 * @param[in] featuresJ The features of the second view.
 * @param[in] homographiesAndMatches Contains each found homography and the relevant supporting matches.
 * @param[in] putativeMatches The putative matches.
 */
void drawHomographyMatches(const std::string& outFilename,
                      const sfm::View & viewI,
                      const sfm::View & viewJ,
                      const std::vector<feature::SIOPointFeature>& siofeatures_I,
                      const std::vector<feature::SIOPointFeature>& siofeatures_J,
                      const std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches,
                      const matching::IndMatches& putativeMatches);

//-- Multiple homography matrices estimation template functor, based on homography growing, used for filter pair of putative correspondences
struct GeometricFilterMatrix_HGrowing : public GeometricFilterMatrix
{
    explicit GeometricFilterMatrix_HGrowing(
          double dPrecision = std::numeric_limits<double>::infinity(),
          size_t iteration = 1024)
              : GeometricFilterMatrix(dPrecision, std::numeric_limits<double>::infinity(), iteration)
  { }

  /**
   * @brief Given two sets of image points, it estimates the homography matrix
   * relating them using a robust method (like A Contrario Ransac).
   * @details It return matches grouped by estimated homographies.
   * Example:
   * - Putative matches id:         [0 1 2 3 4 5 6 7]
   * - Estimated homographies:      [0(h0) 1(h2) 2(h1) 3(nan) 4(h2) 5(h0) 6(h1) 7(nan)]
   * - Sorted matches               [0(h0) 5(h0) 2(h1) 6(h1) 1(h2) 4(h2)]
   * - out_geometricInliersPerType  [0 5 2 6 1 4]
   */
  template<typename Regions_or_Features_ProviderT>
  EstimationStatus geometricEstimation(const sfm::SfMData * sfmData,
                                       const Regions_or_Features_ProviderT &regionsPerView,
                                       const Pair &pairIndex,
                                       const matching::MatchesPerDescType &putativeMatchesPerType,
                                       matching::MatchesPerDescType &out_geometricInliersPerType)
  {
    using namespace aliceVision::feature;
    using namespace aliceVision::matching;

    out_geometricInliersPerType.clear();

    // ------------------------
    // To draw & save matches groups into .svg images:
    //    enter an existing folder in the following variable ('outputSvgDir').
    // File format: <nbHMatches>hmatches_<viewId_I>_<viewId_J>_<descType>.svg
    // * Little white dots = putative matches
    // * Colored dots = geometrically verified matches (1 color per estimated plane)
    std::string outputSvgDir;
    // ------------------------

    const std::vector<feature::EImageDescriberType> descTypes = regionsPerView.getCommonDescTypes(pairIndex);
    if(descTypes.empty())
      return EstimationStatus(false, false);

#if ALICEVISION_IS_DEFINED(ALICEVISION_HAVE_CCTAG)
    if (std::find(descTypes.begin(), descTypes.end(),feature::EImageDescriberType::CCTAG3) != descTypes.end() ||
        std::find(descTypes.begin(), descTypes.end(),feature::EImageDescriberType::CCTAG4) != descTypes.end())
    {
      ALICEVISION_LOG_ERROR("Geometric filtering by Homography Growing cannot handle CCTAG descriptors.");
      return EstimationStatus(false, false);
    }
#endif

    // Get back corresponding view index
    const IndexT viewId_I = pairIndex.first;
    const IndexT viewId_J = pairIndex.second;

    const sfm::View & viewI = *(sfmData->GetViews().at(viewId_I));
    const sfm::View & viewJ = *(sfmData->GetViews().at(viewId_J));

    for (const EImageDescriberType& descType : descTypes)
    {
      if(!putativeMatchesPerType.count(descType))
      {
        continue;
      } // we may have 0 feature for some descriptor types

      const Regions & regions_I = regionsPerView.getRegions(viewId_I, descType);
      const Regions & regions_J = regionsPerView.getRegions(viewId_J, descType);
      const std::vector<SIOPointFeature>& siofeatures_I = getSIOPointFeatures(regions_I);
      const std::vector<SIOPointFeature>& siofeatures_J = getSIOPointFeatures(regions_J);

      std::vector<std::pair<Mat3, matching::IndMatches>> homographiesAndMatches;
      matching::IndMatches outGeometricInliers;
      filterMatchesByHGrowing(siofeatures_I,
                              siofeatures_J,
                              putativeMatchesPerType.at(descType),
                              homographiesAndMatches,
                              outGeometricInliers,
                              _parameters);

      out_geometricInliersPerType.emplace(descType, outGeometricInliers);
      _HsAndMatchesPerDesc.emplace(descType, homographiesAndMatches);

      if (outputSvgDir.empty())
      {
        continue;
      }

      if (boost::filesystem::exists(outputSvgDir))
      {
        const std::size_t nbMatches = outGeometricInliers.size();
        const std::string name = std::to_string(nbMatches) + "hmatches_" + std::to_string(viewI.getViewId()) + "_" +
                                 std::to_string(viewJ.getViewId()) +
                                 "_" + EImageDescriberType_enumToString(descType) + ".svg";
        // @FIXME not worth it having boost::filesystem in a header
        const std::string outFilename = (boost::filesystem::path(outputSvgDir) / boost::filesystem::path(name)).string();
        drawHomographyMatches(outFilename,
                              viewI,
                              viewJ,
                              siofeatures_I,
                              siofeatures_J,
                              homographiesAndMatches,
                              putativeMatchesPerType.at(descType));
      }
      else
      {
        ALICEVISION_LOG_WARNING("Cannot save homography-growing matches into '" << outputSvgDir << "': folder does not exist.");
      }

    } // 'descriptor'

    // Check if resection has strong support
    if (out_geometricInliersPerType.empty())
      return EstimationStatus(true, false);
    else
      return EstimationStatus(true, true);
  }

  /**
   * @brief Geometry_guided_matching
   * @param sfm_data
   * @param regionsPerView
   * @param pairIndex
   * @param dDistanceRatio
   * @param matches
   * @return
   */
  bool Geometry_guided_matching(const sfm::SfMData *sfmData,
                                const feature::RegionsPerView &regionsPerView,
                                const Pair imageIdsPair,
                                const double dDistanceRatio,
                                matching::MatchesPerDescType &matches) override
  {

    /* ... */
    return matches.getNbAllMatches() != 0;
  }

  /**
   * @brief Get the number of descriptor types including verified matches by the
   * homography growing method.
   * @return The number of descriptor types
   */
  inline std::size_t getNbDescTypes() const {return _HsAndMatchesPerDesc.size();}

  /**
   * @brief The number of estimated homographies for the given descriptor.
   * @param[in] descType The wished descriptor type
   * @return The number of estimated homographies (= planes). Return 0 if there is
   * no homography or if the descriptor type does not exist.
   */
  std::size_t getNbHomographies(const feature::EImageDescriberType & descType) const;

  /**
   * @brief Get the number of matches associated to the given descriptor type & homography index.
   * @param[in] descType Descriptor type.
   * @param[in] homographyId The id. of the wished homography / plane.
   * @return The number of matches. Return 0 if the descriptor type or the homography
   * index do not exist in the result.
   */
  std::size_t getNbVerifiedMatches(const feature::EImageDescriberType & descType, IndexT homographyId) const;

  /**
   * @brief Get the number of verified matches for every descriptor and associated homographies.
   * @return The nb of verified matches
   */
  std::size_t getNbAllVerifiedMatches() const;

  /**
   * @brief Get a copy of the matches for a given desc. type & homography index.
   * @param[in] descType The descriptor type.
   * @param[in] homographyId The id. of the wished homography / plane.
   * @param[in] matches Contains the matches.
   * @return true the number of matches is up to 0.
   */
  bool getMatches(const feature::EImageDescriberType & descType, const IndexT homographyId, matching::IndMatches & matches) const;

private:

  // -- Results container

  /// The estimated homographies and their associated planar matches,
  /// for each descriptor type.
  std::map<feature::EImageDescriberType, std::vector<std::pair<Mat3, matching::IndMatches>>>
  _HsAndMatchesPerDesc;

  //-- Parameters
  HGrowingFilteringParam _parameters{};

}; // struct GeometricFilterMatrix_HGrowing

} // namespace matchingImageCollection
} // namespace aliceVision

<|endoftext|>


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

#include "modules/canbus/vehicle/gem/protocol/wheel_speed_rpt_7a.h"

#include "gtest/gtest.h"

namespace apollo {
namespace canbus {
namespace gem {

class Wheelspeedrpt7aTest : public ::testing::Test {
 public:
  virtual void SetUp() {}
};

TEST_F(Wheelspeedrpt7aTest, reset) {
  Wheelspeedrpt7a wheelspeed;
  int32_t length = 8;
  ChassisDetail chassis_detail;
  uint8_t bytes[8] = {0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14};

  wheelspeed.Parse(bytes, length, &chassis_detail);
  EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_rear_right(), 4884);
  EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_rear_left(), 4370);
  EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_front_right(), 772);
  EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a().wheel_spd_front_left(), 258);
}

}  // namespace gem
}  // namespace canbus
}  // namespace apollo

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

#include "modules/canbus/vehicle/gem/protocol/wheel_speed_rpt_7a.h"

#include "gtest/gtest.h"

namespace apollo {
namespace canbus {
namespace gem {

class Wheelspeedrpt7aTest : public ::testing::Test {
 public:
  virtual void SetUp() {}
};

TEST_F(Wheelspeedrpt7aTest, reset) {
  Wheelspeedrpt7a wheelspeed;
  int32_t length = 8;
  ChassisDetail chassis_detail;
  uint8_t bytes[8] = {0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14};
  wheelspeed.Parse(bytes, length, &chassis_detail);
  EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_rear_right(), 4884);
  EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_rear_left(), 4370);
  EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_front_right(), 772);
  EXPECT_DOUBLE_EQ(chassis_detail.gem().wheel_speed_rpt_7a()\
.wheel_spd_front_left(), 258);
}

}  // namespace gem
}  // namespace canbus
}  // namespace apollo

<|endoftext|>