text:
#include "qset.hh"
#include <vector>
#include <map>

#include "TWUtilAlgos.hh"
#include "AbstractMemo.hh"

#include <boost/graph/subgraph.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>

#include <boost/graph/graphviz.hpp>

int permutTW(int nGraph, VSet vsetArg, const std::vector<Vertex>& Svec, const Graph& G) {
	int tw = NO_WIDTH;
	VSet vs = vsetArg;

	//std::cout << "PERMUTTW set " << vsetArg.size() << " vec size " << Svec.size() << "\n";

	auto loopEnd = Svec.end();
	for (auto current = Svec.begin(); current != loopEnd; ++current)
	{
		Vertex v = *current;
		vs.erase(v);
		int qval = sizeQ(nGraph, vs, v, G);
		tw = std::max(tw, qval);
	}
	return tw;
}

int altPermutTW(int nGraph, const VSet& vsetArg, const std::vector<Vertex>& SvecAll, const Graph& G) {
	int tw = NO_WIDTH;
	VSet vs = vsetArg;

	//std::cout << "PERMUTTW set " << vsetArg.size() << " vec size " << Svec.size() << "\n";

	int n = boost::num_vertices(G);

	auto loopEnd = SvecAll.end();
	for (auto current = SvecAll.begin(); current != loopEnd; ++current)
	{
		Vertex v = *current;
		//Lets us give the entire vertex set for the graph
		if (vsetArg.contains(v))
		{

			vs.erase(v);
			int qval = sizeQ(nGraph, vs, v, G);
			tw = std::max(tw, qval);
		}
	}
	return tw;
}

std::pair<Graph, std::map<Vertex, Vertex>> complement_graph(const Graph& G)
{
	auto vertexInfo = boost::vertices(G);
	//Start GC as identical to G, gives us all the same vertices
	Graph GC;

	std::map<Vertex, Vertex> vmap;

	//Add all vertices from G to GC, and store them in a vertex map
	for (auto u = vertexInfo.first; u != vertexInfo.second; u++)
	{
		Vertex newVert = boost::add_vertex(GC);
		//std::cout << "Making graph pair " << *u << " and " << newVert << "\n";
		vmap[*u] = newVert;
	}

	//Add all the remaining edges to our compliment
	for (auto u = vertexInfo.first; u != vertexInfo.second; u++)
	{
		for (auto v = vertexInfo.first; v != vertexInfo.second; v++)
		{
			//std::cout << "Edge Info: " << *u << " " << *v << " " << edge(*u, *v, G).second << "\n";

			if (*u < *v && !(edge(*u, *v, G).second))
			{
				//std::cout << "Adding comp edge " << vmap[*u] << " and " << vmap[*v] << "\n";
				//std::cout << "Comp numbers: " << vmap[*u] << " and " << vmap[*v] << "\n";
				boost::add_edge(vmap[*u], vmap[*v], GC);
			}

		}

	}

	//std::cout << "Done comp\n";

	//Return our key-value set for the map
	//http://stackoverflow.com/questions/8321316/flip-map-key-value-pair
	std::map<Vertex, Vertex> reversed;

	for (auto i = vmap.begin(); i != vmap.end(); ++i)
		reversed[i->second] = i->first;

	std::pair<Graph, std::map<Vertex, Vertex>> ret(GC, reversed);
	return ret;

}

int subgraphDegree(Vertex v, VSet S, const Graph& G)
{
	VSet neighbours;

	//std::cout << "Getting adj vertices for " << v << "\n";

	auto neighbourIter = boost::adjacent_vertices(v, G);
	for (auto n = neighbourIter.first; n != neighbourIter.second; ++n)
	{
		neighbours.insert(*n);
	}

	return S.setIntersection(neighbours).size();

}

//TODO this is not returning cliques
VSet maxIndSetHelper(VSet S, const Graph& G)
{
	//std::cout << "Max IS: size " << S.size() << "\n";
	//Base case
	if (S.size() <= 1)
	{
		//std::cout << "Base case\n";
		return S;
	}

	//std::cout << "Past base case: " << showSet(S) << "\n";

	//auto members = S.members();

	auto minDegInfo = minDegreeSubgraphVert(S, G);

	Vertex minDegreeVert = minDegInfo.first;
	int minDeg = minDegInfo.second;

	//Try finding max IS with the min-degree vertex removed
	auto SV = S;
	//Erase each neighbour of the vertex, and the vertex itself
	//std::cout << "Size " << S.size() << " choosing " << minDegreeVert << "\n";
	SV.erase(minDegreeVert);
	auto svNeighbs = boost::adjacent_vertices(minDegreeVert, G);
	for (auto minNeighb = svNeighbs.first; minNeighb != svNeighbs.second; minNeighb++)
	{
		//std::cout << "Size " << S.size() << " erasing " << *minNeighb << "\n";

		SV.erase(*minNeighb);
	}
	VSet bestFound = maxIndSetHelper(SV, G);
	bestFound.insert(minDegreeVert);

	//Then, iterate through each neighbour of V, and try having it in the IS
	auto neighbourSet = boost::adjacent_vertices(minDegreeVert, G);
	for (auto iter = neighbourSet.first; iter != neighbourSet.second; iter++)
	{
		//Ignore vertices not in the current subgraph
		if (S.contains(*iter))
		{
			auto SNew = S;
			//Erase each neighbour of this neighbour
			//std::cout << "Size " << S.size() << " choosing " << *iter << "\n";
			//And erase the neighbour itself
			SNew.erase(*iter);

			//Erase the min-degree vertex
			//TODO why do we need this?
			//std::cout << "Size " << S.size() << " erasing " << minDegreeVert << "\n";
			SNew.erase(minDegreeVert);

			auto nnSet = boost::adjacent_vertices(minDegreeVert, G);
			for (auto nneighb = nnSet.first; nneighb != nnSet.second; nneighb++)
			{
				//std::cout << "Size " << S.size() << " erasing " << *nneighb << "\n";
				SNew.erase(*nneighb);
			}

			VSet subFound = maxIndSetHelper(SNew, G);
			subFound.insert(*iter);
			//std::cout << "Returning to " << S.size() << "\n";
			if (bestFound.size() < subFound.size())
			{
				bestFound = subFound;
			}
		}

	}
	//std::cout << "Max IS: returning " << S.size() << "\n";
	return bestFound;

}

VSet exactMaxIndSet(const Graph& G)
{
	VSet S(G);
	return maxIndSetHelper(S, G);

}

VSet exactMaxClique(const Graph& G)
{
	auto compInfo = complement_graph(G);
	//std::cout << "Graph complement:\n";
	//boost::write_graphviz(std::cout, compInfo.first);

	VSet iset = exactMaxIndSet(compInfo.first);
	std::vector<Vertex> iVec;
	iset.members(iVec);

	//Translate the compliment vertices into our vertices
	VSet ret;

	for (auto iter = iVec.begin(); iter != iVec.end(); iter++)
	{
		ret.insert(compInfo.second[*iter]);
	}

	return ret;

}

//Approximate algorithms for clique and IS
//using the min-degree heuristic
//We can do this quickly using iteration
VSet approxIndSetHelper(VSet Sarg, const Graph& G)
{
	VSet S = Sarg;
	VSet returnSet;

	//Base case
	while (S.size() > 0)
	{
		std::vector<Vertex> members;
		S.members(members);
		Vertex minDegreeVert = members[0];
		int minDeg = subgraphDegree(members[0], S, G);

		for (auto iter = members.begin(); iter != members.end(); iter++)
		{
			int currentDeg = subgraphDegree(*iter, S, G);
			if (minDeg > currentDeg)
			{
				minDegreeVert = *iter;
				minDeg = currentDeg;
			}
		}

		//Assume the Max-IS contains the min-degree vertex
		//Erase each neighbour of the vertex, and the vertex itself
		auto svNeighbs = boost::adjacent_vertices(minDegreeVert, G);
		for (auto neighb = svNeighbs.first; neighb != svNeighbs.second; neighb++)
		{
			S.erase(*neighb);
		}
		S.erase(minDegreeVert);
		//The min-degree vertex is in our independent set, the neighbours are not
		returnSet.insert(minDegreeVert);
	}

	return returnSet;

}

VSet approxMaxIndSet(const Graph& G)
{
	VSet S(G);
	return approxIndSetHelper(S, G);

}

VSet approxMaxClique(const Graph& G)
{
	auto compInfo = complement_graph(G);
	VSet iset = approxMaxIndSet(compInfo.first);
	std::vector<Vertex> iVec;
	iset.members(iVec);

	//Translate the compliment vertices into our vertices
	VSet ret;

	for (auto iter = iVec.begin(); iter != iVec.end(); iter++)
	{
		ret.insert(compInfo.second[*iter]);
	}

	return ret;

}

//TODO is there a smarter way to do this with boost subgraphs?
int subgraphTWLowerBound(VSet S, const Graph& G, const Graph& GC)
{
	VSet aClique = approxIndSetHelper(S, GC);

	//TODO more advanced techniques?
	return aClique.size();
}

std::pair<Vertex, int> minDegreeSubgraphVert(VSet S, const Graph& G)
{
	std::vector<Vertex> members;
	S.members(members);

	//std::cout << "Members size " << members.size() << "\n";

	Vertex minDegreeVert = members[0];
	int minDeg = subgraphDegree(members[0], S, G);

	//std::cout << "Set members: " << members;

	for (auto iter = members.begin(); iter != members.end(); iter++)
	{
		//std::cout << "Checking degree for " << *iter << "\n";
		int currentDeg = subgraphDegree(*iter, S, G);
		if (minDeg > currentDeg)
		{
			minDegreeVert = *iter;
			minDeg = currentDeg;
		}
	}

	return std::pair<Vertex, int>(minDegreeVert, minDeg);
}

//Fails if S doesn't have at least 2 vertices
std::pair<Vertex, int> minDegreeVertExcept(Vertex v, VSet S, const Graph& G)
{
	std::vector<Vertex> members;
	S.members(members);

	Vertex minDegreeVert;
	int minDeg;

	if (v == members[0])
	{
		minDegreeVert = members[1];
		minDeg = subgraphDegree(members[1], S, G);
	}
	else {
		minDegreeVert = members[0];
		minDeg = subgraphDegree(members[0], S, G);
	}

	for (auto iter = members.begin(); iter != members.end(); iter++)
	{
		//std::cout << "Checking degree for " << *iter << "\n";
		int currentDeg = subgraphDegree(*iter, S, G);
		if (*iter != v && minDeg > currentDeg)
		{
			minDegreeVert = *iter;
			minDeg = currentDeg;
		}
	}

	return std::pair<Vertex, int>(minDegreeVert, minDeg);
}

int MMD(VSet S, const Graph& G)
{
	//std::cout << "Min Degree vertex:" << minDeg(S, G) << "\n";

	VSet H = S;
	int maxmin = 0;
	while (H.size() >= 2)
	{
		Vertex v = minDegreeSubgraphVert(H, G).first;
		//std::cout << "maxmin v degree " << subgraphDegree(v, H, G) << "\n";
		maxmin = std::max(maxmin, subgraphDegree(v, H, G));
		H.erase(v);
	}

	return maxmin;

}

int minDeg(VSet S, const Graph& G)
{
	std::vector<Vertex> memb;
	S.members(memb);
	int minDeg = S.size();
	for (auto iter = memb.begin(); iter != memb.end(); iter++)
	{
		minDeg = std::min(minDeg, subgraphDegree(*iter, S, G));
	}

	return minDeg;

}

int secondSmallestDegree(VSet H, Graph G)
{
	std::vector<Vertex> members;
	H.members(members);
	std::sort(members.begin(), members.end(),
		[G, H](const Vertex & u, const Vertex & v) -> bool
	{
		return subgraphDegree(u, H, G) < subgraphDegree(v, H, G);
	});

	return subgraphDegree(members[1], H, G);
}

Vertex customMinDegreeExcept(Vertex vExclude, VSet H, Graph G)
{
	std::vector<Vertex> members;
	H.members(members);
	std::sort(members.begin(), members.end(),
		[G, H](const Vertex & u, const Vertex & v) -> bool
	{
		return subgraphDegree(u, H, G) < subgraphDegree(v, H, G);
	});

	if (members[0] == vExclude)
	{
		return members[1];
	}
	return members[0];
}

//TODO fix this
//Based on Algorithm 2 from the lower bounds paper
int d2degen(const VSet& SStart, const Graph& G)
{

	int d2D = 0;

	std::vector<Vertex> sMembers;
	SStart.members(sMembers);

	for (Vertex v : sMembers)
	{
		VSet H = SStart;

		while (H.size() >= 2)
		{
			d2D = std::max(d2D, secondSmallestDegree(H, G));
			Vertex u = customMinDegreeExcept(v, H, G);
			//d2D = std::max(d2D, subgraphDegree(v, H, G)); //TODO *iter or w?
			H.erase(u);
		}

	}
	return d2D;

}

ext: cc

max_stars_repo_name: JoeyEremondi/treewidth-memoization

max_issues_repo_name: JoeyEremondi/treewidth-memoization

max_forks_repo_name: JoeyEremondi/treewidth-memoization


text:
#include <boost/mpi/communicator.hpp>

#include "timing.h"
#include "mpi-pyp-topics.hh"

//#include <boost/date_time/posix_time/posix_time_types.hpp>
void MPIPYPTopics::sample_corpus(const MPICorpus& corpus, int samples,
                              int freq_cutoff_start, int freq_cutoff_end,
                              int freq_cutoff_interval,
                              int max_contexts_per_document) {
  Timer timer;

  //int documents = corpus.num_documents();
  /*
  m_mpi_start = 0;
  m_mpi_end = documents;
  if (m_size != 1) {
      assert(documents < std::numeric_limits<int>::max());
      m_mpi_start = (documents / m_size) * m_rank;
      if (m_rank == m_size-1) m_mpi_end = documents;
      else m_mpi_end = (documents / m_size)*(m_rank+1);
  }
  */
  corpus.bounds(&m_mpi_start, &m_mpi_end);
  int local_documents = m_mpi_end - m_mpi_start;

  if (!m_backoff.get()) {
    m_word_pyps.clear();
    m_word_pyps.push_back(MPIPYPs());
  }

  if (m_am_root) std::cerr << "\n Training with " << m_word_pyps.size()-1 << " backoff level"
    << (m_word_pyps.size()>1 ? ":" : "s:") << std::endl;

  for (int i=0; i<(int)m_word_pyps.size(); ++i) {
    m_word_pyps.at(i).reserve(m_num_topics);
    for (int j=0; j<m_num_topics; ++j)
      m_word_pyps.at(i).push_back(new MPIPYP<int>(0.5, 1.0));
  }
  if (m_am_root) std::cerr << std::endl;

  m_document_pyps.reserve(local_documents);
  //m_document_pyps.reserve(corpus.num_documents());
  //for (int j=0; j<corpus.num_documents(); ++j)
  for (int j=0; j<local_documents; ++j)
    m_document_pyps.push_back(new PYP<int>(0.5, 1.0));

  m_topic_p0 = 1.0/m_num_topics;
  m_term_p0 = 1.0/corpus.num_types();
  m_backoff_p0 = 1.0/corpus.num_documents();

  if (m_am_root) std::cerr << " Documents: " << corpus.num_documents() << "("
    << local_documents << ")" << " Terms: " << corpus.num_types() << std::endl;

  int frequency_cutoff = freq_cutoff_start;
  if (m_am_root) std::cerr << " Context frequency cutoff set to " << frequency_cutoff << std::endl;

  timer.Reset();
  // Initialisation pass
  int document_id=0, topic_counter=0;
  for (int i=0; i<local_documents; ++i) {
    document_id = i+m_mpi_start;

  //for (Corpus::const_iterator corpusIt=corpus.begin();
  //     corpusIt != corpus.end(); ++corpusIt, ++document_id) {
    m_corpus_topics.push_back(DocumentTopics(corpus.at(document_id).size(), 0));

    int term_index=0;
    for (Document::const_iterator docIt=corpus.at(document_id).begin();
         docIt != corpus.at(document_id).end(); ++docIt, ++term_index) {
      topic_counter++;
      Term term = *docIt;

      // sample a new_topic
      //int new_topic = (topic_counter % m_num_topics);
      int freq = corpus.context_count(term);
      int new_topic = -1;
      if (freq > frequency_cutoff
          && (!max_contexts_per_document || term_index < max_contexts_per_document)) {
        new_topic = sample(i, term);
        //new_topic = document_id % m_num_topics;

        // add the new topic to the PYPs
        increment(term, new_topic);

        if (m_use_topic_pyp) {
          F p0 = m_topic_pyp.prob(new_topic, m_topic_p0);
          int table_delta = m_document_pyps.at(i).increment(new_topic, p0);
          if (table_delta)
            m_topic_pyp.increment(new_topic, m_topic_p0, rnd);
        }
        else m_document_pyps.at(i).increment(new_topic, m_topic_p0);
      }

      m_corpus_topics.at(i).at(term_index) = new_topic;
    }
  }

  // Synchronise the topic->word counds across the processes.
  synchronise();

  if (m_am_root) std::cerr << "  Initialized in " << timer.Elapsed() << " seconds\n";

  int* randomDocIndices = new int[local_documents];
  for (int i = 0; i < local_documents; ++i)
	  randomDocIndices[i] = i;

  // Sampling phase
  for (int curr_sample=0; curr_sample < samples; ++curr_sample) {
    if (freq_cutoff_interval > 0 && curr_sample != 1
        && curr_sample % freq_cutoff_interval == 1
        && frequency_cutoff > freq_cutoff_end) {
      frequency_cutoff--;
      if (m_am_root) std::cerr << "\n Context frequency cutoff set to " << frequency_cutoff << std::endl;
    }

    if (m_am_root) std::cerr << "\n  -- Sample " << curr_sample << " "; std::cerr.flush();

    // Randomize the corpus indexing array
    int tmp;
    int processed_terms=0;
    for (int i = (local_documents-1); i > 0; --i) {
      //i+1 since j \in [0,i] but rnd() \in [0,1)
    	int j = (int)(rnd() * (i+1));
      assert(j >= 0 && j <= i);
     	tmp = randomDocIndices[i];
    	randomDocIndices[i] = randomDocIndices[j];
    	randomDocIndices[j] = tmp;
    }

    // for each document in the corpus
    for (int rand_doc=0; rand_doc<local_documents; ++rand_doc) {
    	int doc_index = randomDocIndices[rand_doc];
    	int document_id = doc_index + m_mpi_start;
      const Document& doc = corpus.at(document_id);

      // for each term in the document
      int term_index=0;
      Document::const_iterator docEnd = doc.end();
      for (Document::const_iterator docIt=doc.begin();
           docIt != docEnd; ++docIt, ++term_index) {

        if (max_contexts_per_document && term_index > max_contexts_per_document)
          break;

        Term term = *docIt;
        int freq = corpus.context_count(term);
        if (freq < frequency_cutoff)
          continue;

        processed_terms++;

        // remove the prevous topic from the PYPs
        int current_topic = m_corpus_topics.at(doc_index).at(term_index);
        // a negative label mean that term hasn't been sampled yet
        if (current_topic >= 0) {
          decrement(term, current_topic);

          int table_delta = m_document_pyps.at(doc_index).decrement(current_topic);
          if (m_use_topic_pyp && table_delta < 0)
            m_topic_pyp.decrement(current_topic, rnd);
        }

        // sample a new_topic
        int new_topic = sample(doc_index, term);

        // add the new topic to the PYPs
        m_corpus_topics.at(doc_index).at(term_index) = new_topic;
        increment(term, new_topic);

        if (m_use_topic_pyp) {
          F p0 = m_topic_pyp.prob(new_topic, m_topic_p0);
          int table_delta = m_document_pyps.at(doc_index).increment(new_topic, p0);
          if (table_delta)
            m_topic_pyp.increment(new_topic, m_topic_p0, rnd);
        }
        else m_document_pyps.at(doc_index).increment(new_topic, m_topic_p0);
      }
      if (document_id && document_id % 10000 == 0) {
        if (m_am_root) std::cerr << "."; std::cerr.flush();
      }
    }
    std::cerr << "|"; std::cerr.flush();

    // Synchronise the topic->word counds across the processes.
    synchronise();

    if (m_am_root) std::cerr << " ||| sampled " << processed_terms << " terms.";

    if (curr_sample != 0 && curr_sample % 10 == 0) {
      if (m_am_root) std::cerr << " ||| time=" << (timer.Elapsed() / 10.0) << " sec/sample" << std::endl;
      timer.Reset();
      if (m_am_root) std::cerr << "     ... Resampling hyperparameters"; std::cerr.flush();

      // resample the hyperparamters
      F log_p=0.0;
      for (std::vector<MPIPYPs>::iterator levelIt=m_word_pyps.begin();
           levelIt != m_word_pyps.end(); ++levelIt) {
        for (MPIPYPs::iterator pypIt=levelIt->begin();
             pypIt != levelIt->end(); ++pypIt) {
          pypIt->resample_prior(rnd);
          log_p += pypIt->log_restaurant_prob();
        }
      }

      for (PYPs::iterator pypIt=m_document_pyps.begin();
           pypIt != m_document_pyps.end(); ++pypIt) {
        pypIt->resample_prior(rnd);
        log_p += pypIt->log_restaurant_prob();
      }

      if (m_use_topic_pyp) {
        m_topic_pyp.resample_prior(rnd);
        log_p += m_topic_pyp.log_restaurant_prob();
      }

      std::cerr.precision(10);
      if (m_am_root) std::cerr << " ||| LLH=" << log_p << " ||| resampling time=" << timer.Elapsed() << " sec" << std::endl;
      timer.Reset();

      int k=0;
      if (m_am_root) std::cerr << "Topics distribution: ";
      std::cerr.precision(2);
      for (MPIPYPs::iterator pypIt=m_word_pyps.front().begin();
           pypIt != m_word_pyps.front().end(); ++pypIt, ++k) {
        if (m_am_root && k % 5 == 0) std::cerr << std::endl << '\t';
        if (m_am_root) std::cerr << "<" << k << ":" << pypIt->num_customers() << ","
          << pypIt->num_types() << "," << m_topic_pyp.prob(k, m_topic_p0) << "> ";
      }
      std::cerr.precision(4);
      if (m_am_root) std::cerr << std::endl;
    }
  }
  delete [] randomDocIndices;
}

void MPIPYPTopics::synchronise() {
  // Synchronise the topic->word counds across the processes.
  //for (std::vector<MPIPYPs>::iterator levelIt=m_word_pyps.begin();
  //     levelIt != m_word_pyps.end(); ++levelIt) {
//  std::vector<MPIPYPs>::iterator levelIt=m_word_pyps.begin();
//  {
//    for (MPIPYPs::iterator pypIt=levelIt->begin(); pypIt != levelIt->end(); ++pypIt) {
    for (size_t label=0; label < m_word_pyps.at(0).size(); ++label) {
      MPIPYP<int>& pyp = m_word_pyps.at(0).at(label);

      //if (!m_am_root) boost::mpi::communicator().barrier();
      //std::cerr << "Before Sync Process " << m_rank << ":";
      //pyp.debug_info(std::cerr); std::cerr << std::endl;
      //if (m_am_root) boost::mpi::communicator().barrier();

      MPIPYP<int>::dish_delta_type delta;
      pyp.synchronise(&delta);

      for (MPIPYP<int>::dish_delta_type::const_iterator it=delta.begin(); it != delta.end(); ++it) {
        int count = it->second;
        if (count > 0)
          for (int i=0; i < count; ++i) increment(it->first, label);
        if (count < 0)
          for (int i=0; i > count; --i) decrement(it->first, label);
      }
      pyp.reset_deltas();

      //if (!m_am_root) boost::mpi::communicator().barrier();
      //std::cerr << "After Sync Process " << m_rank << ":";
      //pyp.debug_info(std::cerr); std::cerr << std::endl;
      //if (m_am_root) boost::mpi::communicator().barrier();
    }
//  }
    // Synchronise the hierarchical topic pyp
    MPIPYP<int>::dish_delta_type topic_delta;
    m_topic_pyp.synchronise(&topic_delta);
    for (MPIPYP<int>::dish_delta_type::const_iterator it=topic_delta.begin(); it != topic_delta.end(); ++it) {
      int count = it->second;
      if (count > 0)
        for (int i=0; i < count; ++i)
          m_topic_pyp.increment(it->first, m_topic_p0, rnd);
      if (count < 0)
        for (int i=0; i > count; --i)
          m_topic_pyp.decrement(it->first, rnd);
    }
    m_topic_pyp.reset_deltas();
}

void MPIPYPTopics::decrement(const Term& term, int topic, int level) {
  //std::cerr << "MPIPYPTopics::decrement(" << term << "," << topic << "," << level << ")" << std::endl;
  m_word_pyps.at(level).at(topic).decrement(term, rnd);
  if (m_backoff.get()) {
    Term backoff_term = (*m_backoff)[term];
    if (!m_backoff->is_null(backoff_term))
      decrement(backoff_term, topic, level+1);
  }
}

void MPIPYPTopics::increment(const Term& term, int topic, int level) {
  //std::cerr << "MPIPYPTopics::increment(" << term << "," << topic << "," << level << ")" << std::endl;
  m_word_pyps.at(level).at(topic).increment(term, word_pyps_p0(term, topic, level), rnd);

  if (m_backoff.get()) {
    Term backoff_term = (*m_backoff)[term];
    if (!m_backoff->is_null(backoff_term))
      increment(backoff_term, topic, level+1);
  }
}

int MPIPYPTopics::sample(const DocumentId& doc, const Term& term) {
  // First pass: collect probs
  F sum=0.0;
  std::vector<F> sums;
  for (int k=0; k<m_num_topics; ++k) {
    F p_w_k = prob(term, k);

    F topic_prob = m_topic_p0;
    if (m_use_topic_pyp) topic_prob = m_topic_pyp.prob(k, m_topic_p0);

    //F p_k_d = m_document_pyps[doc].prob(k, topic_prob);
    F p_k_d = m_document_pyps.at(doc).unnormalised_prob(k, topic_prob);

    sum += (p_w_k*p_k_d);
    sums.push_back(sum);
  }
  // Second pass: sample a topic
  F cutoff = rnd() * sum;
  for (int k=0; k<m_num_topics; ++k) {
    if (cutoff <= sums[k])
      return k;
  }
  std::cerr << cutoff << " " << sum << std::endl;
  assert(false);
}

MPIPYPTopics::F MPIPYPTopics::word_pyps_p0(const Term& term, int topic, int level) const {
  //for (int i=0; i<level+1; ++i) std::cerr << "  ";
  //std::cerr << "MPIPYPTopics::word_pyps_p0(" << term << "," << topic << "," << level << ")" << std::endl;

  F p0 = m_term_p0;
  if (m_backoff.get()) {
    //static F fudge=m_backoff_p0; // TODO

    Term backoff_term = (*m_backoff)[term];
    if (!m_backoff->is_null(backoff_term)) {
      assert (level < m_backoff->order());
      //p0 = (1.0/(double)m_backoff->terms_at_level(level))*prob(backoff_term, topic, level+1);
      p0 = prob(backoff_term, topic, level+1);
    }
    else
      p0 = m_term_p0;
  }
  //for (int i=0; i<level+1; ++i) std::cerr << "  ";
  //std::cerr << "MPIPYPTopics::word_pyps_p0(" << term << "," << topic << "," << level << ") = " << p0 << std::endl;
  return p0;
}

MPIPYPTopics::F MPIPYPTopics::prob(const Term& term, int topic, int level) const {
  //for (int i=0; i<level+1; ++i) std::cerr << "  ";
  //std::cerr << "MPIPYPTopics::prob(" << term << "," << topic << "," << level << " " << factor << ")" << std::endl;

  F p0 = word_pyps_p0(term, topic, level);
  F p_w_k = m_word_pyps.at(level).at(topic).prob(term, p0);

  //for (int i=0; i<level+1; ++i) std::cerr << "  ";
  //std::cerr << "MPIPYPTopics::prob(" << term << "," << topic << "," << level << ") = " << p_w_k << std::endl;

  return p_w_k;
}

int MPIPYPTopics::max_topic() const {
  if (!m_use_topic_pyp)
    return -1;

  F current_max=0.0;
  int current_topic=-1;
  for (int k=0; k<m_num_topics; ++k) {
    F prob = m_topic_pyp.prob(k, m_topic_p0);
    if (prob > current_max) {
      current_max = prob;
      current_topic = k;
    }
  }
  assert(current_topic >= 0);
  assert(current_max >= 0);
  return current_max;
}

std::pair<int,MPIPYPTopics::F> MPIPYPTopics::max(const DocumentId& true_doc) const {
  //std::cerr << "MPIPYPTopics::max(" << doc << "," << term << ")" << std::endl;
  // collect probs
  F current_max=0.0;
  DocumentId local_doc = true_doc - m_mpi_start;
  int current_topic=-1;
  for (int k=0; k<m_num_topics; ++k) {
    //F p_w_k = prob(term, k);

    F topic_prob = m_topic_p0;
    if (m_use_topic_pyp)
      topic_prob = m_topic_pyp.prob(k, m_topic_p0);

    F prob = 0;
    if (local_doc < 0) prob = topic_prob;
    else               prob = m_document_pyps.at(local_doc).prob(k, topic_prob);

    if (prob > current_max) {
      current_max = prob;
      current_topic = k;
    }
  }
  assert(current_topic >= 0);
  assert(current_max >= 0);
  return std::make_pair(current_topic, current_max);
}

std::pair<int,MPIPYPTopics::F> MPIPYPTopics::max(const DocumentId& true_doc, const Term& term) const {
  //std::cerr << "MPIPYPTopics::max(" << doc << "," << term << ")" << std::endl;
  // collect probs
  F current_max=0.0;
  DocumentId local_doc = true_doc - m_mpi_start;
  int current_topic=-1;
  for (int k=0; k<m_num_topics; ++k) {
    F p_w_k = prob(term, k);

    F topic_prob = m_topic_p0;
    if (m_use_topic_pyp)
      topic_prob = m_topic_pyp.prob(k, m_topic_p0);

    F p_k_d = 0;
    if (local_doc < 0) p_k_d = topic_prob;
    else               p_k_d = m_document_pyps.at(local_doc).prob(k, topic_prob);

    F prob = (p_w_k*p_k_d);
    if (prob > current_max) {
      current_max = prob;
      current_topic = k;
    }
  }
  assert(current_topic >= 0);
  assert(current_max >= 0);
  return std::make_pair(current_topic, current_max);
}

std::ostream& MPIPYPTopics::print_document_topics(std::ostream& out) const {
  for (CorpusTopics::const_iterator corpusIt=m_corpus_topics.begin();
       corpusIt != m_corpus_topics.end(); ++corpusIt) {
    int term_index=0;
    for (DocumentTopics::const_iterator docIt=corpusIt->begin();
         docIt != corpusIt->end(); ++docIt, ++term_index) {
      if (term_index) out << " ";
      out << *docIt;
    }
    out << std::endl;
  }
  return out;
}

std::ostream& MPIPYPTopics::print_topic_terms(std::ostream& out) const {
  for (PYPs::const_iterator pypsIt=m_word_pyps.front().begin();
       pypsIt != m_word_pyps.front().end(); ++pypsIt) {
    int term_index=0;
    for (PYP<int>::const_iterator termIt=pypsIt->begin();
         termIt != pypsIt->end(); ++termIt, ++term_index) {
      if (term_index) out << " ";
      out << termIt->first << ":" << termIt->second;
    }
    out << std::endl;
  }
  return out;
}

max_stars_repo_name: agesmundo/FasterCubePruning

max_issues_repo_name: jhclark/cdec

max_forks_repo_name: jhclark/cdec


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_MEMORY_FUNCTIONS_SIMD_SSE_AVX_STORE_HPP_INCLUDED
#define BOOST_SIMD_MEMORY_FUNCTIONS_SIMD_SSE_AVX_STORE_HPP_INCLUDED
#ifdef BOOST_SIMD_HAS_AVX_SUPPORT

#include <boost/simd/memory/functions/store.hpp>
#include <boost/simd/memory/iterator_category.hpp>
#include <boost/dispatch/functor/preprocessor/call.hpp>
#include <boost/dispatch/meta/scalar_of.hpp>
#include <boost/simd/meta/is_pointing_to.hpp>

namespace boost { namespace simd { namespace ext
{
  /// INTERNAL ONLY - SIMD store double without offset
  BOOST_DISPATCH_IMPLEMENT          ( store_
                                    , boost::simd::tag::avx_
                                    , (A0)(A1)
                                    , ((simd_ < double_<A0>
                                              , boost::simd::tag::avx_
                                              >
                                      ))
                                      (iterator_< scalar_< double_<A1> > >)
                                    )
  {
    typedef void result_type;

    BOOST_FORCEINLINE result_type operator()(__m256d a0, A1 a1) const
    {
      _mm256_storeu_pd(a1,a0);
    }
  };

  /// INTERNAL ONLY - SIMD store float without offset
  BOOST_DISPATCH_IMPLEMENT          ( store_
                                    , boost::simd::tag::avx_
                                    , (A0)(A1)
                                    , ((simd_ < single_<A0>
                                              , boost::simd::tag::avx_
                                              >
                                      ))
                                      (iterator_< scalar_< single_<A1> > >)
                                    )
  {
    typedef void result_type;

    BOOST_FORCEINLINE result_type operator()(__m256 a0, A1 a1) const
    {
      _mm256_storeu_ps(a1,a0);
    }
  };

  /// INTERNAL ONLY - SIMD store integers without offset
  BOOST_DISPATCH_IMPLEMENT_IF         ( store_
                                      , boost::simd::tag::avx_
                                      , (A0)(A1)
                                      , ( simd::meta::is_pointing_to
                                          < A1
                                          , typename  dispatch::meta
                                                    ::scalar_of<A0>::type
                                          >
                                        )
                                      , ((simd_ < integer_<A0>
                                                , boost::simd::tag::avx_
                                                >
                                        ))
                                        (iterator_< scalar_< integer_<A1> > >)
                                      )
  {
    typedef void result_type;

    BOOST_FORCEINLINE result_type operator()(__m256i a0, A1 a1) const
    {
      _mm256_storeu_si256(reinterpret_cast<__m256i*>(a1), a0);
    }
  };
} } }

#endif
#endif

ext: hpp


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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 "service/impala-internal-service.h"

#include <boost/lexical_cast.hpp>

#include "common/status.h"
#include "gutil/strings/substitute.h"
#include "service/impala-server.h"
#include "runtime/query-state.h"
#include "runtime/fragment-instance-state.h"
#include "runtime/exec-env.h"

#include "common/names.h"

using namespace impala;

DECLARE_string(debug_actions);

ImpalaInternalService::ImpalaInternalService() {
  impala_server_ = ExecEnv::GetInstance()->impala_server();
  DCHECK(impala_server_ != nullptr);
}

template <typename T> void SetUnknownIdError(
    const string& id_type, const TUniqueId& id, T* status_container) {
  Status status(ErrorMsg(TErrorCode::INTERNAL_ERROR,
      Substitute("Unknown $0 id: $1", id_type, PrintId(id))));
  status.SetTStatus(status_container);
}


text:
#include "PointSource.h"

#include "io/PointcloudFile.h"
#include "terminal/stdout_helper.h"

#include <boost/format.hpp>

PointSource::PointSource(std::vector<fs::path> files,
                         util::IgnoreErrors errors_to_ignore)
  : _files(std::move(files))
  , _errors_to_ignore(errors_to_ignore)
{
  // Try to open the first file (the first file that can be opened)
  _file_cursor = std::begin(_files);
  while (_file_cursor != std::end(_files) && !try_open_file(_file_cursor)) {
    ++_file_cursor;
  }
}

std::optional<PointBuffer>
PointSource::read_next(size_t count, const PointAttributes& attributes)
{
  if (!_current_file)
    return std::nullopt;

  return std::visit(
    [this, count, &attributes](auto& typed_file) -> std::optional<PointBuffer> {
      const auto& metadata = pc::metadata(typed_file);
      auto point_buffer = std::visit(
        [this, count, &attributes, &typed_file, &metadata](
          auto& typed_file_cursor) -> PointBuffer {
          PointBuffer point_buffer;
          try {
            typed_file_cursor = pc::read_points(
              typed_file_cursor, count, metadata, attributes, point_buffer);
          } catch (const std::exception& ex) {
            if (_errors_to_ignore & util::IgnoreErrors::CorruptedFiles) {
              // Drop this file, move on to next file
              util::write_log((boost::format("Could not read points from "
                                             "file %1%\n\tcaused by: %2%\n") %
                               _file_cursor->string() % ex.what())
                                .str());
              typed_file_cursor = std::cend(typed_file);
            } else {
              throw util::chain_error(
                ex,
                (boost::format("Could not read points from file %1%") %
                 _file_cursor->string())
                  .str());
            }
          }

          // If at end of current file, move to next file
          if (typed_file_cursor == std::cend(typed_file)) {
            move_to_next_file();
          }

          return point_buffer;
        },
        *_current_file_cursor);

      // Apply all transformations
      for (auto& transformation : _transformations) {
        transformation(point_buffer);
      }

      return { std::move(point_buffer) };
    },
    *_current_file);
}

void
PointSource::add_transformation(Transform transform)
{
  _transformations.push_back(std::move(transform));
}

bool
PointSource::try_open_file(std::vector<fs::path>::const_iterator file_cursor)
{
  if (file_cursor == std::end(_files))
    return false;

  return open_point_file(*file_cursor)
    .map([this](PointFile point_file) mutable {
      return std::visit(
        [this](auto& typed_file) mutable {
          _current_file_cursor = { std::cbegin(typed_file) };
          _current_file = { std::move(typed_file) };
          return true;
        },
        point_file);
    })
    .or_else([this](const util::ErrorChain& error_chain) {
      if (_errors_to_ignore & util::IgnoreErrors::InaccessibleFiles) {
        util::write_log((boost::format("Opening next point file failed: %1%") %
                         error_chain.what())
                          .str());
        return;
      }

      throw util::chain_error(error_chain, "Opening next point file failed");
    })
    .value_or(false);
}

bool
PointSource::move_to_next_file()
{
  ++_file_cursor;
  while (_file_cursor != std::end(_files) && !try_open_file(_file_cursor)) {
    ++_file_cursor;
  }
  if (_file_cursor == std::end(_files)) {
    _current_file = std::nullopt;
    _current_file_cursor = std::nullopt;
    return false;
  }
  return true;
}

#pragma region MultiReaderPointSource
MultiReaderPointSource::MultiReaderPointSource(
  std::vector<fs::path> files,
  util::IgnoreErrors errors_to_ignore)
  : _files(std::move(files))
  , _next_files(std::begin(_files), std::end(_files))
  , _errors_to_ignore(errors_to_ignore)
  , _open_files_lock(std::make_unique<std::mutex>())
{
  std::cout << "Input files:\n";
  for (auto& file : _files) {
    std::cout << file << "\n";
  }
}

std::optional<MultiReaderPointSource::PointSourceHandle>
MultiReaderPointSource::lock_source()
{
  std::lock_guard guard{ *_open_files_lock };

  const auto next_available_file = find_next_available_open_file();
  if (next_available_file) {
    next_available_file->available = false;
    return std::make_optional(PointSourceHandle{ next_available_file, this });
  }

  auto next_file = try_open_next_file();
  if (!next_file) {
    return std::nullopt;
  }

  // Lock new file
  next_file->available = false;
  PointSourceHandle handle{ next_file.get(), this };

  _open_files.push_back(std::move(next_file));

  return handle;
}

std::optional<MultiReaderPointSource::PointSourceHandle>
MultiReaderPointSource::lock_specific_source(const fs::path& file_name)
{
  std::lock_guard guard{ *_open_files_lock };

  // Check first if file_name is in _open_files
  const auto open_file_record_or_failure = get_specific_open_file(file_name);

  if (open_file_record_or_failure.has_value()) {
    auto file_record = open_file_record_or_failure.value();
    file_record->available = false;
    return std::make_optional(PointSourceHandle{ file_record, this });
  }

  const auto reason_for_failure = open_file_record_or_failure.error();
  switch (reason_for_failure) {
    case GetSpecificOpenFileFailure::NotAvailable:
      throw std::runtime_error{
        "Requested file source is already locked by another thread!"
      };
    case GetSpecificOpenFileFailure::NotYetOpened: {
      auto opened_file = try_open_specific_file(file_name);
      if (!opened_file) {
        return std::nullopt;
      }

      opened_file->available = false;
      PointSourceHandle handle{ opened_file.get(), this };

      _open_files.push_back(std::move(opened_file));

      return handle;
    }
    default:
      throw std::runtime_error{
        "Unrecognized GetSpecificOpenFileFailure constant"
      };
  }
}

void
MultiReaderPointSource::release_source(const PointSourceHandle& source_handle)
{
  std::lock_guard guard{ *_open_files_lock };

  // Find matching PointFileEntry
  const auto matching_entry_iter =
    std::find_if(std::begin(_open_files),
                 std::end(_open_files),
                 [&source_handle](const auto& entry) {
                   return entry.get() == source_handle._point_file_entry;
                 });
  if (matching_entry_iter == std::end(_open_files)) {
    throw std::invalid_argument{
      "source_handle does not refer to an open file!"
    };
  }

  auto& matching_entry = **matching_entry_iter;
  // If the file is at the end, remove it from _open_files
  if (point_file_entry_is_at_end(matching_entry)) {
    _open_files.erase(matching_entry_iter);
    return;
  }

  // Otherwise we mark the file as available
  matching_entry.available = true;
}

size_t
MultiReaderPointSource::max_concurrent_reads()
{
  std::lock_guard guard{ *_open_files_lock };
  const auto open_files =
    std::count_if(std::begin(_open_files),
                  std::end(_open_files),
                  [](const auto& open_file) { return open_file->available; });
  const auto remaining_files = _next_files.size();
  return open_files + remaining_files;
}

void
MultiReaderPointSource::add_transformation(Transform transform)
{
  _transformations.push_back(std::move(transform));
}

std::unique_ptr<MultiReaderPointSource::PointFileEntry>
MultiReaderPointSource::try_open_next_file()
{
  const auto next_file_iter = std::begin(_next_files);
  if (next_file_iter == std::end(_next_files))
    return nullptr;

  return do_open_file(next_file_iter);
}

std::unique_ptr<MultiReaderPointSource::PointFileEntry>
MultiReaderPointSource::try_open_specific_file(const fs::path& file)
{
  const auto file_iter = _next_files.find(file);
  if (file_iter == std::end(_next_files)) {
    return nullptr;
  }

  return do_open_file(file_iter);
}

std::unique_ptr<MultiReaderPointSource::PointFileEntry>
MultiReaderPointSource::do_open_file(
  std::unordered_set<fs::path, util::PathHash>::iterator file_iter)
{
  const auto file_path = *file_iter;
  _next_files.erase(file_iter);

  const auto file_index = static_cast<size_t>(
    std::distance(std::begin(_files),
                  std::find(std::begin(_files), std::end(_files), file_path)));

  return open_point_file(file_path)
    .map([this, &file_path, file_index](PointFile point_file) mutable {
      return std::make_unique<PointFileEntry>(
        std::move(point_file), file_path, file_index);
    })
    .or_else([this](const util::ErrorChain& error_chain) {
      if (_errors_to_ignore & util::IgnoreErrors::InaccessibleFiles) {
        util::write_log((boost::format("Opening next point file failed: %1%") %
                         error_chain.what())
                          .str());
        return;
      }

      throw util::chain_error(error_chain, "Opening next point file failed");
    })
    .value_or(nullptr);
}

MultiReaderPointSource::PointFileEntry*
MultiReaderPointSource::find_next_available_open_file()
{
  const auto next_available_file_iter = std::find_if(
    std::begin(_open_files),
    std::end(_open_files),
    [](const auto& point_file_entry) { return point_file_entry->available; });
  if (next_available_file_iter == std::end(_open_files)) {
    return nullptr;
  }

  return next_available_file_iter->get();
}

tl::expected<MultiReaderPointSource::PointFileEntry*,
             MultiReaderPointSource::GetSpecificOpenFileFailure>
MultiReaderPointSource::get_specific_open_file(const fs::path& file) const
{
  const auto is_open_iter =
    std::find_if(std::begin(_open_files),
                 std::end(_open_files),
                 [&file](const auto& point_file_entry) {
                   return point_file_entry->file_path == file;
                 });

  if (is_open_iter == std::end(_open_files)) {
    return tl::make_unexpected(GetSpecificOpenFileFailure::NotYetOpened);
  }

  if (!(*is_open_iter)->available) {
    return tl::make_unexpected(GetSpecificOpenFileFailure::NotAvailable);
  }

  return { is_open_iter->get() };
}

bool
MultiReaderPointSource::point_file_entry_is_at_end(
  const PointFileEntry& point_file_entry) const
{
  return std::visit(
    [&point_file_entry](const auto& typed_file) {
      return std::visit(
        [&typed_file](const auto& cursor) {
          return cursor == std::cend(typed_file);
        },
        point_file_entry.cursor);
    },
    point_file_entry.point_file);
}

std::optional<PointBuffer>
MultiReaderPointSource::PointSourceHandle::read_next(
  size_t count,
  const PointAttributes& point_attributes)
{
  // The std::visit syntax makes me want to cry
  return std::visit(
    [count, &point_attributes, this](auto& typed_cursor) {
      return std::visit(
        [count, &point_attributes, &typed_cursor, this](
          auto& typed_file) -> std::optional<PointBuffer> {
          PointBuffer point_buffer;
          try {
            typed_cursor = pc::read_points(typed_cursor,
                                           count,
                                           pc::metadata(typed_file),
                                           point_attributes,
                                           point_buffer);
          } catch (const std::exception& ex) {
            if (_multi_reader_source->_errors_to_ignore &
                util::IgnoreErrors::CorruptedFiles) {
              // Log error and move this file to end, we assume that the file is
              // dead now
              util::write_log((boost::format("Could not read points from "
                                             "file %1%\n\tcaused by: %2%\n") %
                               pc::source(typed_file) % ex.what())
                                .str());
              typed_cursor = std::cend(typed_file);
              return std::nullopt;
            } else {
              throw util::chain_error(
                ex,
                (boost::format("Could not read points from file %1%") %
                 pc::source(typed_file))
                  .str());
            }
          }

          for (auto& transformation : _multi_reader_source->_transformations) {
            transformation(
              { std::begin(point_buffer), std::end(point_buffer) });
          }

          return { std::move(point_buffer) };
        },
        _point_file_entry->point_file);
    },
    _point_file_entry->cursor);
}

PointBuffer::PointIterator
MultiReaderPointSource::PointSourceHandle::read_next_into(
  util::Range<PointBuffer::PointIterator> point_range,
  const PointAttributes& point_attributes)
{
  return std::visit(
    [point_range, &point_attributes, this](auto& typed_cursor) {
      return std::visit(
        [point_range, &point_attributes, &typed_cursor, this](
          auto& typed_file) -> PointBuffer::PointIterator {
          PointBuffer::PointIterator new_end_of_point_range =
            std::begin(point_range);
          try {
            auto [_new_file_iter, _new_out_iter] =
              pc::read_points_into(typed_cursor,
                                   std::cend(typed_file),
                                   pc::metadata(typed_file),
                                   point_attributes,
                                   point_range);

            for (auto point_ref : point_range) {
              *point_ref.point_source_id() =
                static_cast<uint16_t>(_point_file_entry->file_index);
            }

            typed_cursor = _new_file_iter;
            new_end_of_point_range = _new_out_iter;
          } catch (const std::exception& ex) {
            if (_multi_reader_source->_errors_to_ignore &
                util::IgnoreErrors::CorruptedFiles) {
              // Log error and move this file to end, we assume that the file is
              // dead now
              util::write_log((boost::format("Could not read points from "
                                             "file %1%\n\tcaused by: %2%\n") %
                               pc::source(typed_file) % ex.what())
                                .str());
              typed_cursor = std::cend(typed_file);
              return std::begin(point_range);
            } else {
              throw util::chain_error(
                ex,
                (boost::format("Could not read points from file %1%") %
                 pc::source(typed_file))
                  .str());
            }
          }

          for (auto& transformation : _multi_reader_source->_transformations) {
            transformation({ std::begin(point_range), new_end_of_point_range });
          }

          return new_end_of_point_range;
        },
        _point_file_entry->point_file);
    },
    _point_file_entry->cursor);
}

MultiReaderPointSource::PointSourceHandle::PointSourceHandle(
  PointFileEntry* point_file_entry,
  MultiReaderPointSource* multi_reader_source)
  : _point_file_entry(point_file_entry)
  , _multi_reader_source(multi_reader_source)
{}

MultiReaderPointSource::PointFileEntry::PointFileEntry(
  PointFile file,
  const fs::path& file_path,
  size_t file_index)
  : point_file(std::move(file))
  , available(true)
  , file_path(file_path)
  , file_index(file_index)
{
  // Get an iterator to the start of the file and store it
  //( std::variant syntax is so nasty :( )
  std::visit(
    [this](auto& typed_file_cursor) {
      std::visit([&typed_file_cursor](
                   const auto& file) { typed_file_cursor = std::begin(file); },
                 point_file);
    },
    cursor);
}

#pragma endregion

ext: cpp

max_stars_repo_name: igd-geo/schwarzwald

max_issues_repo_name: igd-geo/schwarzwald

max_forks_repo_name: igd-geo/schwarzwald


text:
//  Copyright John Maddock 2006.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/special_functions/erf.hpp>
#include <boost/math/constants/constants.hpp>
#include <map>
#include <iostream>
#include <iomanip>
#include "mp_t.hpp"

using namespace std;
using namespace boost::math;

//
// This program calculates the coefficients of the polynomials
// used for the regularized incomplete gamma functions gamma_p
// and gamma_q when parameter a is large, and sigma is small
// (where sigma = fabs(1 - x/a) ).
//
// See "The Asymptotic Expansion of the Incomplete Gamma Functions"
// N. M. Temme.
// Siam J. Math Anal. Vol 10 No 4, July 1979, p757.
// Coeffient calculation is described from Eq 3.8 (p762) onwards.
//

//
// Alpha:
//
mp_t alpha(unsigned k)
{
   static map<unsigned, mp_t> data;
   if(data.empty())
   {
      data[1] = 1;
   }

   map<unsigned, mp_t>::const_iterator pos = data.find(k);
   if(pos != data.end())
      return (*pos).second;
   //
   // OK try and calculate the value:
   //
   mp_t result = alpha(k-1);
   for(unsigned j = 2; j <= k-1; ++j)
   {
      result -= j * alpha(j) * alpha(k-j+1);
   }
   result /= (k+1);
   data[k] = result;
   return result;
}

mp_t gamma(unsigned k)
{
   static map<unsigned, mp_t> data;

   map<unsigned, mp_t>::const_iterator pos = data.find(k);
   if(pos != data.end())
      return (*pos).second;

   mp_t result = (k&1) ? -1 : 1;

   for(unsigned i = 1; i <= (2 * k + 1); i += 2)
      result *= i;
   result *= alpha(2 * k + 1);
   data[k] = result;
   return result;
}

mp_t Coeff(unsigned n, unsigned k)
{
   map<unsigned, map<unsigned, mp_t> > data;
   if(data.empty())
      data[0][0] = mp_t(-1) / 3;

   map<unsigned, map<unsigned, mp_t> >::const_iterator p1 = data.find(n);
   if(p1 != data.end())
   {
      map<unsigned, mp_t>::const_iterator p2 = p1->second.find(k);
      if(p2 != p1->second.end())
      {
         return p2->second;
      }
   }

   //
   // If we don't have the value, calculate it:
   //
   if(k == 0)
   {
      // special case:
      mp_t result = (n+2) * alpha(n+2);
      data[n][k] = result;
      return result;
   }
   // general case:
   mp_t result = gamma(k) * Coeff(n, 0) + (n+2) * Coeff(n+2, k-1);
   data[n][k] = result;
   return result;
}

void calculate_terms(double sigma, double a, unsigned bits)
{
   cout << endl << endl;
   cout << "Sigma:        " << sigma << endl;
   cout << "A:            " << a << endl;
   double lambda = 1 - sigma;
   cout << "Lambda:       " << lambda << endl;
   double y = a * (-sigma - log1p(-sigma));
   cout << "Y:            " << y << endl;
   double z = -sqrt(2 * (-sigma - log1p(-sigma)));
   cout << "Z:            " << z << endl;
   double dom = erfc(sqrt(y)) / 2;
   cout << "Erfc term:    " << dom << endl;
   double lead = exp(-y) / sqrt(2 * constants::pi<double>() * a);
   cout << "Remainder factor: " << lead << endl;
   double eps = ldexp(1.0, 1 - static_cast<int>(bits));
   double target = dom * eps / lead;
   cout << "Target smallest term: " << target << endl;

   unsigned max_n = 0;

   for(unsigned n = 0; n < 10000; ++n)
   {
      double term = tools::real_cast<double>(Coeff(n, 0) * pow(z, (double)n));
      if(fabs(term) < target)
      {
         max_n = n-1;
         break;
      }
   }
   cout << "Max n required:  " << max_n << endl;

   unsigned max_k;
   for(unsigned k = 1; k < 10000; ++k)
   {
      double term = tools::real_cast<double>(Coeff(0, k) * pow(a, -((double)k)));
      if(fabs(term) < target)
      {
         max_k = k-1;
         break;
      }
   }
   cout << "Max k required:  " << max_k << endl << endl;

   bool code = false;
   cout << "Print code [0|1]? ";
   cin >> code;

   int prec = 2 + (static_cast<double>(bits) * 3010LL)/10000;
   std::cout << std::scientific << std::setprecision(40);

   if(code)
   {
      cout << "   T workspace[" << max_k+1 << "];\n\n";
      for(unsigned k = 0; k <= max_k; ++k)
      {
         cout <<
            "   static const T C" << k << "[] = {\n";
         for(unsigned n = 0; n < 10000; ++n)
         {
            double term = tools::real_cast<double>(Coeff(n, k) * pow(a, -((double)k)) * pow(z, (double)n));
            if(fabs(term) < target)
            {
               break;
            }
            cout << "      " << Coeff(n, k) << "L,\n";
         }
         cout <<
            "   };\n"
            "   workspace[" << k << "] = tools::evaluate_polynomial(C" << k << ", z);\n\n";
      }
      cout << "   T result = tools::evaluate_polynomial(workspace, 1/a);\n\n";
   }
}

int main()
{
   bool cont;
   do{
      cont  = false;
      double sigma;
      cout << "Enter max value for sigma (sigma = |1 - x/a|): ";
      cin >> sigma;
      double a;
      cout << "Enter min value for a: ";
      cin >> a;
      unsigned precision;
      cout << "Enter number of bits precision required: ";
      cin >> precision;

      calculate_terms(sigma, a, precision);

      cout << "Try again[0|1]: ";
      cin >> cont;

   }while(cont);

   return 0;
}


text:
// Copyright (c) 2019 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#define BOOST_TEST_MODULE Bitcoin Seeder Test Suite

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(seeder_tests)

BOOST_AUTO_TEST_CASE(test_stub) {
    BOOST_CHECK_EQUAL(true, true);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: stibits-inc/bitcoin-abc

max_issues_repo_name: rkalis/bitcoin-abc-benchin

max_forks_repo_name: rkalis/bitcoin-abc-benchin


text:
// Copyright 2008 Christophe Henry
// henry UNDERSCORE christophe AT hotmail DOT com
// This is an extended version of the state machine available in the boost::mpl library
// Distributed under the same license as the original.
// Copyright for the original version:
// Copyright 2005 David Abrahams and Aleksey Gurtovoy. Distributed
// under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_MSM_FRONT_EUML_STT_GRAMMAR_H
#define BOOST_MSM_FRONT_EUML_STT_GRAMMAR_H

#include <boost/msm/front/euml/common.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/eval_if.hpp>

#include <boost/msm/front/euml/operator.hpp>
#include <boost/msm/front/euml/guard_grammar.hpp>
#include <boost/msm/front/euml/state_grammar.hpp>

namespace proto = boost::proto;

namespace boost { namespace msm { namespace front { namespace euml
{

template <class SOURCE,class EVENT,class TARGET,class ACTION=none,class GUARD=none>
struct TempRow
{
    typedef SOURCE  Source;
    typedef EVENT   Evt;
    typedef TARGET  Target;
    typedef ACTION  Action;
    typedef GUARD   Guard;
};

template <class TEMP_ROW>
struct convert_to_row
{
    typedef Row<typename TEMP_ROW::Source,typename TEMP_ROW::Evt,typename TEMP_ROW::Target,
                typename TEMP_ROW::Action,typename TEMP_ROW::Guard> type;
};
template <class TEMP_ROW>
struct convert_to_internal_row
{
    typedef Internal<typename TEMP_ROW::Evt,
                     typename TEMP_ROW::Action,typename TEMP_ROW::Guard> type;
};
// explicit + fork + entry point + exit point grammar
struct BuildEntry
    : proto::or_<
        proto::when<
                    proto::function<proto::terminal<proto::_>,proto::terminal<state_tag>,proto::terminal<state_tag> >,
                    get_fct<proto::_child_c<0>,get_state_name<proto::_child_c<1>() >(),get_state_name<proto::_child_c<2>() >() >()
        >
    >
{};

// row grammar
struct BuildNextStates
   : proto::or_<
        proto::when<
                    proto::terminal<state_tag>,
                    get_state_name<proto::_>()
        >,
        proto::when<
                      BuildEntry,
                      BuildEntry
        >,
        proto::when<
                    proto::comma<BuildEntry,BuildEntry >,
                    ::boost::mpl::push_back<
                        make_vector_one_row<BuildEntry(proto::_left)>(),
                        BuildEntry(proto::_right)>()
        >,
        proto::when <
                    proto::comma<BuildNextStates,BuildEntry >,
                    ::boost::mpl::push_back<
                                BuildNextStates(proto::_left),
                                BuildEntry(proto::_right) >()
        >
   >
{};

template <class EventGuard,class ActionClass>
struct fusion_event_action_guard
{
    typedef TempRow<none,typename EventGuard::Evt,none,typename ActionClass::Action,typename EventGuard::Guard> type;
};

template <class SourceGuard,class ActionClass>
struct fusion_source_action_guard
{
    typedef TempRow<typename SourceGuard::Source,none,none,typename ActionClass::Action,typename SourceGuard::Guard> type;
};

template <class SourceClass,class EventClass>
struct fusion_source_event_action_guard
{
    typedef TempRow<typename SourceClass::Source,typename EventClass::Evt,
                    none,typename EventClass::Action,typename EventClass::Guard> type;
};
template <class Left,class Right>
struct fusion_left_right
{
    typedef TempRow<typename Right::Source,typename Right::Evt,typename Left::Target
                   ,typename Right::Action,typename Right::Guard> type;
};

struct BuildEventPlusGuard
    : proto::or_<
        proto::when<
            proto::subscript<proto::terminal<event_tag>, GuardGrammar >,
            TempRow<none,proto::_left,none,none, GuardGrammar(proto::_right)>(proto::_right)
        >
    >
 {};

struct BuildSourceState
   : proto::or_<
        proto::when<
                    proto::terminal<state_tag>,
                    get_state_name<proto::_>()
        >,
        proto::when<
                    BuildEntry,
                    BuildEntry
        >
   >
{};

struct BuildSourcePlusGuard
    : proto::when<
            proto::subscript<BuildSourceState,GuardGrammar >,
            TempRow<BuildSourceState(proto::_left),none,none,none,GuardGrammar(proto::_right)>(proto::_right)
        >
{};

struct BuildEvent
    : proto::or_<
        // just event without guard/action
         proto::when<
                proto::terminal<event_tag>,
                TempRow<none,proto::_,none>() >
        // event / action
       , proto::when<
                proto::divides<proto::terminal<event_tag>,ActionGrammar >,
                TempRow<none,proto::_left,none,ActionGrammar(proto::_right) >(proto::_right) >
        // event [ guard ]
       , proto::when<
                proto::subscript<proto::terminal<event_tag>,GuardGrammar >,
                TempRow<none,proto::_left,none,none,GuardGrammar(proto::_right)>(proto::_right) >
        // event [ guard ] / action
       , proto::when<
                proto::divides<BuildEventPlusGuard, ActionGrammar>,
                fusion_event_action_guard<BuildEventPlusGuard(proto::_left),
                                          TempRow<none,none,none,ActionGrammar(proto::_right)>(proto::_right)
                                           >()
                >
        >
{};
struct BuildSource
    : proto::or_<
        // after == if just state without event or guard/action
         proto::when<
                BuildSourceState,
                TempRow<BuildSourceState(proto::_),none,none>() >
        // == source / action
       , proto::when<
                proto::divides<BuildSourceState,ActionGrammar >,
                TempRow<BuildSourceState(proto::_left),none,none,ActionGrammar(proto::_right) >(proto::_right) >
        // == source [ guard ]
       , proto::when<
                proto::subscript<BuildSourceState,GuardGrammar >,
                TempRow<BuildSourceState(proto::_left),none,none,none,GuardGrammar(proto::_right)>(proto::_right) >
        // == source [ guard ] / action
       , proto::when<
                proto::divides<BuildSourcePlusGuard,
                               ActionGrammar >,
                fusion_source_action_guard<BuildSourcePlusGuard(proto::_left),
                                           TempRow<none,none,none,ActionGrammar(proto::_right)>(proto::_right)
                                           >()
                >
        >
{};

struct BuildRight
    : proto::or_<
         proto::when<
                proto::plus<BuildSource,BuildEvent >,
                fusion_source_event_action_guard<BuildSource(proto::_left),BuildEvent(proto::_right)>()
         >,
         proto::when<
                BuildSource,
                BuildSource
         >
    >
{};

struct BuildRow
    : proto::or_<
        // grammar 1
        proto::when<
            proto::equal_to<BuildNextStates,BuildRight >,
            convert_to_row<
                fusion_left_right<TempRow<none,none,BuildNextStates(proto::_left)>,BuildRight(proto::_right)> >()
        >,
        // internal events
        proto::when<
            BuildRight,
            convert_to_row<
                fusion_left_right<TempRow<none,none,none>,BuildRight(proto::_)> >()
        >,
        // grammar 2
        proto::when<
            proto::equal_to<BuildRight,BuildNextStates>,
            convert_to_row<
                fusion_left_right<TempRow<none,none,BuildNextStates(proto::_right)>,BuildRight(proto::_left)> >()
        >
    >
{};

// stt grammar
struct BuildStt
   : proto::or_<
        proto::when<
                    proto::comma<BuildStt,BuildStt>,
                    boost::mpl::push_back<BuildStt(proto::_left),BuildRow(proto::_right)>()
                >,
        proto::when <
                    BuildRow,
                    make_vector_one_row<BuildRow(proto::_)>()
        >
   >
{};

template <class Expr>
typename ::boost::mpl::eval_if<
    typename proto::matches<Expr,BuildStt>::type,
    boost::result_of<BuildStt(Expr)>,
    make_invalid_type>::type
build_stt(Expr const&)
{
    return typename boost::result_of<BuildStt(Expr)>::type();
}

// internal stt grammar
struct BuildInternalRow
    :   proto::when<
            BuildEvent,
            convert_to_internal_row<
                fusion_left_right<TempRow<none,none,none>,BuildEvent(proto::_)> >()
        >
{};
struct BuildInternalStt
   : proto::or_<
        proto::when<
                    proto::comma<BuildInternalStt,BuildInternalStt>,
                    boost::mpl::push_back<BuildInternalStt(proto::_left),BuildInternalRow(proto::_right)>()
                >,
        proto::when <
                    BuildInternalRow,
                    make_vector_one_row<BuildInternalRow(proto::_)>()
        >
   >
{};

template <class Expr>
typename ::boost::mpl::eval_if<
    typename proto::matches<Expr,BuildInternalStt>::type,
    boost::result_of<BuildInternalStt(Expr)>,
    make_invalid_type>::type
build_internal_stt(Expr const&)
{
    return typename boost::result_of<BuildInternalStt(Expr)>::type();
}

}}}}
#endif //BOOST_MSM_FRONT_EUML_STT_GRAMMAR_H


text:
/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2020 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Core/Algorithms/Legacy/FiniteElements/Mapping/BuildNodeLink.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/DenseColumnMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Datatypes/SparseRowMatrixFromMap.h>
#include <Core/Datatypes/MatrixTypeConversions.h>

#include <Core/Math/MiscMath.h>
#include <boost/scoped_array.hpp>

using namespace SCIRun;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Thread;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::FiniteElements;
using namespace SCIRun::Core::Logging;

bool
BuildNodeLinkAlgo::run(MatrixHandle nodeDomain, MatrixHandle& nodeLink) const
{
  ScopedAlgorithmStatusReporter asr(this, "BuildNodeLink");

  if (!nodeDomain)
  {
    error("No matrix on input");
    return (false);
  }

  if (nodeDomain->ncols() != 1)
  {
    error("NodeDomain needs to be a column vector");
    return (false);
  }

  DenseColumnMatrixHandle nodeDomainCol = convertMatrix::toColumn(nodeDomain);

  size_type num_values = nodeDomainCol->nrows();

  double min2 = -std::numeric_limits<double>::max();
  double min = std::numeric_limits<double>::max();

  bool found_domain = false;

  LegacySparseDataContainer<double> sparseData(num_values+1, num_values, 0);
  auto rr = sparseData.rows();
  auto cc = sparseData.columns();
  size_type nnz = 0;

  if (!rr || !cc)
  {
    error("Could not allocate memory for sparse matrix");
    return (false);
  }

  for (index_type j = 0; j<num_values; j++) cc[j] = -1;

  do
  {
    found_domain = false;
    min = std::numeric_limits<double>::max();

    for (index_type j = 0; j<num_values; j++)
    {
      double val = (*nodeDomainCol)(j);
      if (IsFinite(val))
      {
        if (val < min && val > min2 )
        {
          found_domain = true;
          min = val;
        }
      }
    }

    if (found_domain)
    {
      min2 = min;
      index_type idx = -1;
      for (index_type j = 0; j<num_values; j++)
      {
        double val = (*nodeDomainCol)(j);
        if (val == min2)
        {
          if (idx < 0) idx = j;
          else { cc[j] = idx; nnz++; }
        }
      }
    }
  }
  while (found_domain);

  sparseData.allocateData(nnz);
  auto aa = sparseData.data();

  if (!aa)
  {
    error("Could not allocate memory for sparse matrix");
    return (false);
  }

  index_type k = 0;
  rr[0] = 0;
  for (index_type j = 0; j<num_values; j++)
  {
    if (cc[j] > -1 )
    {
      cc[k] = cc[j];
      aa[k] = 1.0;
      k++;
    }
    rr[j+1] = k;
  }

  SparseRowMatrix nodeLinkHalf(num_values, num_values, rr.get(), cc.get(), aa.get(), nnz);
  SparseRowMatrix nodeLinkHalfT(nodeLinkHalf.transpose());
  nodeLink.reset(new SparseRowMatrix(nodeLinkHalf + nodeLinkHalfT));
  return (true);
}

AlgorithmOutput BuildNodeLinkAlgo::run(const AlgorithmInput &) const
{
  throw "not implemented";
}

max_stars_repo_name: Haydelj/SCIRun

max_issues_repo_name: Haydelj/SCIRun

max_forks_repo_name: Haydelj/SCIRun


text:
/*
Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/

// Without this flag, GTSAM Expressions currently fail within fbcode.
// We need EIGEN_MAKE_ALIGNED_OPERATOR_NEW in GTSAM to really fix this
#define EIGEN_DONT_ALIGN_STATICALLY

#include <boost/filesystem.hpp>

#include "Mesh.h"

#include <iostream>
#include <math.h>

namespace sumo {

using namespace std;

Mesh::Mesh(
    const vector<Index>& indices,
    const vector<Vertex>& vertices,
    const vector<Normal>& normals)
    : indices_(indices), vertices_(vertices), normals_(normals) {
  assert(vertices.size() == normals.size());
}

vector<Mesh::Normal> Mesh::CalculateFaceNormals(
    const vector<Index>& indices,
    const vector<Vertex>& vertices) {
  vector<Normal> faceNormals;
  const size_t numTriangles = indices.size() / 3;
  faceNormals.reserve(numTriangles);
  // Compute face normals using cross product method.
  for (size_t i = 0; i < numTriangles; i++) {
    // get three triangle vertex indices
    const size_t j = i * 3;
    const Index i0 = indices[j], i1 = indices[j + 1], i2 = indices[j + 2];
    Vertex a = vertices[i1] - vertices[i0];
    Vertex b = vertices[i2] - vertices[i0];

    Normal n = a.cross(b).normalized();
    faceNormals.push_back(n);
  }
  return faceNormals;
}

vector<Mesh::Normal> Mesh::EstimateNormals(
    const vector<Index>& indices,
    const vector<Vertex>& vertices) {
  vector<Normal> faceNormals = CalculateFaceNormals(indices, vertices);

  // Initialize normals to zero.
  size_t numVertices = vertices.size();
  vector<Mesh::Normal> normals(numVertices, Normal::Zero());

  // Add face normals to all involved vertices.
  // TODO use iterator
  size_t j = 0;
  for (const auto& n : faceNormals) {
    for (Index i : {indices[j], indices[j + 1], indices[j + 2]}) {
      assert(i < numVertices);
      normals[i] += n;
    }
    j += 3;
  }

  for (auto& n : normals) {
    n.normalize();
  }

  return normals;
}

void Mesh::cleanupLongEdges(float threshold) {
  vector<Index> new_indices;
  new_indices.reserve(numIndices());
  // define distance function
  const auto dist = [](Vertex x, Vertex y) { return (x - y).norm(); };
  // loop over all triangles in this mesh
  for (const auto& triangle : *this) {
    // check all edges
    if (dist(triangle.a, triangle.b) <= threshold &&
        dist(triangle.b, triangle.c) <= threshold &&
        dist(triangle.c, triangle.a) <= threshold) {
      // add triangle since valid
      new_indices.push_back(triangle.i);
      new_indices.push_back(triangle.j);
      new_indices.push_back(triangle.k);
    }
  }
  indices_ = new_indices;
}

void Mesh::cleanupEdgesToOrigin(const double precision) {
  vector<Index> new_indices;
  new_indices.reserve(numIndices());
  // loop over all triangles in this mesh
  for (const auto& triangle : *this) {
    // If any vertex is zero, we bail.
    if (triangle.a.isZero(precision) || triangle.b.isZero(precision) ||
        triangle.c.isZero(precision)) {
      continue;
    }
    // add triangle since valid
    new_indices.push_back(triangle.i);
    new_indices.push_back(triangle.j);
    new_indices.push_back(triangle.k);
  }
  indices_ = new_indices;
}

Mesh Mesh::Example(
    const double length /* = 2.0*/,
    const bool inward /* = true */) {
  vector<Index> indices;
  indices.insert(indices.end(), {1, 0, 2}); // Left face   (x = -1.0f)
  indices.insert(indices.end(), {2, 3, 1}); // Left face   (x = -1.0f)
  indices.insert(indices.end(), {4, 0, 1}); // Bottom face (y = -1.0f)
  indices.insert(indices.end(), {1, 5, 4}); // Bottom face (y = -1.0f)
  indices.insert(indices.end(), {2, 0, 4}); // Back face   (z = -1.0f)
  indices.insert(indices.end(), {4, 6, 2}); // Back face   (z = -1.0f)
  indices.insert(indices.end(), {5, 7, 6}); // Right face  (x = +1.0f)
  indices.insert(indices.end(), {6, 4, 5}); // Right face  (x = +1.0f)
  indices.insert(indices.end(), {6, 7, 3}); // Top face    (y = +1.0f)
  indices.insert(indices.end(), {3, 2, 6}); // Top face    (y = +1.0f)
  indices.insert(indices.end(), {3, 7, 5}); // Front face  (z = +1.0f)
  indices.insert(indices.end(), {5, 1, 3}); // Front face  (z = +1.0f)
  if (inward == false) {
    reverse(indices.begin(), indices.end());
  }

  vector<Vertex> vertices;
  const double radius = length / 2;
  vertices.push_back(Vertex(-1.0f, -1.0f, -1.0f) * radius); // 0th
  vertices.push_back(Vertex(-1.0f, -1.0f, +1.0f) * radius); // 1st
  vertices.push_back(Vertex(-1.0f, +1.0f, -1.0f) * radius); // 2nd
  vertices.push_back(Vertex(-1.0f, +1.0f, +1.0f) * radius); // 3rd
  vertices.push_back(Vertex(+1.0f, -1.0f, -1.0f) * radius); // 4th
  vertices.push_back(Vertex(+1.0f, -1.0f, +1.0f) * radius); // 5th
  vertices.push_back(Vertex(+1.0f, +1.0f, -1.0f) * radius); // 6th
  vertices.push_back(Vertex(+1.0f, +1.0f, +1.0f) * radius); // 7th

  return Mesh(indices, vertices, Mesh::EstimateNormals(indices, vertices));
}

void Mesh::merge(const Mesh& mesh2, size_t numCommonVertices) {
  // Merge the indices.
  const size_t offset = numVertices() - numCommonVertices;
  for (const size_t& index2 : mesh2.indices()) {
    indices_.push_back(index2 < numCommonVertices ? index2 : index2 + offset);
  }

  // Treat the case when mesh2 defines new vertices.
  if (mesh2.numVertices() > numCommonVertices) {
    const auto append = [numCommonVertices](auto& a, const auto& b) {
      a.insert(a.end(), b.begin() + numCommonVertices, b.end());
    };
    append(vertices_, mesh2.vertices());
    append(normals_, mesh2.normals());
  }
}

void Mesh::replaceGeometry(const Mesh& mesh2) {
  //Replace the geometry of the mesh.
  indices_.clear();
  vertices_.clear();
  normals_.clear();

  merge(mesh2, 0);

}

  /// Operator == for Parameter
  // ::: TODO: This function is not correct.  It does not check all aspects
  // of the parameter struct.  Furthermore, some aspects of the Parameter
  // struct are unstable (that is, they are not initialized to known values,
  // so comparing two Parameter objects is not really feasible with the
  // tiny_gltf design.
static bool parametersEqual(
    const tinygltf::Parameter& a,
    const tinygltf::Parameter& b) {
  return
    a.has_number_value == b.has_number_value &&
    a.string_value == b.string_value &&
    a.json_double_value == b.json_double_value;
}

/// Operator == for Parameter
static bool namedParametersEqual(
    const tinygltf::ParameterMap::value_type& a,
    const tinygltf::ParameterMap::value_type& b) {
  return a.first == b.first && parametersEqual(a.second, b.second);
}

/// Operator == for ParameterMap
bool operator==(
    const tinygltf::ParameterMap& a,
    const tinygltf::ParameterMap& b) {
  return a.size() == b.size() &&
      std::equal(a.begin(), a.end(), b.begin(), namedParametersEqual);
}

/// Operator == for Material
// Only comparing ParameterMaps and name.
// TODO: Compare extensions and extras.
bool operator==(const tinygltf::Material& a, const tinygltf::Material& b) {
  return a.additionalValues == b.additionalValues && a.values == b.values &&
      a.name == b.name;
}

bool Mesh::hasSameMaterial(const Mesh& other) const {
  return material_ == other.material_;
}

} // namespace sumo

max_stars_repo_name: pmoulon/sumo-challenge

max_issues_repo_name: pmoulon/sumo-challenge

max_forks_repo_name: pmoulon/sumo-challenge


text:
#ifndef BOOST_MP11_MAP_HPP_INCLUDED
#define BOOST_MP11_MAP_HPP_INCLUDED

//  Copyright 2015-2017 Peter Dimov.
//
//  Distributed under the Boost Software License, Version 1.0.
//
//  See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt

#include <boost/mp11/detail/mp_map_find.hpp>
#include <boost/mp11/list.hpp>
#include <boost/mp11/integral.hpp>
#include <boost/mp11/utility.hpp>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/function.hpp>
#include <boost/mp11/set.hpp>
#include <type_traits>

namespace boost
{
namespace mp11
{

// mp_map_contains<M, K>
template<class M, class K> using mp_map_contains = mp_not<std::is_same<mp_map_find<M, K>, void>>;

// mp_map_insert<M, T>
template<class M, class T> using mp_map_insert = mp_if< mp_map_contains<M, mp_first<T>>, M, mp_push_back<M, T> >;

// mp_map_replace<M, T>
namespace detail
{

template<class M, class T> struct mp_map_replace_impl;

template<template<class...> class M, class... U, class T> struct mp_map_replace_impl<M<U...>, T>
{
    using K = mp_first<T>;

    // mp_replace_if is inlined here using a struct _f because of msvc-14.0

    template<class V> struct _f { using type = mp_if< std::is_same<mp_first<V>, K>, T, V >; };

    using type = mp_if< mp_map_contains<M<U...>, K>, M<typename _f<U>::type...>, M<U..., T> >;
};

} // namespace detail

template<class M, class T> using mp_map_replace = typename detail::mp_map_replace_impl<M, T>::type;

// mp_map_update<M, T, F>
namespace detail
{

template<class M, class T, template<class...> class F> struct mp_map_update_impl
{
    template<class U> using _f = std::is_same<mp_first<T>, mp_first<U>>;

    // _f3<L<X, Y...>> -> L<X, F<X, Y...>>
    template<class L> using _f3 = mp_assign<L, mp_list<mp_first<L>, mp_rename<L, F>>>;

    using type = mp_if< mp_map_contains<M, mp_first<T>>, mp_transform_if<_f, _f3, M>, mp_push_back<M, T> >;
};

} // namespace detail

template<class M, class T, template<class...> class F> using mp_map_update = typename detail::mp_map_update_impl<M, T, F>::type;
template<class M, class T, class Q> using mp_map_update_q = mp_map_update<M, T, Q::template fn>;

// mp_map_erase<M, K>
namespace detail
{

template<class M, class K> struct mp_map_erase_impl
{
    template<class T> using _f = std::is_same<mp_first<T>, K>;
    using type = mp_remove_if<M, _f>;
};

} // namespace detail

template<class M, class K> using mp_map_erase = typename detail::mp_map_erase_impl<M, K>::type;

// mp_map_keys<M>
template<class M> using mp_map_keys = mp_transform<mp_first, M>;

// mp_is_map<M>
namespace detail
{

template<class L> struct mp_is_map_element: mp_false
{
};

template<template<class...> class L, class T1, class... T> struct mp_is_map_element<L<T1, T...>>: mp_true
{
};

template<class M> using mp_keys_are_set = mp_is_set<mp_map_keys<M>>;

template<class M> struct mp_is_map_impl
{
    using type = mp_false;
};

template<template<class...> class M, class... T> struct mp_is_map_impl<M<T...>>
{
    using type = mp_eval_if<mp_not<mp_all<mp_is_map_element<T>...>>, mp_false, mp_keys_are_set, M<T...>>;
};

} // namespace detail

template<class M> using mp_is_map = typename detail::mp_is_map_impl<M>::type;

} // namespace mp11
} // namespace boost

#endif // #ifndef BOOST_MP11_MAP_HPP_INCLUDED


text:
// Copyright (c) 2016 The UUV Simulator 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.

/// \file UnderwaterObjectROSPlugin.hh Publishes the underwater object's
/// Gazebo topics and parameters into ROS standards

#ifndef __UNDERWATER_OBJECT_ROS_PLUGIN_HH__
#define __UNDERWATER_OBJECT_ROS_PLUGIN_HH__

#include <string>

#include <uuv_gazebo_plugins/UnderwaterObjectPlugin.hh>

#include <boost/scoped_ptr.hpp>
#include <gazebo/gazebo.hh>
#include <gazebo/common/Plugin.hh>
#include <ros/ros.h>
#include <geometry_msgs/WrenchStamped.h>

#include <map>

namespace uuv_simulator_ros
{
  class UnderwaterObjectROSPlugin : public gazebo::UnderwaterObjectPlugin
  {
    /// \brief Constructor
    public: UnderwaterObjectROSPlugin();

    /// \brief Destructor
    public: virtual ~UnderwaterObjectROSPlugin();

    /// \brief Load module and read parameters from SDF.
    public: void Load(gazebo::physics::ModelPtr _parent, sdf::ElementPtr _sdf);

    /// \brief Initialize Module.
    public: virtual void Init();

    /// \brief Reset Module.
    public: virtual void Reset();

    /// \brief Publish restoring force
    /// \param[in] _link Pointer to the link where the force information will
    /// be extracted from
    protected: virtual void PublishRestoringForce(
      gazebo::physics::LinkPtr _link);

    /// \brief Publish hydrodynamic wrenches
    /// \param[in] _link Pointer to the link where the force information will
    /// be extracted from
    protected: virtual void PublishHydrodynamicWrenches(
      gazebo::physics::LinkPtr _link);

    /// \brief Returns the wrench message for debugging topics
    /// \param[in] _force Force vector
    /// \param[in] _torque Torque vector
    /// \param[in] _output Stamped wrench message to be updated
    protected: virtual void GenWrenchMsg(
      gazebo::math::Vector3 _force, gazebo::math::Vector3 _torque,
      geometry_msgs::WrenchStamped &_output);

    /// \brief Sets the topics used for publishing the intermediate data during
    /// the simulation
    /// \param[in] _link Pointer to the link
    /// \param[in] _hydro Pointer to the hydrodynamic model
    protected: virtual void InitDebug(gazebo::physics::LinkPtr _link,
      gazebo::HydrodynamicModelPtr _hydro);

    /// \brief Pointer to this ROS node's handle.
    private: boost::scoped_ptr<ros::NodeHandle> rosNode;

    /// \brief Subscriber reacting to new reference thrust set points.
    private: ros::Subscriber subThrustReference;

    /// \brief Publisher for current actual thrust.
    private: std::map<std::string, ros::Publisher> rosHydroPub;
  };
}

#endif  // __UNDERWATER_OBJECT_ROS_PLUGIN_HH__

ext: hh


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

#include <boost/bind.hpp>
#include <gtest/gtest.h>

#include "kudu/util/countdown_latch.h"
#include "kudu/util/test_util.h"
#include "kudu/util/thread.h"
#include "kudu/util/threadpool.h"

namespace kudu {

static void DecrementLatch(CountDownLatch* latch, int amount) {
  if (amount == 1) {
    latch->CountDown();
    return;
  }
  latch->CountDown(amount);
}

// Tests that we can decrement the latch by arbitrary amounts, as well
// as 1 by one.
TEST(TestCountDownLatch, TestLatch) {

  gscoped_ptr<ThreadPool> pool;
  ASSERT_OK(ThreadPoolBuilder("cdl-test").set_max_threads(1).Build(&pool));

  CountDownLatch latch(1000);

  // Decrement the count by 1 in another thread, this should not fire the
  // latch.
  ASSERT_OK(pool->SubmitFunc(boost::bind(DecrementLatch, &latch, 1)));
  ASSERT_FALSE(latch.WaitFor(MonoDelta::FromMilliseconds(200)));
  ASSERT_EQ(999, latch.count());

  // Now decrement by 1000 this should decrement to 0 and fire the latch
  // (even though 1000 is one more than the current count).
  ASSERT_OK(pool->SubmitFunc(boost::bind(DecrementLatch, &latch, 1000)));
  latch.Wait();
  ASSERT_EQ(0, latch.count());
}

// Test that resetting to zero while there are waiters lets the waiters
// continue.
TEST(TestCountDownLatch, TestResetToZero) {
  CountDownLatch cdl(100);
  scoped_refptr<Thread> t;
  ASSERT_OK(Thread::Create("test", "cdl-test", &CountDownLatch::Wait, &cdl, &t));

  // Sleep for a bit until it's likely the other thread is waiting on the latch.
  SleepFor(MonoDelta::FromMilliseconds(10));
  cdl.Reset(0);
  t->Join();
}

} // namespace kudu

max_stars_repo_name: kv-zuiwanyuan/kudu

max_issues_repo_name: kv-zuiwanyuan/kudu

max_forks_repo_name: kv-zuiwanyuan/kudu


text:
/**
 * \file dcs/testbed/conf/commons.hpp
 *
 * \brief Common definitions
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 * <hr/>
 *
 * Copyright 2014 Marco Guazzone (marco.guazzone@gmail.com)
 *
 * 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.
 */

#ifndef DCS_TESTBED_CONF_COMMONS_HPP
#define DCS_TESTBED_CONF_COMMONS_HPP

#include <boost/algorithm/string.hpp>
#include <boost/smart_ptr.hpp>
#include <dcs/exception.hpp>
#include <dcs/math/traits/float.hpp>
#include <dcs/testbed/application_performance_category.hpp>
#include <dcs/testbed/virtual_machine_performance_category.hpp>
#include <dcs/testbed/workload_category.hpp>
#include <dcs/testbed/workload_generator_category.hpp>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>

namespace dcs { namespace testbed { namespace conf {

enum app_manager_category
{
	albano2013_fuzzyqe_app_manager,
	anglano2014_fc2q_app_manager,
	anglano2014_fc2q_mimo_app_manager,
	dummy_app_manager,
	padala2009_autocontrol_app_manager,
	rao2013_dynaqos_app_manager,
	sysid_app_manager
};

template <typename CharT, typename CharTraitsT>
std::basic_istream<CharT,CharTraitsT>& operator>>(std::basic_istream<CharT,CharTraitsT>& is, app_manager_category& cat)
{
	std::string s;
	is >> s;
	boost::to_lower(s);

	if (!s.compare("albano2013-fuzzyqe") || !s.compare("albano2013"))
	{
		cat = albano2013_fuzzyqe_app_manager;
	}
	else if (!s.compare("anglano2014-fc2q-miso") || !s.compare("anglano2014-fc2q"))
	{
		cat = anglano2014_fc2q_app_manager;
	}
	else if (!s.compare("anglano2014-fc2q-mimo"))
	{
		cat = anglano2014_fc2q_mimo_app_manager;
	}
	else if (!s.compare("dummy"))
	{
		cat = dummy_app_manager;
	}
	else if (!s.compare("padala2009-autocontrol"))
	{
		cat = padala2009_autocontrol_app_manager;
	}
	else if (!s.compare("rao2013-dynaqos"))
	{
		cat = rao2013_dynaqos_app_manager;
	}
	else if (!s.compare("sysid"))
	{
		cat = sysid_app_manager;
	}
	else
	{
		DCS_EXCEPTION_THROW(std::runtime_error, "Unknown application manager category");
	}

	return is;
}

template <typename CharT, typename CharTraitsT>
std::basic_ostream<CharT,CharTraitsT>& operator<<(std::basic_ostream<CharT,CharTraitsT>& os, app_manager_category cat)
{
	switch (cat)
	{
		case albano2013_fuzzyqe_app_manager:
			os << "albano2013-fuzzyqe";
			break;
		case anglano2014_fc2q_app_manager:
			os << "anglano2014-fc2q";
			break;
		case anglano2014_fc2q_mimo_app_manager:
			os << "anglano2014-fc2q-mimo";
			break;
		case dummy_app_manager:
			os << "dummy";
			break;
		case padala2009_autocontrol_app_manager:
			os << "padal2009-autocontrol";
			break;
		case rao2013_dynaqos_app_manager:
			os << "rao2013-dynaqos";
			break;
		case sysid_app_manager:
			os << "sysid";
			break;
		default:
			DCS_EXCEPTION_THROW(::std::runtime_error, "Unknown application manager category");
	}

	return os;
}

enum data_estimator_category
{
	mean_estimator,
	chen2000_ewma_quantile_estimator,
	chen2000_ewsa_quantile_estimator,
	chen2000_sa_quantile_estimator,
	jain1985_p2_algorithm_quantile_estimator,
	most_recently_observed_estimator,
	true_quantile_estimator,
	welsh2003_ewma_quantile_estimator/*,
	welsh2003_ewma_ext_quantile_estimator*/
};

template <typename CharT, typename CharTraitsT>
std::basic_istream<CharT,CharTraitsT>& operator>>(std::basic_istream<CharT,CharTraitsT>& is, data_estimator_category& cat)
{
	std::string s;
	is >> s;
	boost::to_lower(s);

	if (!s.compare("mean"))
	{
		cat = mean_estimator;
	}
	else if (!s.compare("mro"))
	{
		cat = most_recently_observed_estimator;
	}
	else if (!s.compare("chen2000-ewma-quantile"))
	{
		cat = chen2000_ewma_quantile_estimator;
	}
	else if (!s.compare("chen2000-ewsa-quantile"))
	{
		cat = chen2000_ewsa_quantile_estimator;
	}
	else if (!s.compare("chen2000-sa-quantile"))
	{
		cat = chen2000_sa_quantile_estimator;
	}
	else if (!s.compare("jain1985-p2_algorithm-quantile"))
	{
		cat = jain1985_p2_algorithm_quantile_estimator;
	}
	else if (!s.compare("welsh2003-ewma-quantile"))
	{
		cat = welsh2003_ewma_quantile_estimator;
	}
//	else if (!s.compare("welsh2003-ewma-ext-quantile"))
//	{
//		cat = welsh2003_ewma_ext_quantile_estimator;
//	}
	else
	{
		DCS_EXCEPTION_THROW(std::runtime_error, "Unknown data estimator category");
	}

	return is;
}

template <typename CharT, typename CharTraitsT>
std::basic_ostream<CharT,CharTraitsT>& operator<<(std::basic_ostream<CharT,CharTraitsT>& os, data_estimator_category cat)
{
	switch (cat)
	{
		case mean_estimator:
			os << "mean";
			break;
		case most_recently_observed_estimator:
			os << "mro";
			break;
		case chen2000_ewma_quantile_estimator:
			os << "chen2000-ewma-quantile";
			break;
		case chen2000_ewsa_quantile_estimator:
			os << "chen2000-ewsa-quantile";
			break;
		case chen2000_sa_quantile_estimator:
			os << "chen2000-sa-quantile";
			break;
		case jain1985_p2_algorithm_quantile_estimator:
			os << "jain1985-p2-algorithm-quantile";
			break;
		case welsh2003_ewma_quantile_estimator:
			os << "welsh2003-ewma-quantile";
			break;
//		case welsh2003_ewma_ext_quantile_estimator:
//			os << "welsh2003-ewma-ext-quantile";
//			break;
		default:
			DCS_EXCEPTION_THROW(::std::runtime_error, "Unknown data estimator category");
	}

	return os;
}

enum data_smoother_category
{
    dummy_smoother,
    brown_single_exponential_smoother,
    brown_double_exponential_smoother,
    holt_winters_double_exponential_smoother
};

template <typename CharT, typename CharTraitsT>
std::basic_istream<CharT,CharTraitsT>& operator>>(std::basic_istream<CharT,CharTraitsT>& is, data_smoother_category& cat)
{
	std::string s;
	is >> s;
	boost::to_lower(s);

	if (!s.compare("brown_ses"))
	{
		cat = brown_single_exponential_smoother;
	}
	else if (!s.compare("dummy"))
	{
		cat = dummy_smoother;
	}
	else if (!s.compare("brown_des"))
	{
		cat = brown_double_exponential_smoother;
	}
	else if (!s.compare("holt_winters_des"))
	{
		cat = holt_winters_double_exponential_smoother;
	}
	else
	{
		DCS_EXCEPTION_THROW(std::runtime_error, "Unknown data smoother category");
	}

	return is;
}

template <typename CharT, typename CharTraitsT>
std::basic_ostream<CharT,CharTraitsT>& operator<<(std::basic_ostream<CharT,CharTraitsT>& os, data_smoother_category cat)
{
	switch (cat)
	{
		case brown_single_exponential_smoother:
			os << "brown_ses";
			break;
		case brown_double_exponential_smoother:
			os << "brown_des";
			break;
		case dummy_smoother:
			os << "dummy";
			break;
		case holt_winters_double_exponential_smoother:
			os << "holt_winters_des";
			break;
		default:
			DCS_EXCEPTION_THROW(std::runtime_error, "Unknown data smoother category");
	}

	return os;
}

enum signal_category
{
    constant_signal,
    half_sinusoidal_mesh_signal,
    half_sinusoidal_signal,
    gaussian_signal,
    sawtooth_signal,
    sinusoidal_mesh_signal,
    sinusoidal_signal,
    square_signal,
    uniform_signal
};

template <typename CharT, typename CharTraitsT>
std::basic_istream<CharT,CharTraitsT>& operator>>(std::basic_istream<CharT,CharTraitsT>& is, signal_category& cat)
{
	std::string s;
	is >> s;
	boost::to_lower(s);

	if (!s.compare("constant"))
	{
		cat = constant_signal;
	}
	else if (!s.compare("half-sine"))
	{
		cat = half_sinusoidal_signal;
	}
	else if (!s.compare("half-sine-mesh"))
	{
		cat = half_sinusoidal_mesh_signal;
	}
	else if (!s.compare("gaussian"))
	{
		cat = gaussian_signal;
	}
	else if (!s.compare("sawtooth"))
	{
		cat = sawtooth_signal;
	}
	else if (!s.compare("sine"))
	{
		cat = sinusoidal_signal;
	}
	else if (!s.compare("sine-mesh"))
	{
		cat = sinusoidal_mesh_signal;
	}
	else if (!s.compare("square"))
	{
		cat = square_signal;
	}
	else if (!s.compare("uniform"))
	{
		cat = uniform_signal;
	}
	else
	{
		DCS_EXCEPTION_THROW(std::runtime_error, "Cannot find a valid signal category");
	}

	return is;
}

template <typename CharT, typename CharTraitsT>
std::basic_ostream<CharT,CharTraitsT>& operator<<(std::basic_ostream<CharT,CharTraitsT>& os, signal_category sig)
{
	switch (sig)
	{
		case constant_signal:
			os << "constant";
			break;
		case half_sinusoidal_signal:
			os << "half-sine";
			break;
		case half_sinusoidal_mesh_signal:
			os << "half-sine-mesh";
			break;
		case gaussian_signal:
			os << "gaussian";
			break;
		case sawtooth_signal:
			os << "sawtooth";
			break;
		case sinusoidal_signal:
			os << "sine";
			break;
		case sinusoidal_mesh_signal:
			os << "sine-mesh";
			break;
		case square_signal:
			os << "square";
			break;
		case uniform_signal:
			os << "uniform";
			break;
		default:
			DCS_EXCEPTION_THROW(std::runtime_error, "Cannot find a valid signal category");
	}

	return os;
}

namespace defaults
{
	const bool app_experiment_restore_vms = true;
	const app_manager_category app_manager = dummy_app_manager;
	const std::string app_manager_report_file_path("./appmgr-out.dat");
	const double app_manager_albano2013_fuzzyqe_beta = 0.9;
	const double app_manager_anglano2014_fc2q_beta = 0.9;
	const std::size_t app_manager_padala2009_autocontrol_na = 2;
	const std::size_t app_manager_padala2009_autocontrol_nb = 2;
	const std::size_t app_manager_padala2009_autocontrol_nk = 1;
	const std::size_t app_manager_padala2009_autocontrol_ny = 1;
	const std::size_t app_manager_padala2009_autocontrol_nu = 1;
	const double app_manager_padala2009_autocontrol_ff = 0.98;
	const double app_manager_padala2009_autocontrol_q = 2;
	const double app_manager_rao2013_dynaqos_gamma = 0.8;
	const bool app_manager_sysid_report_extended = false;
	const double sampling_time = 10;
	const double control_time = 3*sampling_time;
	const double exciting_time = 3*sampling_time;
	const unsigned long rng_seed = 5489UL;
	const data_estimator_category data_estimator = mean_estimator;
	const double data_estimator_quantile_probability = 0.99;
	//const double data_estimator_jain1985_p2_quantile_probability = data_estimator_quantile_probability;
	const double data_estimator_chen2000_ewma_w = 0.05;
	//const double data_estimator_chen2000_ewma_quantile_probability = data_estimator_quantile_probability;
	const double data_estimator_chen2000_ewsa_w = 0.05;
	//const double data_estimator_chen2000_ewsa_quantile_probability = data_estimator_quantile_probability;
	//const double data_estimator_chen2000_sa_quantile_probability = data_estimator_quantile_probability;
	const double data_estimator_welsh2003_ewma_alpha = 0.7;
	//const double data_estimator_welsh2003_ewma_quantile_probability = data_estimator_quantile_probability;
	const bool data_estimator_welsh2003_ewma_extended = false;
	const data_smoother_category data_smoother = dummy_smoother;
	const double data_smoother_brown_single_exponential_alpha = 0.7;
	const double data_smoother_brown_double_exponential_alpha = 0.7;
	const double data_smoother_holt_winters_double_exponential_alpha = 0.8;
	const double data_smoother_holt_winters_double_exponential_beta = 0.3;
	const double data_smoother_holt_winters_double_exponential_delta = 0.7;
	const signal_category signal = constant_signal;
	const double signal_upper_bound = std::numeric_limits<double>::infinity();
	const double signal_lower_bound = -std::numeric_limits<double>::infinity();
	const double signal_constant_value = 1;
	const double signal_sawtooth_low = 0;
	const double signal_sawtooth_high = 1;
	const double signal_sawtooth_increment = 0.1;
	const double signal_sine_amplitude = 0.5;
	const unsigned int signal_sine_frequency = 8;
	const unsigned int signal_sine_phase = 0;
	const double signal_sine_bias = 0.5;
	const double signal_sine_mesh_amplitude = 0.5;
	const unsigned int signal_sine_mesh_frequency = 8;
	const unsigned int signal_sine_mesh_phase = 0;
	const double signal_sine_mesh_bias = 0.5;
	const double signal_half_sine_amplitude = 0.5;
	const unsigned int signal_half_sine_frequency = 8;
	const unsigned int signal_half_sine_phase = 0;
	const double signal_half_sine_bias = 0.5;
	const double signal_half_sine_mesh_amplitude = 0.5;
	const unsigned int signal_half_sine_mesh_frequency = 8;
	const unsigned int signal_half_sine_mesh_phase = 0;
	const double signal_half_sine_mesh_bias = 0.5;
	const double signal_square_low = 0;
	const double signal_square_high = 1;
	const double signal_uniform_min = 0;
	const double signal_uniform_max = 1;
	const double signal_gaussian_mean = 0;
	const double signal_gaussian_sd = 1;
	const dcs::testbed::application_performance_category slo_metric = dcs::testbed::response_time_application_performance;
	const double slo_value = std::numeric_limits<double>::quiet_NaN();
	const dcs::testbed::virtual_machine_performance_category vm_performance = dcs::testbed::cpu_util_virtual_machine_performance;
	const dcs::testbed::workload_category workload = dcs::testbed::olio_workload;
	const dcs::testbed::workload_generator_category workload_generator = dcs::testbed::rain_workload_generator;
	const std::string workload_generator_rain_path("/usr/local/opt/rain-workload-toolkit");
	const std::string workload_generator_ycsb_path("/usr/local/opt/YCSB");
	const std::vector<std::string> workload_generator_ycsb_property_files(1, "/usr/local/opt/YCSB/workloads/workloada");
	const std::string workload_generator_ycsb_classpath;
	const std::string workload_generator_ycsb_db_class("basic");
} // Namespace defaults

namespace detail {

template <typename RealT>
struct response_time_slo_checker
{
	response_time_slo_checker(RealT max_val, RealT rel_tol=0.05)
	: max_val_(max_val),
	  check_val_(max_val_*(1+rel_tol))
	{
	}

	bool operator()(RealT val)
	{
		return ::dcs::math::float_traits<RealT>::approximately_less_equal(val, check_val_);
	}

	private: RealT max_val_;
	private: RealT check_val_;
};

template <typename RealT>
struct throughput_slo_checker
{
	throughput_slo_checker(RealT min_val, RealT rel_tol=0.05)
	: min_val_(min_val),
	  check_val_(min_val_*(1+rel_tol))
	{
	}

	bool operator()(RealT val)
	{
		return ::dcs::math::float_traits<RealT>::approximately_greater_equal(val, check_val_);
	}

	private: RealT min_val_;
	private: RealT check_val_;
};

} // Namespace detail

}}} // Namespace dcs::testbed::conf

#endif // DCS_TESTBED_CONF_COMMONS_HPP

max_stars_repo_name: sguazt/dcsxx-testbed

max_issues_repo_name: sguazt/dcsxx-testbed

max_forks_repo_name: sguazt/dcsxx-testbed