<commit_before>#define NONIUS_RUNNER
#include <nonius/main.h++>

#include "../include/dict/dict.hpp"

#include <unordered_map>
#include <random>
#include <functional>

#ifdef WITH_GOOGLE_BENCH
#include <sparsehash/dense_hash_map>
#endif

template <typename Map>
void insert_test(Map& map) {
    for (int i = 0; i != 10000; ++i) {
        map[i] = i;
    }
}

NONIUS_BENCHMARK("dict insert", [](nonius::chronometer meter) {
    io::dict<int, int> d;
    d.reserve(1000);
    meter.measure([&] { insert_test(d); });
})

NONIUS_BENCHMARK("umap insert", [](nonius::chronometer meter) {
    std::unordered_map<int, int> d;
    d.reserve(1000);
    meter.measure([&] { insert_test(d); });
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google insert", [](nonius::chronometer meter) {
    google::dense_hash_map<int, int> d(1000);
    d.set_empty_key(0);
    meter.measure([&] { insert_test(d); });
})
#endif

#ifdef WITH_GOOGLE_BENCH
template <typename Map>
Map build_map_google(int size) {
    Map d;
    d.set_empty_key(0);

    for (int i = 0; i != size; ++i) {
        d[i] = i;
    }

    return d;
}

template <typename Map>
Map build_map_google_with_reserve(int size) {
    Map d(size);
    d.set_empty_key(0);

    for (int i = 0; i != size; ++i) {
        d[i] = i;
    }

    return d;
}
#endif

template <typename Map>
Map build_map(int size) {
    Map d;

    for (int i = 0; i != size; ++i) {
        d[i] = i;
    }

    return d;
}

template <typename Map>
Map build_map_with_reserve(int size) {
    Map d(size);

    for (int i = 0; i != size; ++i) {
        d[i] = i;
    }

    return d;
}

template <typename Map, typename Generator>
int lookup_test(Map& map, Generator& gen) {
    int res = 0;
    for (std::size_t i = 0; i < 100; i += 1) {
        res += map[gen()];
    }

    return res;
}

const int small_lookup_test_size = 10;

NONIUS_BENCHMARK("small dict lookup", [](nonius::chronometer meter) {
    auto d = build_map<io::dict<int, int>>(small_lookup_test_size);

    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

NONIUS_BENCHMARK("small umap lookup", [](nonius::chronometer meter) {
    auto d = build_map<std::unordered_map<int, int>>(small_lookup_test_size);

    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("small google lookup", [](nonius::chronometer meter) {
    auto d =
        build_map_google<google::dense_hash_map<int, int>>(small_lookup_test_size);

    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})
#endif

const int lookup_test_size = 1000000;

NONIUS_BENCHMARK("dict lookup", [](nonius::chronometer meter) {
    auto d = build_map<io::dict<int, int>>(lookup_test_size);

    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

NONIUS_BENCHMARK("umap lookup", [](nonius::chronometer meter) {
    auto d = build_map<std::unordered_map<int, int>>(lookup_test_size);

    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google lookup", [](nonius::chronometer meter) {
    auto d =
        build_map_google<google::dense_hash_map<int, int>>(lookup_test_size);

    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})
#endif

const int build_test_size = 1000;

NONIUS_BENCHMARK("dict build", [] {
    return build_map<io::dict<int, int>>(build_test_size);
})

NONIUS_BENCHMARK("umap build", [] {
    return build_map<std::unordered_map<int, int>>(build_test_size);
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build", [] {
    return build_map_google<google::dense_hash_map<int, int>>(build_test_size);
})
#endif

NONIUS_BENCHMARK("dict build with reserve", [] {
    return build_map_with_reserve<io::dict<int, int>>(build_test_size);
})

NONIUS_BENCHMARK("umap build with reserve", [] {
    return build_map_with_reserve<std::unordered_map<int, int>>(
        build_test_size);
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build with reserve", [] {
    return build_map_google<google::dense_hash_map<int, int>>(build_test_size);
})
#endif

template <typename Map>
Map build_string_map(int size) {
    Map d;

    for (int i = 0; i != size; ++i) {
        d[std::to_string(i) + std::to_string(i) + std::to_string(i) +
          std::to_string(i) + std::to_string(i) + std::to_string(i) +
          std::to_string(i)] = i;
    }

    return d;
}

#ifdef WITH_GOOGLE_BENCH
template <typename Map>
Map build_string_map_google(int size) {
    Map d;
    d.set_empty_key("");

    for (int i = 0; i != size; ++i) {
        d[std::to_string(i) + std::to_string(i) + std::to_string(i) +
          std::to_string(i) + std::to_string(i) + std::to_string(i) +
          std::to_string(i)] = i;
    }

    return d;
}
#endif

NONIUS_BENCHMARK("dict build with string key", [] {
    return build_string_map<io::dict<std::string, int>>(build_test_size);
})

NONIUS_BENCHMARK("umap build with string key", [] {
    return build_string_map<std::unordered_map<std::string, int>>(
        build_test_size);
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build with string key", [] {
    return build_string_map_google<google::dense_hash_map<std::string, int>>(
        build_test_size);
})
#endif

template <typename Map, typename LookUpKeys>
int string_lookup_test(Map& map, const LookUpKeys& keys) {
    int res = 0;
    for (auto&& k : keys) {
        res += map[k];
    }

    return res;
}

const int string_lookup_test_size = 1000;

NONIUS_BENCHMARK("dict string lookup", [](nonius::chronometer meter) {
    auto d = build_string_map<io::dict<std::string, int>>(
        string_lookup_test_size);
    std::vector<std::string> keys{ "1111111", "2222222", "3333333",
                                   "4444444", "5555555", "6666666",
                                   "7777777", "8888888", "9999999" };

    meter.measure([&] { return string_lookup_test(d, keys); });
})

NONIUS_BENCHMARK("umap string lookup", [](nonius::chronometer meter) {
    auto d = build_string_map<std::unordered_map<std::string, int>>(
        string_lookup_test_size);
    std::vector<std::string> keys{ "1111111", "2222222", "3333333",
                                   "4444444", "5555555", "6666666",
                                   "7777777", "8888888", "9999999" };

    meter.measure([&] { return string_lookup_test(d, keys); });
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google string lookup", [](nonius::chronometer meter) {
    auto d = build_string_map_google<google::dense_hash_map<std::string, int>>(
        string_lookup_test_size);
    std::vector<std::string> keys{ "1111111", "2222222", "3333333",
                                   "4444444", "5555555", "6666666",
                                   "7777777", "8888888", "9999999" };

    meter.measure([&] { return string_lookup_test(d, keys); });
})
#endif
<commit_msg>added more performance tests<commit_after>#define NONIUS_RUNNER
#include <nonius/main.h++>

#include "../include/dict/dict.hpp"

#include <unordered_map>
#include <random>
#include <functional>

#ifdef WITH_GOOGLE_BENCH
#include <sparsehash/dense_hash_map>
#endif

struct inc_gen {
    int operator()() {
        return _counter++;
    }

    int _counter = 0;
};

template <typename Map>
void insert_test(Map& map) {
    for (int i = 0; i != 10000; ++i) {
        map[i] = i;
    }
}

NONIUS_BENCHMARK("dict insert", [](nonius::chronometer meter) {
    io::dict<int, int> d;
    d.reserve(1000);
    meter.measure([&] { insert_test(d); });
})

NONIUS_BENCHMARK("umap insert", [](nonius::chronometer meter) {
    std::unordered_map<int, int> d;
    d.reserve(1000);
    meter.measure([&] { insert_test(d); });
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google insert", [](nonius::chronometer meter) {
    google::dense_hash_map<int, int> d(1000);
    d.set_empty_key(0);
    meter.measure([&] { insert_test(d); });
})
#endif

#ifdef WITH_GOOGLE_BENCH
template <typename Map, typename Gen>
Map build_map_google(int size, Gen gen) {
    Map d;
    d.set_empty_key(0);

    for (int i = 0; i != size; ++i) {
        d[gen()] = i;
    }

    return d;
}

template <typename Map>
Map build_map_google_with_reserve(int size) {
    Map d(size);
    d.set_empty_key(0);

    for (int i = 0; i != size; ++i) {
        d[i] = i;
    }

    return d;
}
#endif

template <typename Map, typename Gen>
Map build_map(int size, Gen gen) {
    Map d;

    for (int i = 0; i != size; ++i) {
        d[gen()] = i;
    }

    return d;
}

template <typename Map>
Map build_map_with_reserve(int size) {
    Map d(size);

    for (int i = 0; i != size; ++i) {
        d[i] = i;
    }

    return d;
}

template <typename Map, typename Generator>
int lookup_test(Map& map, Generator& gen) {
    int res = 0;
    for (std::size_t i = 0; i < 100; i += 1) {
        res += map[gen()];
    }

    return res;
}

const int small_lookup_test_size = 10;

NONIUS_BENCHMARK("small dict lookup", [](nonius::chronometer meter) {
    auto d = build_map<io::dict<int, int>>(small_lookup_test_size, inc_gen());

    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

NONIUS_BENCHMARK("small umap lookup", [](nonius::chronometer meter) {
    auto d = build_map<std::unordered_map<int, int>>(small_lookup_test_size, inc_gen());

    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("small google lookup", [](nonius::chronometer meter) {
    auto d =
        build_map_google<google::dense_hash_map<int, int>>(small_lookup_test_size, inc_gen());

    std::uniform_int_distribution<std::size_t> normal(0, d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})
#endif

const int lookup_test_size = 1000000;

NONIUS_BENCHMARK("dict lookup", [](nonius::chronometer meter) {

    std::uniform_int_distribution<std::size_t> normal(0, lookup_test_size - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));
    auto d = build_map<io::dict<int, int>>(lookup_test_size, gen);

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

NONIUS_BENCHMARK("umap lookup", [](nonius::chronometer meter) {

    std::uniform_int_distribution<std::size_t> normal(0, lookup_test_size - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));
    auto d = build_map<std::unordered_map<int, int>>(lookup_test_size, gen);

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google lookup", [](nonius::chronometer meter) {
    std::uniform_int_distribution<std::size_t> normal(0, lookup_test_size - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));
    auto d =
        build_map_google<google::dense_hash_map<int, int>>(lookup_test_size, gen);

    meter.measure([&, gen] { return lookup_test(d, gen); });
})
#endif

NONIUS_BENCHMARK("dict lookup with many misses", [](nonius::chronometer meter) {
    std::uniform_int_distribution<std::size_t> build_normal(0, lookup_test_size - 1);
    std::mt19937 build_engine;
    auto build_gen = std::bind(std::ref(build_normal), std::ref(build_engine));
    auto d = build_map<io::dict<int, int>>(lookup_test_size, build_gen);

    std::uniform_int_distribution<std::size_t> normal(0, 16 * lookup_test_size - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

NONIUS_BENCHMARK("umap lookup with many misses", [](nonius::chronometer meter) {
    std::uniform_int_distribution<std::size_t> build_normal(0, lookup_test_size - 1);
    std::mt19937 build_engine;
    auto build_gen = std::bind(std::ref(build_normal), std::ref(build_engine));
    auto d = build_map<std::unordered_map<int, int>>(lookup_test_size, build_gen);

    std::uniform_int_distribution<std::size_t> normal(0, 16 * lookup_test_size - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google lookup with many misses", [](nonius::chronometer meter) {
    std::uniform_int_distribution<std::size_t> build_normal(0, lookup_test_size - 1);
    std::mt19937 build_engine;
    auto build_gen = std::bind(std::ref(build_normal), std::ref(build_engine));
    auto d =
        build_map_google<google::dense_hash_map<int, int>>(lookup_test_size, build_gen);

    std::uniform_int_distribution<std::size_t> normal(0, 16 * d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})
#endif

// TODO(improve) - this hits us hard
NONIUS_BENCHMARK("dict lookup with heavy clustering", [](nonius::chronometer meter) {
    auto d = build_map<io::dict<int, int>>(lookup_test_size, inc_gen());

    std::uniform_int_distribution<std::size_t> normal(0, 16 * lookup_test_size - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

NONIUS_BENCHMARK("umap lookup with heavy clustering", [](nonius::chronometer meter) {
    auto d = build_map<std::unordered_map<int, int>>(lookup_test_size, inc_gen());

    std::uniform_int_distribution<std::size_t> normal(0, 16 * lookup_test_size - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google lookup with heavy clustering", [](nonius::chronometer meter) {
    auto d =
        build_map_google<google::dense_hash_map<int, int>>(lookup_test_size, inc_gen());

    std::uniform_int_distribution<std::size_t> normal(0, 16 * d.size() - 1);
    std::mt19937 engine;
    auto gen = std::bind(std::ref(normal), std::ref(engine));

    meter.measure([&, gen] { return lookup_test(d, gen); });
})
#endif

const int build_test_size = 1000;

NONIUS_BENCHMARK("dict build", [] {
    return build_map<io::dict<int, int>>(build_test_size, inc_gen());
})

NONIUS_BENCHMARK("umap build", [] {
    return build_map<std::unordered_map<int, int>>(build_test_size, inc_gen());
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build", [] {
    return build_map_google<google::dense_hash_map<int, int>>(build_test_size, inc_gen());
})
#endif

NONIUS_BENCHMARK("dict build with reserve", [] {
    return build_map_with_reserve<io::dict<int, int>>(build_test_size);
})

NONIUS_BENCHMARK("umap build with reserve", [] {
    return build_map_with_reserve<std::unordered_map<int, int>>(
        build_test_size);
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build with reserve", [] {
    return build_map_google<google::dense_hash_map<int, int>>(build_test_size, inc_gen());
})
#endif

template <typename Map>
Map build_string_map(int size) {
    Map d;

    for (int i = 0; i != size; ++i) {
        d[std::to_string(i) + std::to_string(i) + std::to_string(i) +
          std::to_string(i) + std::to_string(i) + std::to_string(i) +
          std::to_string(i)] = i;
    }

    return d;
}

#ifdef WITH_GOOGLE_BENCH
template <typename Map>
Map build_string_map_google(int size) {
    Map d;
    d.set_empty_key("");

    for (int i = 0; i != size; ++i) {
        d[std::to_string(i) + std::to_string(i) + std::to_string(i) +
          std::to_string(i) + std::to_string(i) + std::to_string(i) +
          std::to_string(i)] = i;
    }

    return d;
}
#endif

NONIUS_BENCHMARK("dict build with string key", [] {
    return build_string_map<io::dict<std::string, int>>(build_test_size);
})

NONIUS_BENCHMARK("umap build with string key", [] {
    return build_string_map<std::unordered_map<std::string, int>>(
        build_test_size);
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google build with string key", [] {
    return build_string_map_google<google::dense_hash_map<std::string, int>>(
        build_test_size);
})
#endif

template <typename Map, typename LookUpKeys>
int string_lookup_test(Map& map, const LookUpKeys& keys) {
    int res = 0;
    for (auto&& k : keys) {
        res += map[k];
    }

    return res;
}

const int string_lookup_test_size = 1000;

NONIUS_BENCHMARK("dict string lookup", [](nonius::chronometer meter) {
    auto d = build_string_map<io::dict<std::string, int>>(
        string_lookup_test_size);
    std::vector<std::string> keys{ "1111111", "2222222", "3333333",
                                   "4444444", "5555555", "6666666",
                                   "7777777", "8888888", "9999999" };

    meter.measure([&] { return string_lookup_test(d, keys); });
})

NONIUS_BENCHMARK("umap string lookup", [](nonius::chronometer meter) {
    auto d = build_string_map<std::unordered_map<std::string, int>>(
        string_lookup_test_size);
    std::vector<std::string> keys{ "1111111", "2222222", "3333333",
                                   "4444444", "5555555", "6666666",
                                   "7777777", "8888888", "9999999" };

    meter.measure([&] { return string_lookup_test(d, keys); });
})

#ifdef WITH_GOOGLE_BENCH
NONIUS_BENCHMARK("google string lookup", [](nonius::chronometer meter) {
    auto d = build_string_map_google<google::dense_hash_map<std::string, int>>(
        string_lookup_test_size);
    std::vector<std::string> keys{ "1111111", "2222222", "3333333",
                                   "4444444", "5555555", "6666666",
                                   "7777777", "8888888", "9999999" };

    meter.measure([&] { return string_lookup_test(d, keys); });
})
#endif
<|endoftext|>


<commit_before>#include <sstream>
#include <iostream>

#include "TChain.h"
#include "TTree.h"
#include "TFile.h"

#include "neutvect.h"
#include "neutvtx.h"

#include "CLITools.hxx"
#include "PureGenUtils.hxx"

#include "PureNeutRooTracker.hxx"

namespace {

std::ostream& operator<<(std::ostream& o, const TLorentzVector& tlv){
  return o << "[" << tlv.X() << ", " << tlv.Y() << ", " << tlv.Z() << ", "
    << tlv.T() <<  "]";
}

std::string outfname;
std::string inpfdescript;
bool ObjectOutput = false;
bool useSimpleTree = false;
bool OutputInGev = false;
bool SaveIsBound = false;
int verbosity = 0;
}

int NeutToRooTracker(const char* InputFileDescriptor){

//Input stuff
  TChain* NeutTree = new TChain("neuttree");

  int nFiles = NeutTree->Add(InputFileDescriptor);

  if(!nFiles){
    std::cout << "\"" << InputFileDescriptor << "\" matched 0 input files."
      << std::endl;
    return 2;
  }

  NeutVect *vector = new NeutVect();
  NeutTree->SetBranchAddress("vectorbranch",&vector);
  NeutVtx *vertex = new NeutVtx();
  NeutTree->SetBranchAddress("vertexbranch",&vertex);

  long NEntries = NeutTree->GetEntries();
  long FilledEntries = 0;

  if(!NEntries){
    std::cout << "Failed to find any entries (" << NEntries
      << ")." << std::endl;
    return 4;
  }
  std::cout << "Reading " << nFiles << " input files with "
    << NEntries << " entries." << std::endl;

//Output stuff
  TFile* outFile = new TFile(outfname.c_str(),"CREATE");

  if(!outFile->IsOpen()){
    std::cerr << "[ERROR]: Couldn't open output file: " << outfname
    << std::endl;
    return 8;
  } else {
    std::cout << "Created output file: " << outFile->GetName() << std::endl;
  }

  TTree* rooTrackerTree = new TTree("nRooTracker","Pure NEUT RooTracker");
  NRooTrackerVtx* outRooTracker = new NRooTrackerVtx();
  if(ObjectOutput){
    rooTrackerTree->Branch("nRooTracker", &outRooTracker);
  } else {
    outRooTracker->AddBranches(rooTrackerTree, useSimpleTree, SaveIsBound);
  }

  for(long entryNum = 0; entryNum < NEntries; ++entryNum){

    if( entryNum && (!(entryNum%10000)) ){
      std::cout << "Read " << entryNum << " entries." << std::endl;
    }

    if(!entryNum){ // cout for my sanity
      std::cout << "Reading first entry... " << std::flush;
    }
    NeutTree->GetEntry(entryNum);
    if(!entryNum){ // cout for my sanity
      std::cout << "Read first entry!" << std::endl;
    }

    //**************************************************
    //Event Level
    std::stringstream ss("");
    ss << vector->Mode;
    (*outRooTracker->EvtCode) = ss.str();
    outRooTracker->EvtNum = vector->EventNo;
    outRooTracker->EvtXSec = vector->Totcrs;

    outRooTracker->NEcrsx = vector->Crsx;
    outRooTracker->NEcrsy = vector->Crsy;
    outRooTracker->NEcrsz = vector->Crsz;
    outRooTracker->NEcrsphi = vector->Crsphi;

    (void)outRooTracker->EvtVtx[0];
    (void)outRooTracker->EvtVtx[0];
    (void)outRooTracker->EvtVtx[0];
    (void)outRooTracker->EvtVtx[0];

    //**************************************************
    //StdHepN Particles

    if(verbosity > 1){
      std::cout << "Vector #:" << entryNum << std::endl;
      std::cout << "\tNPrimary: " << vector->Nprimary() << std::endl;
      std::cout << "\tEvtCode: " << (*outRooTracker->EvtCode) << std::endl;
      std::cout << "\tEvtXSec: " << outRooTracker->EvtXSec << std::endl;
      std::cout << "\tNEcrsx: " << outRooTracker->NEcrsx << std::endl;
      std::cout << "\tNEcrsy: " << outRooTracker->NEcrsy << std::endl;
      std::cout << "\tNEcrsz: " << outRooTracker->NEcrsz << std::endl;
      std::cout << "\tNEcrsphi: " << outRooTracker->NEcrsphi << std::endl;
      std::cout << "\tNOutgoing Particles: " << vector->Npart() << std::endl;
      std::cout << std::endl;
    }

    //Fill the particle info
    outRooTracker->StdHepN = vector->Npart();
    outRooTracker->IsBound = vector->Ibound;

    for(int partNum = 0; partNum < vector->Npart(); ++partNum){
      const NeutPart& part = (*vector->PartInfo(partNum));

      if(partNum == 1){
        // As in TNeutOutput, to emulate neutgeom
        // StdHepX[1] is the target
        outRooTracker->StdHepPdg[1] =
          PGUtils::MakeNuclearPDG(vector->TargetZ, vector->TargetA);
        outRooTracker->StdHepP4[1][kNStdHepIdxE] = vector->TargetA;
        if(verbosity > 1){
          std::cout << "TARGET"
            << "\n\tA: " << vector->TargetA
            << "\n\tZ: " << vector->TargetZ
            << "\n\tPDG: " << outRooTracker->StdHepPdg[partNum]
            << "\n\tStatus: " << outRooTracker->StdHepStatus[partNum]
            << "\n\tHEPP4: " << PGUtils::PrintArray(
              outRooTracker->StdHepP4[partNum])
            << "\n\tIsBoundTarget: " << outRooTracker->IsBound
            << std::endl;
        }
        continue;
      }

      outRooTracker->StdHepPdg[partNum] = part.fPID;

      switch(part.fStatus){
        case -1:{
          outRooTracker->StdHepStatus[partNum] = 0;
          break;
        }
        case 0:{
          outRooTracker->StdHepStatus[partNum] = 1;
          break;
        }
        case 2:{
          outRooTracker->StdHepStatus[partNum] = 1;
          break;
        }
        default:{
          if(verbosity > 1){
            std::cout << "--Found other neutcode: " << part.fStatus << std::endl;
            outRooTracker->StdHepStatus[partNum] =
              (part.fStatus==1)?-1:part.fStatus;
          }
        }
      }

      if(OutputInGev){
        static constexpr float MeVToGeV = 1.0/1000;
        outRooTracker->StdHepP4[partNum][kNStdHepIdxPx] = part.fP.X()*MeVToGeV;
        outRooTracker->StdHepP4[partNum][kNStdHepIdxPy] = part.fP.Y()*MeVToGeV;
        outRooTracker->StdHepP4[partNum][kNStdHepIdxPz] = part.fP.Z()*MeVToGeV;
        outRooTracker->StdHepP4[partNum][kNStdHepIdxE] = part.fP.E()*MeVToGeV;
      } else {
        outRooTracker->StdHepP4[partNum][kNStdHepIdxPx] = part.fP.X();
        outRooTracker->StdHepP4[partNum][kNStdHepIdxPy] = part.fP.Y();
        outRooTracker->StdHepP4[partNum][kNStdHepIdxPz] = part.fP.Z();
        outRooTracker->StdHepP4[partNum][kNStdHepIdxE] = part.fP.E();
      }

      if(verbosity > 1){
        std::cout << ((partNum>1)?"Particle:":"Incoming Neutrino:")
          << "\n\tStdHEPPDG: " << outRooTracker->StdHepPdg[partNum]
          << "\n\tStdHEPStatus: " << outRooTracker->StdHepStatus[partNum]
          << "\n\tStdHEPP4: " << PGUtils::PrintArray(
            outRooTracker->StdHepP4[partNum])
          << std::endl;
      }

      //Not implemented in NEUT
      (void)outRooTracker->StdHepX4[partNum][kNStdHepIdxX];
      (void)outRooTracker->StdHepX4[partNum][kNStdHepIdxY];
      (void)outRooTracker->StdHepX4[partNum][kNStdHepIdxZ];
      (void)outRooTracker->StdHepX4[partNum][kNStdHepIdxT];
      (void)outRooTracker->StdHepPolz[partNum][kNStdHepIdxPx];
      (void)outRooTracker->StdHepPolz[partNum][kNStdHepIdxPy];
      (void)outRooTracker->StdHepPolz[partNum][kNStdHepIdxPz];
      (void)outRooTracker->StdHepPolz[partNum][kNStdHepIdxE];
    }

    //**************************************************
    //NEUT VCWork Particles
    //Not yet implemented.
    outRooTracker->NEnvc = 1;
    for(int i = 0; i < outRooTracker->NEnvc; ++i){
      (void)outRooTracker->NEpvc[i];
      (void)outRooTracker->NEiorgvc[i];
      (void)outRooTracker->NEiflgvc[i];
      (void)outRooTracker->NEicrnvc[i];
    }

    //**************************************************
    //NEUT Pion FSI interaction history
    //Not yet implemented
    outRooTracker->NEnvert = 1;

    for(int i = 0; i < outRooTracker->NEnvert; ++i){
      (void)outRooTracker->NEposvert[i];
      (void)outRooTracker->NEiflgvert[i];
    }

    outRooTracker->NEnvcvert = 1;
    for(int i = 0; i < outRooTracker->NEnvcvert; ++i){
      (void)outRooTracker->NEdirvert[i];
      (void)outRooTracker->NEabspvert[i];
      (void)outRooTracker->NEabstpvert[i];
      (void)outRooTracker->NEipvert[i];
      (void)outRooTracker->NEiverti[i];
      (void)outRooTracker->NEivertf[i];
    }

    //**************************************************
    //NEUT Nucleon FSI interaction history
    //Not yet implemented
    outRooTracker->NFnvert = 1;
    (void)outRooTracker->NFiflag[0];
    (void)outRooTracker->NFx[0];
    (void)outRooTracker->NFy[0];
    (void)outRooTracker->NFz[0];
    (void)outRooTracker->NFpx[0];
    (void)outRooTracker->NFpy[0];
    (void)outRooTracker->NFpz[0];
    (void)outRooTracker->NFe[0];
    (void)outRooTracker->NFfirststep[0];

    outRooTracker->NFnstep = 1;
    (void)outRooTracker->NFecms2[0];

    rooTrackerTree->Fill();
    FilledEntries++;
    if(verbosity > 1){
      std::cout << "*****************Filled*****************\n" << std::endl;
    }
    outRooTracker->Reset();
  }
  std::cout << "Wrote " << FilledEntries << "events to disk." << std::endl;
  rooTrackerTree->Write();
  outFile->Close();
  return 0;
}

namespace {

void SetOpts(){
  CLIArgs::OptSpec.emplace_back("-h","--help", false,
    [&] (std::string const &opt) -> bool {
      CLIArgs::SayRunLike();
      exit(0);
    });

  CLIArgs::OptSpec.emplace_back("-i", "--input-file", true,
    [&] (std::string const &opt) -> bool {
      std::cout << "\tReading from file descriptor : " << opt << std::endl;
      inpfdescript = opt;
      return true;
    }, true,[](){},"<TChain::Add descriptor>");

  CLIArgs::OptSpec.emplace_back("-o", "--output-file", true,
    [&] (std::string const &opt) -> bool {
      std::cout << "\tWriting to File: " << opt << std::endl;
      outfname = opt;
      return true;
    }, false,
    [&](){outfname = "vector.ntrac.root";},
    "<File Name>{default=vector.ntrac.root}");

  CLIArgs::OptSpec.emplace_back("-v", "--verbosity", true,
    [&] (std::string const &opt) -> bool {
      int vbhold;
      if(PGUtils::str2int(vbhold,opt.c_str()) == PGUtils::STRINT_SUCCESS){
        std::cout << "Verbosity: " << vbhold << std::endl;
        verbosity = vbhold;
        return true;
      }
      return false;
    }, false,
    [&](){verbosity = 0;}, "<0-4>{default=0}");

  CLIArgs::OptSpec.emplace_back("-s", "--simple-tree", false,
    [&] (std::string const &opt) -> bool {
      std::cout << "Using simple tree." << std::endl;
      useSimpleTree = true;
      return true;
    }, false,
    [&](){useSimpleTree = false;}, "Only output StdHep.");

  CLIArgs::OptSpec.emplace_back("-G", "--GeV-mode", false,
    [&] (std::string const &opt) -> bool {
      std::cout << "Outputting in GeV." << std::endl;
      OutputInGev = true;
      return true;
    }, false,
    [&](){OutputInGev = false;}, "Use GeV rather than MeV.");

  CLIArgs::OptSpec.emplace_back("-O", "--objectify-output", false,
    [&] (std::string const &opt) -> bool {
      std::cout << "Using simple tree." << std::endl;
      ObjectOutput = true;
      return true;
    }, false,
    [&](){ObjectOutput = false;}, "Output object tree.");

  CLIArgs::OptSpec.emplace_back("-b", "--save-isbound", false,
    [&] (std::string const &opt) -> bool {
      std::cout << "Adding IsBound branch to output tree." << std::endl;
      SaveIsBound = true;
      return true;
    }, false,
    [&](){SaveIsBound = false;}, "Output IsBound Branch");
}
}

int main(int argc, char const * argv[]){
  SetOpts();

  CLIArgs::AddArguments(argc,argv);
  if(!CLIArgs::GetOpts()){
    CLIArgs::SayRunLike();
    return 1;
  }

  int rtncode = 0;
  if((rtncode = NeutToRooTracker(inpfdescript.c_str()))){
    CLIArgs::SayRunLike();
  }
  return rtncode;
}
<commit_msg>Neut2RooTracker now saves the struck nucleon StdHep info.<commit_after>#include <sstream>
#include <iostream>

#include "TChain.h"
#include "TTree.h"
#include "TFile.h"

#include "neutvect.h"
#include "neutvtx.h"

#include "CLITools.hxx"
#include "PureGenUtils.hxx"

#include "PureNeutRooTracker.hxx"

namespace {

std::ostream& operator<<(std::ostream& o, const TLorentzVector& tlv){
  return o << "[" << tlv.X() << ", " << tlv.Y() << ", " << tlv.Z() << ", "
    << tlv.T() <<  "]";
}

std::string outfname;
std::string inpfdescript;
bool ObjectOutput = false;
bool useSimpleTree = false;
bool OutputInGev = false;
bool SaveIsBound = false;
int verbosity = 0;
long MaxEntries = 0;
}

int NeutToRooTracker(const char* InputFileDescriptor){

//Input stuff
  TChain* NeutTree = new TChain("neuttree");

  int nFiles = NeutTree->Add(InputFileDescriptor);

  if(!nFiles){
    std::cout << "\"" << InputFileDescriptor << "\" matched 0 input files."
      << std::endl;
    return 2;
  }

  NeutVect *vector = new NeutVect();
  NeutTree->SetBranchAddress("vectorbranch",&vector);
  NeutVtx *vertex = new NeutVtx();
  NeutTree->SetBranchAddress("vertexbranch",&vertex);

  long NEntries = NeutTree->GetEntries();
  long FilledEntries = 0;

  if(!NEntries){
    std::cout << "Failed to find any entries (" << NEntries
      << ")." << std::endl;
    return 4;
  }
  std::cout << "Reading " << nFiles << " input files with "
    << NEntries << " entries." << std::endl;

//Output stuff
  TFile* outFile = new TFile(outfname.c_str(),"CREATE");

  if(!outFile->IsOpen()){
    std::cerr << "[ERROR]: Couldn't open output file: " << outfname
    << std::endl;
    return 8;
  } else {
    std::cout << "Created output file: " << outFile->GetName() << std::endl;
  }

  TTree* rooTrackerTree = new TTree("nRooTracker","Pure NEUT RooTracker");
  NRooTrackerVtx* outRooTracker = new NRooTrackerVtx();
  if(ObjectOutput){
    rooTrackerTree->Branch("nRooTracker", &outRooTracker);
  } else {
    outRooTracker->AddBranches(rooTrackerTree, useSimpleTree, SaveIsBound);
  }

  long long doEntries = (MaxEntries==-1) ?
    NEntries : (std::min(MaxEntries, NEntries));

  for(long entryNum = 0; entryNum < doEntries; ++entryNum){

    if( entryNum && (!(entryNum%10000)) ){
      std::cout << "Read " << entryNum << " entries." << std::endl;
    }

    if(!entryNum){ // cout for my sanity
      std::cout << "Reading first entry... " << std::flush;
    }
    NeutTree->GetEntry(entryNum);
    if(!entryNum){ // cout for my sanity
      std::cout << "Read first entry!" << std::endl;
    }

    //**************************************************
    //Event Level
    std::stringstream ss("");
    ss << vector->Mode;
    (*outRooTracker->EvtCode) = ss.str();
    outRooTracker->EvtNum = vector->EventNo;
    outRooTracker->EvtXSec = vector->Totcrs;

    outRooTracker->NEcrsx = vector->Crsx;
    outRooTracker->NEcrsy = vector->Crsy;
    outRooTracker->NEcrsz = vector->Crsz;
    outRooTracker->NEcrsphi = vector->Crsphi;

    (void)outRooTracker->EvtVtx[0];
    (void)outRooTracker->EvtVtx[0];
    (void)outRooTracker->EvtVtx[0];
    (void)outRooTracker->EvtVtx[0];

    //**************************************************
    //StdHepN Particles

    if(verbosity>3){
      std::cout << "**"
"******************************************************************************"
    << std::endl;
    vector->Dump();
      std::cout << "**"
"******************************************************************************"
    << std::endl;
    }

    if(verbosity > 1){
      std::cout << "Vector #:" << entryNum << std::endl;
      std::cout << "\tNPrimary: " << vector->Npart() << std::endl;
      std::cout << "\tNPrimary: " << vector->Nprimary() << std::endl;
      std::cout << "\tEvtCode: " << (*outRooTracker->EvtCode) << std::endl;
      std::cout << "\tEvtXSec: " << outRooTracker->EvtXSec << std::endl;
      std::cout << "\tNEcrsx: " << outRooTracker->NEcrsx << std::endl;
      std::cout << "\tNEcrsy: " << outRooTracker->NEcrsy << std::endl;
      std::cout << "\tNEcrsz: " << outRooTracker->NEcrsz << std::endl;
      std::cout << "\tNEcrsphi: " << outRooTracker->NEcrsphi << std::endl;
      std::cout << "\tNOutgoing Particles: " << vector->Npart() << std::endl;
      std::cout << std::endl;
    }

    //Fill the particle info
    outRooTracker->StdHepN = vector->Npart()+1;//Need to include nuclear target.
    outRooTracker->IsBound = vector->Ibound;

    for(int partNum = 0, saveInd = 0; partNum < vector->Npart();
      ++partNum, ++saveInd){
      const NeutPart& part = (*vector->PartInfo(partNum));

      if(partNum == 1){
        // As in TNeutOutput, to emulate neutgeom
        // StdHepX[1] is the target
        outRooTracker->StdHepPdg[saveInd] =
          PGUtils::MakeNuclearPDG(vector->TargetZ, vector->TargetA);
        outRooTracker->StdHepP4[saveInd][kNStdHepIdxE] = vector->TargetA;
        if(verbosity > 1){
          std::cout << "TARGET"
            << "\n\tA: " << vector->TargetA
            << "\n\tZ: " << vector->TargetZ
            << "\n\tPDG: " << outRooTracker->StdHepPdg[saveInd]
            << "\n\tStatus: " << outRooTracker->StdHepStatus[saveInd]
            << "\n\tHEPP4: " << PGUtils::PrintArray(
              outRooTracker->StdHepP4[saveInd])
            << "\n\tIsBoundTarget: " << outRooTracker->IsBound
            << std::endl;
        }

        //Now save the struck nucleon properties
        ++saveInd;
      }

      outRooTracker->StdHepPdg[saveInd] = part.fPID;

      switch(part.fStatus){
        case -1:{
          outRooTracker->StdHepStatus[saveInd] = 0;
          break;
        }
        case 0:{
          outRooTracker->StdHepStatus[saveInd] = 1;
          break;
        }
        case 2:{
          outRooTracker->StdHepStatus[saveInd] = 1;
          break;
        }
        default:{
          if(verbosity > 1){
            std::cout << "--Found other neutcode: " << part.fStatus << std::endl;
            outRooTracker->StdHepStatus[saveInd] =
              (part.fStatus==1)?-1:part.fStatus;
          }
        }
      }
      if(partNum == 1 && part.fStatus == -1){
        outRooTracker->StdHepStatus[saveInd] = 11; //To sync with GENIE code for
        //Struck Nucleon.
      }

      if(OutputInGev){
        static constexpr float MeVToGeV = 1.0/1000;
        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPx] = part.fP.X()*MeVToGeV;
        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPy] = part.fP.Y()*MeVToGeV;
        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPz] = part.fP.Z()*MeVToGeV;
        outRooTracker->StdHepP4[saveInd][kNStdHepIdxE] = part.fP.E()*MeVToGeV;
      } else {
        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPx] = part.fP.X();
        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPy] = part.fP.Y();
        outRooTracker->StdHepP4[saveInd][kNStdHepIdxPz] = part.fP.Z();
        outRooTracker->StdHepP4[saveInd][kNStdHepIdxE] = part.fP.E();
      }

      if(verbosity > 1){
        std::cout << ((saveInd>1)?"Particle:":"Incoming Neutrino:")
          << "\n\tStdHEPPDG: " << outRooTracker->StdHepPdg[saveInd]
          << "\n\tStdHEPStatus: " << outRooTracker->StdHepStatus[saveInd]
          << "\n\tStdHEPP4: " << PGUtils::PrintArray(
            outRooTracker->StdHepP4[saveInd])
          << std::endl;
      }

      //Not implemented in NEUT
      (void)outRooTracker->StdHepX4[saveInd][kNStdHepIdxX];
      (void)outRooTracker->StdHepX4[saveInd][kNStdHepIdxY];
      (void)outRooTracker->StdHepX4[saveInd][kNStdHepIdxZ];
      (void)outRooTracker->StdHepX4[saveInd][kNStdHepIdxT];
      (void)outRooTracker->StdHepPolz[saveInd][kNStdHepIdxPx];
      (void)outRooTracker->StdHepPolz[saveInd][kNStdHepIdxPy];
      (void)outRooTracker->StdHepPolz[saveInd][kNStdHepIdxPz];
      (void)outRooTracker->StdHepPolz[saveInd][kNStdHepIdxE];
    }

    //**************************************************
    //NEUT VCWork Particles
    //Not yet implemented.
    outRooTracker->NEnvc = 1;
    for(int i = 0; i < outRooTracker->NEnvc; ++i){
      (void)outRooTracker->NEpvc[i];
      (void)outRooTracker->NEiorgvc[i];
      (void)outRooTracker->NEiflgvc[i];
      (void)outRooTracker->NEicrnvc[i];
    }

    //**************************************************
    //NEUT Pion FSI interaction history
    //Not yet implemented
    outRooTracker->NEnvert = 1;

    for(int i = 0; i < outRooTracker->NEnvert; ++i){
      (void)outRooTracker->NEposvert[i];
      (void)outRooTracker->NEiflgvert[i];
    }

    outRooTracker->NEnvcvert = 1;
    for(int i = 0; i < outRooTracker->NEnvcvert; ++i){
      (void)outRooTracker->NEdirvert[i];
      (void)outRooTracker->NEabspvert[i];
      (void)outRooTracker->NEabstpvert[i];
      (void)outRooTracker->NEipvert[i];
      (void)outRooTracker->NEiverti[i];
      (void)outRooTracker->NEivertf[i];
    }

    //**************************************************
    //NEUT Nucleon FSI interaction history
    //Not yet implemented
    outRooTracker->NFnvert = 1;
    (void)outRooTracker->NFiflag[0];
    (void)outRooTracker->NFx[0];
    (void)outRooTracker->NFy[0];
    (void)outRooTracker->NFz[0];
    (void)outRooTracker->NFpx[0];
    (void)outRooTracker->NFpy[0];
    (void)outRooTracker->NFpz[0];
    (void)outRooTracker->NFe[0];
    (void)outRooTracker->NFfirststep[0];

    outRooTracker->NFnstep = 1;
    (void)outRooTracker->NFecms2[0];

    rooTrackerTree->Fill();
    FilledEntries++;
    if(verbosity > 1){
      std::cout << "*****************Filled*****************\n" << std::endl;
    }
    outRooTracker->Reset();
  }
  std::cout << "Wrote " << FilledEntries << " events to disk." << std::endl;
  rooTrackerTree->Write();
  outFile->Close();
  return 0;
}

namespace {

void SetOpts(){
  CLIArgs::OptSpec.emplace_back("-h","--help", false,
    [&] (std::string const &opt) -> bool {
      CLIArgs::SayRunLike();
      exit(0);
    });

  CLIArgs::OptSpec.emplace_back("-i", "--input-file", true,
    [&] (std::string const &opt) -> bool {
      std::cout << "\t--Reading from file descriptor : " << opt << std::endl;
      inpfdescript = opt;
      return true;
    }, true,[](){},"<TChain::Add descriptor>");

  CLIArgs::OptSpec.emplace_back("-o", "--output-file", true,
    [&] (std::string const &opt) -> bool {
      std::cout << "\t--Writing to File: " << opt << std::endl;
      outfname = opt;
      return true;
    }, false,
    [&](){outfname = "vector.ntrac.root";},
    "<File Name>{default=vector.ntrac.root}");

  CLIArgs::OptSpec.emplace_back("-n", "--nentries", true,
    [&] (std::string const &opt) -> bool {
      long vbhold;
      if(PGUtils::str2int(vbhold,opt.c_str()) == PGUtils::STRINT_SUCCESS){
        if(vbhold != -1){
          std::cout << "\t--Looking at, at most, " << vbhold << " entries."
            << std::endl;
        }
        MaxEntries = vbhold;
        return true;
      }
      return false;
    }, false,
    [&](){MaxEntries = -1;}, "<-1>: Read all {default=-1}");

  CLIArgs::OptSpec.emplace_back("-v", "--verbosity", true,
    [&] (std::string const &opt) -> bool {
      int vbhold;
      if(PGUtils::str2int(vbhold,opt.c_str()) == PGUtils::STRINT_SUCCESS){
        std::cout << "\t--Verbosity: " << vbhold << std::endl;
        verbosity = vbhold;
        return true;
      }
      return false;
    }, false,
    [&](){verbosity = 0;}, "<0-4>{default=0}");

  CLIArgs::OptSpec.emplace_back("-s", "--simple-tree", false,
    [&] (std::string const &opt) -> bool {
      std::cout << "\t--Using simple tree." << std::endl;
      useSimpleTree = true;
      return true;
    }, false,
    [&](){useSimpleTree = false;}, "Only output StdHep.");

  CLIArgs::OptSpec.emplace_back("-G", "--GeV-mode", false,
    [&] (std::string const &opt) -> bool {
      std::cout << "\t--Outputting in GeV." << std::endl;
      OutputInGev = true;
      return true;
    }, false,
    [&](){OutputInGev = false;}, "Use GeV rather than MeV.");

  CLIArgs::OptSpec.emplace_back("-O", "--objectify-output", false,
    [&] (std::string const &opt) -> bool {
      std::cout << "\t--Using simple tree." << std::endl;
      ObjectOutput = true;
      return true;
    }, false,
    [&](){ObjectOutput = false;}, "Output object tree.");

  CLIArgs::OptSpec.emplace_back("-b", "--save-isbound", false,
    [&] (std::string const &opt) -> bool {
      std::cout << "\t--Adding IsBound branch to output tree." << std::endl;
      SaveIsBound = true;
      return true;
    }, false,
    [&](){SaveIsBound = false;}, "Output IsBound Branch");
}
}

int main(int argc, char const * argv[]){
  SetOpts();

  CLIArgs::AddArguments(argc,argv);
  if(!CLIArgs::GetOpts()){
    CLIArgs::SayRunLike();
    return 1;
  }

  int rtncode = 0;
  if((rtncode = NeutToRooTracker(inpfdescript.c_str()))){
    CLIArgs::SayRunLike();
  }
  return rtncode;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

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

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TEST_HPP
#define TEST_HPP

void report_failure(char const* str, char const* file, int line);

#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
    struct BOOST_PP_CAT(type, _counter_guard) \
    { \
        ~BOOST_PP_CAT(type, _counter_guard()) \
        { \
            TEST_CHECK(counted_type<type>::count == 0); \
        } \
    } BOOST_PP_CAT(type, _guard)
#endif

#define TEST_REPORT_AUX(x, line, file) \
	report_failure(x, line, file)

#define TEST_CHECK(x) \
    if (!(x)) \
        TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__)

#define TEST_ERROR(x) \
	TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)

#define TEST_NOTHROW(x) \
	try \
	{ \
		x; \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#endif // TEST_HPP

<commit_msg>catch exceptions from TEST_CHECK<commit_after>/*

Copyright (c) 2008, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

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

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TEST_HPP
#define TEST_HPP

void report_failure(char const* str, char const* file, int line);

#if defined(_MSC_VER)
#define COUNTER_GUARD(x)
#else
#define COUNTER_GUARD(type) \
    struct BOOST_PP_CAT(type, _counter_guard) \
    { \
        ~BOOST_PP_CAT(type, _counter_guard()) \
        { \
            TEST_CHECK(counted_type<type>::count == 0); \
        } \
    } BOOST_PP_CAT(type, _guard)
#endif

#define TEST_REPORT_AUX(x, line, file) \
	report_failure(x, line, file)

#define TEST_CHECK(x) \
	try \
	{ \
		if (!(x)) \
			TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); \
	} \
	catch (std::exception& e) \
	{ \
		TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#define TEST_ERROR(x) \
	TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__)

#define TEST_NOTHROW(x) \
	try \
	{ \
		x; \
	} \
	catch (...) \
	{ \
		TEST_ERROR("Exception thrown: " #x); \
	}

#endif // TEST_HPP

<|endoftext|>


<commit_before><commit_msg>n#827332: Charts shrink when there are no legends.<commit_after><|endoftext|>


<commit_before>/**
 * @Author Bob
 * @Eamil 0haizhu0@gmail.com
 * @Date 2017/7/6
 */

<commit_msg>2.4.1 常量引用<commit_after>#include <iostream>

/**
 * @Author Bob
 * @Eamil 0haizhu0@gmail.com
 * @Date 2017/7/6
 */
int main() {

  /**
   * 可以把引用绑定到const对象上，就像绑定到其他对象上一样，我们称之为对常量的引用。
   * 引用初始化之后不能被修改，而常量引用既可以指向常量，又可以指向非常量。
   */
  int i = 42;
  int &r1 = i; // 引用r1绑定对象i
  const int &i2 = i; // r2也绑定对象i，但是不允许通过r2修改i的值
  std::cout << &r1 << " => " << r1 << " => " << i << std::endl;
  r1 = 0; // r1 并非常量，i的值修改为0
//  r2 = 0; // 错误：r2 是一个常量引用
  std::cout << &r1 << " => " << r1 << " => " << i << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/test/base/ui_test_utils.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       ExtensionPointerLockAccessFail) {
  // Test that pointer lock cannot be accessed from an extension without
  // permission.
  ASSERT_TRUE(RunPlatformAppTest("pointer_lock/no_permission")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       ExtensionPointerLockAccessPass) {
  // Test that pointer lock can be accessed from an extension with permission.
  ASSERT_TRUE(RunPlatformAppTest("pointer_lock/has_permission")) << message_;
}
<commit_msg>Disable test that is failing on linux trybots.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/test/base/ui_test_utils.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       ExtensionPointerLockAccessFail) {
  // Test that pointer lock cannot be accessed from an extension without
  // permission.
  ASSERT_TRUE(RunPlatformAppTest("pointer_lock/no_permission")) << message_;
}

// http://crbug.com/223447
#if defined(OS_LINUX)
#define MAYBE_ExtensionPointerLockAccessPass \
    DISABLED_ExtensionPointerLockAccessPass
#else
#define MAYBE_ExtensionPointerLockAccessPass ExtensionPointerLockAccessPass
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest,
                       MAYBE_ExtensionPointerLockAccessPass) {
  // Test that pointer lock can be accessed from an extension with permission.
  ASSERT_TRUE(RunPlatformAppTest("pointer_lock/has_permission")) << message_;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/importer/external_process_importer_bridge.h"

#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/profile_import/profile_import_thread.h"
#include "webkit/glue/password_form.h"

#if defined(OS_WIN)
#include "chrome/browser/password_manager/ie7_password.h"
#endif

ExternalProcessImporterBridge::ExternalProcessImporterBridge(
    ProfileImportThread* profile_import_thread,
    const DictionaryValue& localized_strings)
    : profile_import_thread_(profile_import_thread) {
  // Bridge needs to make its own copy because OS 10.6 autoreleases the
  // localized_strings value that is passed in (see http://crbug.com/46003 ).
  localized_strings_.reset(localized_strings.DeepCopy());
}

void ExternalProcessImporterBridge::AddBookmarkEntries(
    const std::vector<ProfileWriter::BookmarkEntry>& bookmarks,
    const std::wstring& first_folder_name,
    int options) {
  profile_import_thread_->NotifyBookmarksImportReady(
      bookmarks, first_folder_name, options);
}

void ExternalProcessImporterBridge::AddHomePage(const GURL &home_page) {
  // TODO(mirandac): remove home page import from code base.
  // http://crbug.com/45678 :-)
  NOTIMPLEMENTED();
}

#if defined(OS_WIN)
void ExternalProcessImporterBridge::AddIE7PasswordInfo(
    const IE7PasswordInfo password_info) {
  NOTIMPLEMENTED();
}
#endif

void ExternalProcessImporterBridge::SetFavicons(
    const std::vector<history::ImportedFaviconUsage>& favicons) {
  profile_import_thread_->NotifyFaviconsImportReady(favicons);
}

void ExternalProcessImporterBridge::SetHistoryItems(
    const std::vector<history::URLRow>& rows,
    history::VisitSource visit_source) {
  profile_import_thread_->NotifyHistoryImportReady(rows, visit_source);
}

void ExternalProcessImporterBridge::SetKeywords(
    const std::vector<TemplateURL*>& template_urls,
    int default_keyword_index,
    bool unique_on_host_and_path) {
  profile_import_thread_->NotifyKeywordsReady(
      template_urls, default_keyword_index, unique_on_host_and_path);
}

void ExternalProcessImporterBridge::SetPasswordForm(
    const webkit_glue::PasswordForm& form) {
  profile_import_thread_->NotifyPasswordFormReady(form);
}

void ExternalProcessImporterBridge::NotifyStarted() {
  profile_import_thread_->NotifyStarted();
}

void ExternalProcessImporterBridge::NotifyItemStarted(
    importer::ImportItem item) {
  profile_import_thread_->NotifyItemStarted(item);
}

void ExternalProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) {
  profile_import_thread_->NotifyItemEnded(item);
}

void ExternalProcessImporterBridge::NotifyEnded() {
  // The internal process detects import end when all items have been received.
}

// TODO(viettrungluu): convert to string16.
std::wstring ExternalProcessImporterBridge::GetLocalizedString(int message_id) {
  string16 message;
  localized_strings_->GetString(base::IntToString(message_id), &message);
  return UTF16ToWideHack(message);
}

ExternalProcessImporterBridge::~ExternalProcessImporterBridge() {}
<commit_msg>importer: Remove an obsolete TODO comment.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/importer/external_process_importer_bridge.h"

#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/profile_import/profile_import_thread.h"
#include "webkit/glue/password_form.h"

#if defined(OS_WIN)
#include "chrome/browser/password_manager/ie7_password.h"
#endif

ExternalProcessImporterBridge::ExternalProcessImporterBridge(
    ProfileImportThread* profile_import_thread,
    const DictionaryValue& localized_strings)
    : profile_import_thread_(profile_import_thread) {
  // Bridge needs to make its own copy because OS 10.6 autoreleases the
  // localized_strings value that is passed in (see http://crbug.com/46003 ).
  localized_strings_.reset(localized_strings.DeepCopy());
}

void ExternalProcessImporterBridge::AddBookmarkEntries(
    const std::vector<ProfileWriter::BookmarkEntry>& bookmarks,
    const std::wstring& first_folder_name,
    int options) {
  profile_import_thread_->NotifyBookmarksImportReady(
      bookmarks, first_folder_name, options);
}

void ExternalProcessImporterBridge::AddHomePage(const GURL& home_page) {
  NOTIMPLEMENTED();
}

#if defined(OS_WIN)
void ExternalProcessImporterBridge::AddIE7PasswordInfo(
    const IE7PasswordInfo password_info) {
  NOTIMPLEMENTED();
}
#endif

void ExternalProcessImporterBridge::SetFavicons(
    const std::vector<history::ImportedFaviconUsage>& favicons) {
  profile_import_thread_->NotifyFaviconsImportReady(favicons);
}

void ExternalProcessImporterBridge::SetHistoryItems(
    const std::vector<history::URLRow>& rows,
    history::VisitSource visit_source) {
  profile_import_thread_->NotifyHistoryImportReady(rows, visit_source);
}

void ExternalProcessImporterBridge::SetKeywords(
    const std::vector<TemplateURL*>& template_urls,
    int default_keyword_index,
    bool unique_on_host_and_path) {
  profile_import_thread_->NotifyKeywordsReady(
      template_urls, default_keyword_index, unique_on_host_and_path);
}

void ExternalProcessImporterBridge::SetPasswordForm(
    const webkit_glue::PasswordForm& form) {
  profile_import_thread_->NotifyPasswordFormReady(form);
}

void ExternalProcessImporterBridge::NotifyStarted() {
  profile_import_thread_->NotifyStarted();
}

void ExternalProcessImporterBridge::NotifyItemStarted(
    importer::ImportItem item) {
  profile_import_thread_->NotifyItemStarted(item);
}

void ExternalProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) {
  profile_import_thread_->NotifyItemEnded(item);
}

void ExternalProcessImporterBridge::NotifyEnded() {
  // The internal process detects import end when all items have been received.
}

// TODO(viettrungluu): convert to string16.
std::wstring ExternalProcessImporterBridge::GetLocalizedString(int message_id) {
  string16 message;
  localized_strings_->GetString(base::IntToString(message_id), &message);
  return UTF16ToWideHack(message);
}

ExternalProcessImporterBridge::~ExternalProcessImporterBridge() {}
<|endoftext|>


<commit_before>/*
 * NetworkClient.cpp
 *
 *  Created on: 07.04.2016
 *      Author: Marc Hartung
 */

#include "../../include/network_impl/NetworkClient.hpp"

#include <iostream>
namespace NetOff
{

    NetworkClient::NetworkClient()
            : NetworkMember()
    {

    }

    NetworkClient::~NetworkClient()
    {}

    bool NetworkClient::initialize(const std::string& host, const int& port)
    {
        IPaddress ip;
		SDLNet_Init();

        unsigned times = 0;

		if (SDLNet_ResolveHost(&ip, host.c_str(), port) == -1)
		{
			std::cout << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl;
			return false;
		}

        do
        {
            SDL_Delay(_sleepTime);
            _socket = SDLNet_TCP_Open(&ip);
			std::cout << "wait for server on host " << ip.host << " and port " << port << std::endl;

        } while((_socket == nullptr || SDLNet_ResolveHost(&ip, host.c_str(), port) == -1) && (times++ <= (unsigned int)_numMaxSleeps));
        if (SDLNet_ResolveHost(&ip, host.c_str(), port) == -1)
        {
			std::cout << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl;

            return false;
        }

        if (_socket == nullptr)
        {
			std::cout << "no socket" << std::endl;

            return false;
        }
        return true;
    }

    void NetworkClient::deinitialize()
    {
        killSocket(_socket);
    }

} /* namespace NetOff */
<commit_msg>Adopt code style and improve output for user<commit_after>/*
 * NetworkClient.cpp
 *
 *  Created on: 07.04.2016
 *      Author: Marc Hartung
 */

#include "../../include/network_impl/NetworkClient.hpp"

#include <iostream>

namespace NetOff
{

    NetworkClient::NetworkClient()
            : NetworkMember()
    {
    }

    NetworkClient::~NetworkClient()
    {
    }

    bool NetworkClient::initialize(const std::string & host, const int & port)
    {
        IPaddress ip;
        SDLNet_Init();

        unsigned times = 0;

        if (SDLNet_ResolveHost(&ip, host.c_str(), port) == -1)
        {
            std::cout << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl;
            return false;
        }

        do
        {
            SDL_Delay(_sleepTime);
            _socket = SDLNet_TCP_Open(&ip);
            std::cout << "Waiting for server on host " << ip.host << " and port " << port << " ..." << std::endl;

        }
        while ((_socket == nullptr || SDLNet_ResolveHost(&ip, host.c_str(), port) == -1) && (times++ <= (unsigned int) _numMaxSleeps));
        if (SDLNet_ResolveHost(&ip, host.c_str(), port) == -1)
        {
            std::cout << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl;

            return false;
        }

        if (_socket == nullptr)
        {
            std::cout << "no socket" << std::endl;
            return false;
        }
        return true;
    }

    void NetworkClient::deinitialize()
    {
        killSocket(_socket);
    }

} /* namespace NetOff */
<|endoftext|>


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

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

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 "itktubeTubeExtractor.h"
#include "tubeCLIFilterWatcher.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"

#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkGroupSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
#include <itkTimeProbesCollectorBase.h>

#include "SegmentTubesCLP.h"

template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] );

// Must follow include of "...CLP.h" and
//   forward declaration of int DoIt( ... ).
#include "tubeCLIHelperFunctions.h"

template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] )
{
  PARSE_ARGS;

  // The timeCollector is used to perform basic profiling of the components
  //   of your algorithm.
  itk::TimeProbesCollectorBase timeCollector;

  // CLIProgressReporter is used to communicate progress with the Slicer GUI
  tube::CLIProgressReporter    progressReporter( "RidgeExtractor",
    CLPProcessInformation );
  progressReporter.Start();

  typedef float                                         PixelType;
  typedef itk::Image< PixelType, VDimension >           ImageType;
  typedef itk::ImageFileReader< ImageType >             ReaderType;

  typedef itk::tube::TubeExtractor< ImageType >         TubeOpType;
  typedef typename TubeOpType::TubeMaskImageType        MaskImageType;
  typedef itk::ImageFileReader< MaskImageType >         MaskReaderType;
  typedef itk::ImageFileWriter< MaskImageType >         MaskWriterType;

  typedef itk::SpatialObject< VDimension >              SpatialObjectType;
  typedef typename SpatialObjectType::ChildrenListType  ObjectListType;
  typedef itk::GroupSpatialObject< VDimension >         GroupType;
  typedef itk::VesselTubeSpatialObject< VDimension >    TubeType;
  typedef typename TubeType::PointListType              PointListType;
  typedef typename TubeType::PointType                  PointType;
  typedef typename TubeType::TubePointType              TubePointType;

  typedef itk::SpatialObjectWriter< VDimension >        SpatialObjectWriterType;

  timeCollector.Start("Load data");
  typename ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( inputVolume.c_str() );
  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    tube::ErrorMessage( "Reading volume: Exception caught: "
                        + std::string(err.GetDescription()) );
    timeCollector.Report();
    return EXIT_FAILURE;
    }
  timeCollector.Stop("Load data");
  double progress = 0.1;
  progressReporter.Report( progress );

  typename ImageType::Pointer inputImage = reader->GetOutput();

  if( scale < 0.3 )
    {
    tube::ErrorMessage( "Error: Scale < 0.3 is unsupported." );
    return EXIT_FAILURE;
    }

  typename TubeOpType::Pointer tubeOp = TubeOpType::New();

  tubeOp->SetInputImage( inputImage );
  tubeOp->SetRadius( scale );

  typedef itk::ContinuousIndex< double, VDimension >  seedIndexType;
  typedef double                                      seedScaleType;
  typedef std::vector< seedIndexType >                seedIndexListType;
  typedef std::vector< seedScaleType >                seedScaleListType;

  seedIndexType seedIndex;
  seedIndexListType seedIndexList;

  seedScaleListType seedScaleList;

  seedIndexList.clear();
  seedScaleList.clear();

  if( !seedX.empty() )
    {
    for( unsigned int seedXNum=0; seedXNum<seedX.size(); ++seedXNum )
      {
      for( unsigned int i=0; i<seedX[seedXNum].size(); i++ )
        {
        std::cout << seedX[seedXNum][i] << " ";
        }
      for( unsigned int i=0; i<VDimension; i++ )
        {
        seedIndex[i] = seedX[seedXNum][i];
        }
      seedIndexList.push_back( seedIndex );
      seedScaleList.push_back( scale );
      }
    }

  if( !seedPhysicalPoint.empty() )
    {
    for(size_t seedNum=0; seedNum<seedPhysicalPoint.size(); ++seedNum)
      {
      typename ImageType::PointType point;
      for( unsigned int i=0; i<VDimension; i++ )
        {
        point[i] = seedPhysicalPoint[seedNum][i];
        }

      point[0]*=-1;
      point[1]*=-1;

      bool transformSuccess =
        inputImage->TransformPhysicalPointToContinuousIndex(point, seedIndex);
      if (!transformSuccess)
        {
        std::cerr<<"Could not transform point #"
          <<seedNum<<" to seed index."<<std::endl;
        continue;
        }

      seedIndexList.push_back( seedIndex );
      seedScaleList.push_back( scale );
      }
    }

  if( !seedListFile.empty() )
    {
    std::ifstream readStream;
    readStream.open( seedListFile.c_str(), std::ios::binary |
      std::ios::in );
    std::string line;
    double seedScale;
    while( std::getline( readStream, line ) )
      {
      std::istringstream iss(line);
      for( unsigned int i = 0; i < VDimension; ++i )
        {
        iss >> seedIndex[i];
        }
      iss >> seedScale;
      }
    seedIndexList.push_back( seedIndex );
    seedScaleList.push_back( seedScale );
    }

  if( seedMask.empty() )
    {
    if( seedScaleMask.empty() )
      {
      }
    else
      {
      seedScaleList.push_back( scale );
      }

    }
  else if( seedScaleMask.empty() )
    {
    }

  typename seedIndexListType::iterator seedIndexIter =
    seedIndexList.begin();
  seedScaleListType::iterator seedScaleIter =
    seedScaleList.begin();

  unsigned int count = 1;
  while( seedIndexIter != seedIndexList.end() )
    {
    timeCollector.Start("Ridge Extractor");

    tubeOp->SetDebug( true );
    tubeOp->GetRidgeOp()->SetDebug( true );

    tubeOp->GetRidgeOp()->SetThreshRoundness( 0.0001 );
    tubeOp->GetRidgeOp()->SetThreshRoundnessStart( 0.0001 );
    tubeOp->GetRidgeOp()->SetThreshCurvature( 0.0001 );
    tubeOp->GetRidgeOp()->SetThreshCurvatureStart( 0.0001 );

    tubeOp->SetRadius( *seedScaleIter );

    typename TubeType::Pointer xTube = tubeOp->ExtractTube( *seedIndexIter,
      count );

    if( xTube.IsNull() )
      {
      tube::ErrorMessage( "Error: Ridge not found. " );
      return EXIT_FAILURE;
      }

    tubeOp->AddTube( xTube );

    ++seedIndexIter;
    ++seedScaleIter;
    ++count;
    }

  // Save Tubes
  typename SpatialObjectWriterType::Pointer soWriter =
    SpatialObjectWriterType::New();
  soWriter->SetFileName( outputTubeFile );
  soWriter->SetInput( tubeOp->GetTubeGroup().GetPointer() );
  soWriter->Update();

  // Save Tube Mask Image
  if( !outputTubeImage.empty() )
    {
    typename MaskWriterType::Pointer writer = MaskWriterType::New();
    writer->SetFileName( outputTubeImage );
    writer->SetInput( tubeOp->GetTubeMaskImage() );
    writer->SetUseCompression( true );
    writer->Update();
    }

  timeCollector.Stop("Ridge Extractor");

  progressReporter.Report( 1.0 );
  progressReporter.End();

  timeCollector.Report();
  return EXIT_SUCCESS;
}

// Main
int main( int argc, char * argv[] )
{
  try
    {
    PARSE_ARGS;
    }
  catch( const std::exception & err )
    {
    tube::ErrorMessage( err.what() );
    return EXIT_FAILURE;
    }
  PARSE_ARGS;

  // You may need to update this line if, in the project's .xml CLI file,
  //   you change the variable name for the inputVolume.
  return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv );
}
<commit_msg>FIX: Fix weird probe error when no seed is present<commit_after>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

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 "itktubeTubeExtractor.h"
#include "tubeCLIFilterWatcher.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"

#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkGroupSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
#include <itkTimeProbesCollectorBase.h>

#include "SegmentTubesCLP.h"

template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] );

// Must follow include of "...CLP.h" and
//   forward declaration of int DoIt( ... ).
#include "tubeCLIHelperFunctions.h"

template< class TPixel, unsigned int VDimension >
int DoIt( int argc, char * argv[] )
{
  PARSE_ARGS;

  // The timeCollector is used to perform basic profiling of the components
  //   of your algorithm.
  itk::TimeProbesCollectorBase timeCollector;

  // CLIProgressReporter is used to communicate progress with the Slicer GUI
  tube::CLIProgressReporter    progressReporter( "RidgeExtractor",
    CLPProcessInformation );
  progressReporter.Start();

  typedef float                                         PixelType;
  typedef itk::Image< PixelType, VDimension >           ImageType;
  typedef itk::ImageFileReader< ImageType >             ReaderType;

  typedef itk::tube::TubeExtractor< ImageType >         TubeOpType;
  typedef typename TubeOpType::TubeMaskImageType        MaskImageType;
  typedef itk::ImageFileReader< MaskImageType >         MaskReaderType;
  typedef itk::ImageFileWriter< MaskImageType >         MaskWriterType;

  typedef itk::SpatialObject< VDimension >              SpatialObjectType;
  typedef typename SpatialObjectType::ChildrenListType  ObjectListType;
  typedef itk::GroupSpatialObject< VDimension >         GroupType;
  typedef itk::VesselTubeSpatialObject< VDimension >    TubeType;
  typedef typename TubeType::PointListType              PointListType;
  typedef typename TubeType::PointType                  PointType;
  typedef typename TubeType::TubePointType              TubePointType;

  typedef itk::SpatialObjectWriter< VDimension >        SpatialObjectWriterType;

  timeCollector.Start("Load data");
  typename ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( inputVolume.c_str() );
  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & err )
    {
    tube::ErrorMessage( "Reading volume: Exception caught: "
                        + std::string(err.GetDescription()) );
    timeCollector.Report();
    return EXIT_FAILURE;
    }
  timeCollector.Stop("Load data");
  double progress = 0.1;
  progressReporter.Report( progress );

  typename ImageType::Pointer inputImage = reader->GetOutput();

  if( scale < 0.3 )
    {
    tube::ErrorMessage( "Error: Scale < 0.3 is unsupported." );
    return EXIT_FAILURE;
    }

  typename TubeOpType::Pointer tubeOp = TubeOpType::New();

  tubeOp->SetInputImage( inputImage );
  tubeOp->SetRadius( scale );

  typedef itk::ContinuousIndex< double, VDimension >  seedIndexType;
  typedef double                                      seedScaleType;
  typedef std::vector< seedIndexType >                seedIndexListType;
  typedef std::vector< seedScaleType >                seedScaleListType;

  seedIndexType seedIndex;
  seedIndexListType seedIndexList;

  seedScaleListType seedScaleList;

  seedIndexList.clear();
  seedScaleList.clear();

  if( !seedX.empty() )
    {
    for( unsigned int seedXNum=0; seedXNum<seedX.size(); ++seedXNum )
      {
      for( unsigned int i=0; i<seedX[seedXNum].size(); i++ )
        {
        std::cout << seedX[seedXNum][i] << " ";
        }
      for( unsigned int i=0; i<VDimension; i++ )
        {
        seedIndex[i] = seedX[seedXNum][i];
        }
      seedIndexList.push_back( seedIndex );
      seedScaleList.push_back( scale );
      }
    }

  if( !seedPhysicalPoint.empty() )
    {
    for(size_t seedNum=0; seedNum<seedPhysicalPoint.size(); ++seedNum)
      {
      typename ImageType::PointType point;
      for( unsigned int i=0; i<VDimension; i++ )
        {
        point[i] = seedPhysicalPoint[seedNum][i];
        }

      point[0]*=-1;
      point[1]*=-1;

      bool transformSuccess =
        inputImage->TransformPhysicalPointToContinuousIndex(point, seedIndex);
      if (!transformSuccess)
        {
        std::cerr<<"Could not transform point #"
          <<seedNum<<" to seed index."<<std::endl;
        continue;
        }

      seedIndexList.push_back( seedIndex );
      seedScaleList.push_back( scale );
      }
    }

  if( !seedListFile.empty() )
    {
    std::ifstream readStream;
    readStream.open( seedListFile.c_str(), std::ios::binary |
      std::ios::in );
    std::string line;
    double seedScale;
    while( std::getline( readStream, line ) )
      {
      std::istringstream iss(line);
      for( unsigned int i = 0; i < VDimension; ++i )
        {
        iss >> seedIndex[i];
        }
      iss >> seedScale;
      }
    seedIndexList.push_back( seedIndex );
    seedScaleList.push_back( seedScale );
    }

  if( seedMask.empty() )
    {
    if( seedScaleMask.empty() )
      {
      }
    else
      {
      seedScaleList.push_back( scale );
      }

    }
  else if( seedScaleMask.empty() )
    {
    }

  typename seedIndexListType::iterator seedIndexIter =
    seedIndexList.begin();
  seedScaleListType::iterator seedScaleIter =
    seedScaleList.begin();

  timeCollector.Start("Ridge Extractor");
  unsigned int count = 1;
  while( seedIndexIter != seedIndexList.end() )
    {

    tubeOp->SetDebug( true );
    tubeOp->GetRidgeOp()->SetDebug( true );

    tubeOp->GetRidgeOp()->SetThreshRoundness( 0.0001 );
    tubeOp->GetRidgeOp()->SetThreshRoundnessStart( 0.0001 );
    tubeOp->GetRidgeOp()->SetThreshCurvature( 0.0001 );
    tubeOp->GetRidgeOp()->SetThreshCurvatureStart( 0.0001 );

    tubeOp->SetRadius( *seedScaleIter );

    typename TubeType::Pointer xTube = tubeOp->ExtractTube( *seedIndexIter,
      count );

    if( xTube.IsNull() )
      {
      tube::ErrorMessage( "Error: Ridge not found. " );
      return EXIT_FAILURE;
      }

    tubeOp->AddTube( xTube );

    ++seedIndexIter;
    ++seedScaleIter;
    ++count;
    }

  // Save Tubes
  typename SpatialObjectWriterType::Pointer soWriter =
    SpatialObjectWriterType::New();
  soWriter->SetFileName( outputTubeFile );
  soWriter->SetInput( tubeOp->GetTubeGroup().GetPointer() );
  soWriter->Update();

  // Save Tube Mask Image
  if( !outputTubeImage.empty() )
    {
    typename MaskWriterType::Pointer writer = MaskWriterType::New();
    writer->SetFileName( outputTubeImage );
    writer->SetInput( tubeOp->GetTubeMaskImage() );
    writer->SetUseCompression( true );
    writer->Update();
    }

  timeCollector.Stop("Ridge Extractor");

  progressReporter.Report( 1.0 );
  progressReporter.End();

  timeCollector.Report();
  return EXIT_SUCCESS;
}

// Main
int main( int argc, char * argv[] )
{
  try
    {
    PARSE_ARGS;
    }
  catch( const std::exception & err )
    {
    tube::ErrorMessage( err.what() );
    return EXIT_FAILURE;
    }
  PARSE_ARGS;

  // You may need to update this line if, in the project's .xml CLI file,
  //   you change the variable name for the inputVolume.
  return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv );
}
<|endoftext|>