text:
/*
 *  universe.hpp
 *  ames-ms/raparm-ms/rm-ms Object classes (with base methods)
 *
 *  Created by David Brawand on 30.03.10.
 *  Copyright 2010 Université de Lausanne. All rights reserved.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <utility>
#include <map>
#include <math.h>
#include <assert.h>
#include <boost/graph/adjacency_list.hpp>
#include <boost/pending/disjoint_sets.hpp>
#include <boost/graph/incremental_components.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/connected_components.hpp>

using namespace std;

/* ------------------------------------------------------------- */
/* DEFINITIONS                                                   */
/* ------------------------------------------------------------- */
#define MAXTAG 3;
#define MAXREADLENGTH 150;
#define MAXREGIONEXONS 1000000;
#define MAXGENEEXONS 1000;
#define	ISLANDIST 0;            // max distance between reads to be merged into an island
/* ------------------------------------------------------------- */
/* Class declarations                                            */
/* ------------------------------------------------------------- */
class Exon;
class Gene;
class Assignment;
class Region;
class Read;
class Mapping;
class Splice;
class Island;
/* ------------------------------------------------------------- */
/* Type declarations                                             */
/* ------------------------------------------------------------- */
typedef map<int, int> intmap;
typedef map<int, double> intdoublemap;
typedef map<int, Splice*> splicemap;
typedef vector<Mapping*> mapvec;
typedef vector<Assignment*> assignvec;
typedef vector<int> intvec;
typedef map<int, Gene*> gmap;
typedef multimap<int, Gene*> mgmap;
typedef multimap<int, Mapping*> imap;
typedef multimap<int, Island*> jmap;
typedef multimap<int, int> intmultimap;
typedef map<int, int> covmap;
typedef set<Mapping*> mapset;
typedef set<Exon*> exonset;
typedef vector<Exon*> exonvec;
typedef vector<Island*> istack;
/* ------------------------------------------------------------- */
/* inline functions                                              */
/* ------------------------------------------------------------- */
inline bool sameStrand(int a, int b) {
	if (abs(a-b) == 2) return false;
	else return true;
}
/* ------------------------------------------------------------- */
/* Class declarations                                            */
/* ------------------------------------------------------------- */
//OK
class Exon {
public:
	Exon(int values[]) {
		geneid    = values[0];
		exonid    = values[1];
		regionid  = values[2];
		first     = values[3];
		last      = values[4];
		strand    = values[5];
		tag       = values[6];
		uniq      = values[7];
		elength   = abs(last - first + 1);
		partmap   = new int [maxreadl];
		prexpress = 0;
		for (int i = 0; i < maxreadl; ++i) partmap[i] = 0;
	}
	~Exon() {};

	void updateRead(Read* rd); // RAPARM
	bool maps(Mapping* mp); // RAPARM
	void addMap(Mapping* mp, int readl, int selectedtag); // RAPARM
	void addWeightedMap(Mapping* mp, int readl); // RAPARM
	double overlappingReads(int readl); // RAPARM
	bool assignOverlap(Mapping* m, int readl); //RAPARM (replaces 2 older functions [maps&&addMap])

	int gid() {
		return geneid;
	}
	int eid() {
		return exonid;
	}
	int length() {
		return elength;
	}
	int region() {
		return regionid;
	}
	int str() {
		return strand;
	}
	int start() {
		return first;
	}
	int end() {
		return last;
	}
	void end(int e) {
		last = e;
		return;
	}
	int tags() {
		return tag;
	}
	int uniscore() {
		return uniq;
	}
	int mappings(int m) {
		return partmap[m];
	}
	void setGene (Gene * g) {
		genepointer = g;
	}
	Gene * getGene () {
		return genepointer;
	}
	void setPrexpress(double pex) {
		prexpress = pex;
		return;
	}
	double getPrexpress() {
		return prexpress;
	}
	bool joint (Exon * ex) {
		if (ex->start() < this->end() && ex->end() > this->start() ) {
			return true;
		}
		else if (this->start() - 1 == ex->end() || ex->start() - 1 == this->end()) {
			return true;
		}
		return false;
	}
	friend class Read;
	friend class Region;
protected:
	int regionid;
	int geneid;      //the gene identifier (integer)
	int exonid;
	int first;
	int last;
	int strand;
	int tag;
	int uniq;
	int elength;
	int *partmap;
	double prexpress; // uniqmap expression
	Gene * genepointer;
	const static int maxreadl = MAXREADLENGTH;
};

//OK
class Gene {
public:
	int exonCount;
	int start;
	int end;
	Gene(int gid) {
		geneid    = gid;
		exons = new Exon *[maxexon];
		start = 9;
		end = 0;
		exonCount = 0;
		generegion = 0;
		mapscore   = 0.0;
	}
	~Gene() {};

	void addExon (Exon * ex); // RAPARM
	void calcPrexpressPerExon(int readl); // RAPARM // WiP OK?
	void calcPrexpressPerExonUsingTag(int readl, int activetag); // REPLACEMENT FOR PREXPRESS??? (if exons has no information use tagged exons as reference (average out on lowly expressed genes)

	int exonAddOverlaps(Exon * x); // RAPARM
	double rpkm(int total, int tg); // RAPARM

	bool compatibleWith (Gene * g); //CHECK

	int strand() {
		int str = 0;
		for (int e = 0; e != exonCount; ++e) {
			if ( strandcmp(exons[e]->str(), str) ) {
				if (exons[e]->str() != 0) str = exons[e]->str();
			}
			else {
				cerr << "ABORT TRAP: Gene has Exons on opposite strands!" << endl;
				abort();
			}
		}
		return str;
	}
	int gid() {
		return geneid;
	}
	int length() {
		return (end - start + 1);
	}
	int tagged_length (int t) {
		if (geneid == 0) return 0;
		int tl = 0;
		for (int e=0; e < exonCount; e++) if (exons[e]->tags() >= t) tl += exons[e]->length();
		// IF tl is zero gene will be ignored!
		//if (tl == 0) std::cerr << std::endl << "WARNING: zero tag length for gene " << geneid << " with " << exonCount << " exons" << std::endl;
		return tl;
	}
	int region() {
		return generegion;
	}
	Exon * getExon(int number) {
		return exons[number];
	}
	int exonNumber() {
		return exonCount;
	}
	int mappedReads() {
		return (int) (mapscore + 0.5);
	}
	void addMapscore(double o, double e) {
		mapscore += (double)o*(double)e;
		return;
	}
	double getPrexpressSum() {
		double sum = 0;
		for (int e=0; e < exonCount; e++) {
			sum += exons[e]->getPrexpress();
		}
		return sum;
	}
	string location () {
		stringstream loc;
		loc << start << "\t" << end << "\t" << this->strand();
		return loc.str();
	}
	friend class Exon;
protected:
	int geneid;      //the gene identifier (integer)
	const static int maxexon = MAXGENEEXONS;
	Exon **exons;
	int generegion;
	double mapscore; // the mapping score (sum of all overlapFrac*expressFrac assignments for this gene) >>(divided by tagged length and mapped reads ->RPKM)
};

//OK
class Assignment {
public:
	Assignment(Gene * g, Exon * exo, double o, double e) {
		gene = g;
		exon = exo;
		overlapFrac = o;
		expressFrac = e; //is -1 for ambig mapping if not fractionated yet, 1 for unambiguous
	};
	~Assignment(){};
	int getGeneID () {
		return gene->gid();
	}
	Gene * getGene () {
		return gene;
	}
	int getExonID () {
		return exon->eid();
	}
	Exon * getExon () {
		return exon;
	}
	double getExpressFrac () {
		return expressFrac;
	}
	double getWeight() {
		return exon->getPrexpress() * overlapFrac;
	}
	double getOverlapFrac (int tt) {
		return (exon->tags() >= tt) ? overlapFrac : 0.0;
	}
	void setExpressfrac(double f) {
		expressFrac = f;
		return;
	}
	bool commitExpression(int t) {
		double ovf = this->getOverlapFrac(t);
		if (expressFrac < 0.0) {
			std::cerr << "WARNING: Read may not have been fractinated yet (" << expressFrac << ") => setting to 0 !";
			gene->addMapscore(ovf, 0);
		}
		else gene->addMapscore(ovf, expressFrac);
		if (ovf > 0.0) return true;
		else return false;
	}
	bool singleExonAssign() {
		if (gene->exonNumber() == 1) return true;
		return false;
	}
	bool multiExonAssign() {
		if (gene->exonNumber() != 1) return true;
		return false;
	}
//?	friend class Mapping;
protected:
	Gene * gene;
	Exon * exon;
	double expressFrac;
	double overlapFrac;
};

//OK
class Region {
public:
	Region(){};
	Region(int val){
		rid   = val;
		gsize = 0;
		csize = -1;
		maxGeneLength = 0;
		nullgene = new Gene(0);
	};
	~Region(){};

	void projection(Mapping * mp, int readl); // OKOKOK

	int buildIslands(); // RAPARM
	int connectIslands();  // DEVELOPMENT
	int verifyIslands(bool extend); //sets the bestgene if requested
	int typeIslands(int tag, int readlength); // RAPARM
	Exon * addIslandAnnotationAndResetReads(Island * isl, int newExonId, int newGeneId, int analysisTag, int rl); //RETRO_ADD
	int dicoindex(Mapping * mp); //COMMON

	void covadd(int position, int length) {
		cov[position]++;
		cov[position+length]--;
		return;
	}
	void revcovadd(int position, int length) {
		revcov[position]++;
		revcov[position+length]--;
		return;
	}
	void unicovadd(int position, int length) {
		unicov[position]++;
		unicov[position+length]--;
		return;
	}
	void revunicovadd(int position, int length) {
		revunicov[position]++;
		revunicov[position+length]--;
		return;
	}

	int region() {
		return rid;
	}
	int genenumber() {
		return regiongenes.size();
	}
	Gene * getGene(int g) {
		return garray[g];
	}
	int exonnumber() {
		int ec = 0;
		for(gmap::const_iterator it = regiongenes.begin(); it != regiongenes.end(); ++it){
			ec += it->second->exonCount;
		}
		return ec;
	}
	void addExonToGene(Exon * ex) {
		gmap::iterator iter = regiongenes.find(ex->geneid);
		if( iter == regiongenes.end() ) regiongenes.insert(pair<int, Gene*>(ex->geneid, new Gene(ex->geneid)));
		regiongenes[ex->geneid]->addExon(ex);
		return;
	}
	int orderGenesByEnd(int tg) {
		int untagged = 0;
		if (regiongenes.size() == 0) {
			return untagged;
		}
		mgmap orderedregiongenes;
		for(gmap::const_iterator it = regiongenes.begin(); it != regiongenes.end(); ++it){
			if (it->second->tagged_length(tg) == 0) untagged++;
			orderedregiongenes.insert(pair<int,Gene*>(it->second->end, it->second));
		}
		garray = new Gene * [regiongenes.size()];
		gsize = 0;
		maxGeneLength = 0;
		for(mgmap::const_iterator it = orderedregiongenes.begin(); it != orderedregiongenes.end(); ++it){
			garray[gsize++] = it->second;
			if (it->second->length() > maxGeneLength) maxGeneLength = it->second->length();
		}
		return untagged;
	}

	int gCount() {
		return gsize;
	}

	int iCount () {
		return islands.size();
	}
	Island * getIsland(int i) {
		return islands[i];
	}
	void addIsland(Island * il) {
		islands.push_back(il);
		return;
	}
	friend class Exon;

	covmap cov;       // Coverage (pos,delta?)
	covmap revcov;    // Coverage (pos,delta?)
	covmap unicov;    // Coverage for unique reads
	covmap revunicov; // Coverage for unique reads
protected:
	Gene * nullgene; // the NULL gene
	int	rid;
	gmap regiongenes;
	imap allMaps;
	Gene **garray;
	int gsize;
	int maxGeneLength;
	istack islands; // island containing vector
	int csize; //connected islands
};

//OK
class Splice {
public:
	Splice(){};
	Splice(int msid, int sr, int st){
		spliceID  = msid;
		seqRegion = sr;
		strand    = st;
	};
	~Splice(){};

	void addSlice(int from, int to, int intronid) {
		if (from > to) {
			std::cerr << "Reversed slice";
			abort();
		}
		slices.insert(pair <int,int> (from, to));
		if (intronid != 0) introns[to] = intronid;
		return;
	}
	int region() {
		return seqRegion;
	}
	int str() {
		return strand;
	}
	intmap * resolvePosition(int p, int l) {
		intmap * mslc = new intmap;
		int offset = 0;
		for (intmap::const_iterator s = slices.begin(); s != slices.end(); ++s) {
			if (offset < p && p <= offset + s->second - s->first + 1) {
				do {
					int start = s->first + (p - offset - 1);
					int end   = (l > s->second - start + 1) ? (s->second) : (start + l - 1);
					p        += end - start + 1;
					l        -= end - start + 1;
					offset   += s->second - s->first + 1;
					mslc->insert(pair <int,int> (start,end));
					++s;
				} while (l > 0);
				if (l == 0) return mslc;
				else abort();
			}
			offset += s->second - s->first + 1;
		}
		std::cerr << "ERROR: Mapping and Multisplice do not match! (" << spliceID << "|" << p << "|" << l << ")" << std::endl;
		for (intmap::const_iterator s = slices.begin(); s != slices.end(); ++s) cerr << "\t" << s->first << "\t" << s->second << endl;
		abort();
	}
	intvec * spannedIntrons(intmap * sli) {
		intvec * spi = new intvec;
		// get the last slice
		intmap::iterator lastslice = sli->end();
		--lastslice;
		for (intmap::const_iterator s = sli->begin(); s != sli->end(); ++s) {
			if (introns.find(s->second) != introns.end() && lastslice->second != s->second) {
				spi->push_back(introns.find(s->second)->second);
			}
		}
		return spi;
	}

protected:
	int spliceID;
	int seqRegion;
	int strand;
	intmap slices;
	intmap introns;
};

//OK
class Mapping {
public:
	Mapping(){};
	Mapping(Read * rd, int regid, int str, intmap * slc, int mm){
		regionid = regid;
		strand   = str;
		slices   = slc;
		read     = rd;
		mism     = mm;
		accepted = false;
		splice = NULL;
		flag = -1; // -1 sets not evaluated (or intergenic)
	};
	Mapping(Read * rd, int regid, int str, int pos, int readl, int mm){
		regionid = regid;
		strand   = str;
		slices   = new intmap;
		slices->insert(pair<int, int> (pos,pos+readl-1));
		read     = rd;
		mism     = mm;
		accepted = false;
		splice = NULL;
		flag = -1; // -1 sets not evaluated (or intergenic)
	};
	~Mapping(){
		delete slices;
		assign.clear();
	};

	Gene * assignedGene();
	double highestExpressFrac();
	double assignedGenesSum();
	void addAssignment(Gene * g, Exon * e, double ovp, double ef);
	bool radd(Region ** regions, int rs);

	bool operator==(const Mapping * other) const {
		if (regionid != other->regionid) return false;
		if (!(sameStrand(strand, other->strand))) return false;
		for(intmap::const_iterator aa = slices->begin(); aa != slices->end(); ++aa) {
			if (other->slices->find(aa->first) == other->slices->end() || other->slices->find(aa->first)->second != aa->second) return false;
		}
		return true;
	}
	void addSplice(Splice * spl) {
		splice = spl;
		return;
	}
	bool isUnspliced() {
		if (splice == NULL) return true;
		else return false;
	}
	Splice * getSplice() {
		return splice;
	}
	int str() {
		return strand;
	}
	void show() {
		std::cerr << regionid << "\t" << strand << std::endl;
		for (intmap::const_iterator xx = slices->begin(); xx != slices->end(); ++xx) {
			std::cerr << "\t" << xx->first << "-" << xx->second << std::endl;
		}
		return;
	}
	bool overlaps(Gene * g) {
		// works also for spliced mappings
		if (((g->start <= this->start()) && (this->start() <= g->end)) || ((g->start <= this->end()) && (this->end() <= g->end))) {
			return true;
		}
		if ((this->start() < g->start) && (g->end < this->end())) {
			return true;
		}
		return false;
	}
	bool regiomap(Region * r) {
		if (regionid == r->region()) return true;
		return false;
	}
	int maplength() {
		int len = 0;
		for(intmap::const_iterator it = slices->begin(); it != slices->end(); ++it) {
			len += it->second;
		}
		return len;
	}
	int region() {
		return regionid;
	}
	int start() {
		return slices->begin()->first;
	}
	int end() {
		intmap::iterator it = slices->end();
		--it;
		return it->second;
	}
	bool spliced() {
		if (slices->size() > 1) {
			return true;
		}
		return false;
	}
	bool overlaps(Mapping* m) {
		for (intmap::const_iterator xx = this->slices->begin(); xx != this->slices->end(); ++xx) {
			for (intmap::const_iterator yy = m->slices->begin(); yy != m->slices->end(); ++yy) {
				if ((yy->first <= xx->first && xx->first <= yy->second) ||
					(yy->first <= xx->second && xx->second <= yy->second) ||
					(xx->first <= yy->first && yy->second <= xx->second)) {
					return true;
				}
			}
		}
		return false;
	}
	void accept() {
		accepted = true;
		return;
	}
	bool notAccepted() {
		return !(accepted);
	}
	int gaps() {
		return slices->size() - 1;
	}
	void setFlag(int f) {
		// flags will never be downgraded
		if (flag < f)flag = f;
		return;
	}
	int getFlag() {
		return flag;
	}
	Read * getRead () {
		return read;
	}
	int assignments() {
		return assign.size();
	}
	Assignment * getAssignment(int a) {
		return assign[a];
	}
	int singleExon() {
		if (!(assign.size() > 0)) return 0;
		int se = 0;
		for (unsigned int o = 0; o < assign.size(); ++o) {
			if (assign[o]->singleExonAssign()) se++;
		}
		return se;
	}
	bool multiExonAssign() {
		if (!(assign.size() > 0)) return false;
		for (unsigned int o = 0; o < assign.size(); ++o) if (assign[o]->multiExonAssign()) return true;
		return false;
	}
	int sliceEndWithStart(int startsWith) {
		for (intmap::const_iterator it = slices->begin(); it != slices->end(); ++it) {
			if (it->first == startsWith) return it->second;
		}
		int rr = startsWith + this->maplength() - 1;
		std::cerr << "WARNING: Asked for a nonexistent mapping slice, returned " << rr << std::endl;
		return rr;
	}
	double sliceFracWithStart(int startsWith) {
		double sliceLength = 0.0;
		double totalLength = 0.0;
		for (intmap::const_iterator it = slices->begin(); it != slices->end(); ++it) {
			if (it->first == startsWith) sliceLength = it->second - it->first + 1;
			totalLength += it->second - it->first + 1;
		}
		return sliceLength / totalLength;
	}
	string cigarline() {
		stringstream ss;
		ss << "(";
		for (intmap::const_iterator it = slices->begin(); it != slices->end(); ++it) {
			ss << "." << it->first << "-" << it->second << ".";
		}
		ss << ")";

		return ss.str();
	}
	void removeAssignments() {
		for (unsigned int a = 0; a != assign.size(); ++a) delete assign[a];
		assign.clear();
	}
	intmap * getSlices() {
		return slices;
	}
	friend class Exon;   //OK
	friend class Region; //OK
	friend class Island; //OK
	friend class Read;   //OK
	bool accepted;
protected:
	intmap * slices; // move to protected again
	int	regionid;
	int strand;
	int flag; // -1:intergenic 0:genic 1:exonic
	int mism; // number of mismatches
	Read * read;
	Splice * splice;
	assignvec assign;
};

//OK
class Read {
public:
	Read(){};
	Read(int identifier) {
		readid    = identifier;
		remapFlag = false;
	}
	~Read(){
		// destruct all mappings
		//delete mappings;
	}

	void fractionate(); // OK
	void equalize();    // OBSOLETE AS COVERAGE ROUTINE WILL TAKE CARE
	int  unify(bool leastMismatch); // WiP
	bool calculateCoverage(Region ** regions, int rs);

	//FUNCTIONS TO CHECK FOR NECESSITY
	//FUNCTIONS TO CHECK FOR NECESSITY
	//FUNCTIONS TO CHECK FOR NECESSITY
	int totalAssignments() {
		int as = 0;
		for(unsigned int m=0; m < mappings.size(); m++) as += mappings[m]->assignments();
		return as;
	}
	//FUNCTIONS TO CHECK FOR NECESSITY
	//FUNCTIONS TO CHECK FOR NECESSITY
	//FUNCTIONS TO CHECK FOR NECESSITY

	bool isUnambiguous() {
		if (mappings.size() == 1) {
			return true;
		}
		return false;
	}
	int countMappings() {
		return mappings.size();
	}
	void addFullMapping(int r, int s, int p, int l, int mm) { // region, strand, start, readlength
		Mapping * map_n = new Mapping(this,r,s,p,l,mm);
		if (!(this->contains(map_n))) mappings.push_back(map_n);
		else abort();
		return;
	}
	void addSpliceMapping(Splice * sp, int s, int p, int l, int mm) { // region, strand, position, readlength, splice
		//cerr << " A" << sp ;
		int r = sp->region();
		//cerr << " B";
		intmap * sm = sp->resolvePosition(p,l);
		//cerr << " C";
		Mapping * map_n = new Mapping(this,r,s,sm,mm);
		//cerr << " D";
		map_n->addSplice(sp);
		//cerr << " E";
		if (!(this->contains(map_n))) mappings.push_back(map_n);
		else abort();
		//cerr << " F";
		return;
	}
	int rid() {
		return readid;
	}
	Mapping * readMapping(int mid) {
		return mappings[mid];
	}
	Mapping * trustedMapping() {
		Mapping * ret = NULL;
		for (unsigned int m = 0; m != mappings.size(); ++m) {
			if (mappings[m]->accepted) {
				if (ret != NULL) {
					cerr << "FATAL: Read has more than one accepted mapping" << endl;
					abort();
				}
				ret = mappings[m];
			}
		}
		if (ret == NULL) cerr << "WARNING: Called trustedMapping on unresolved Read" << endl;
		return ret;
	}
	bool contains(Mapping * mp) {
		for(unsigned int v = 0; v != mappings.size(); ++v) {
			if (mp == mappings[v]) return true;
		}
		return false;
	}

	bool isGenic() {
		int exom = 0;
		for (unsigned int m = 0; m < mappings.size(); m++) if (mappings[m]->assignments() > 0) exom++;
		if (exom > 0) return true;
		return false;
	}
	void resetForRemap() { // marks reads for remapping (after retro detection)
		remapFlag = true;
		for(unsigned int i = 0; i != mappings.size(); ++i) mappings[i]->removeAssignments();
		return;
	}
	bool flaggedForRemap() {
		return remapFlag;
	}
	friend class Mapping;
	friend class Island;
protected:
	bool remapFlag;
	int readid;
	double uniq;
	mapvec mappings;
};

//OK
class Island {
public:
	Island(Region * r, int firstpos, Mapping * m){
		region     = r;
		totalReads = m->sliceFracWithStart(firstpos);
		allReads   = 1;
		bGene      = NULL;
		bGeneReads = 0;
		from       = firstpos;
		to         = m->sliceEndWithStart(firstpos);
		leftmost   = m->start();
		rightmost  = m->end();
		connex     = -1;
		strand     = m->strand;
		flag       = m->getFlag();
		islandID   = r->iCount();
		rFlag      = '-';
		posmap.insert(imap::value_type(firstpos, m));
		// defined by other methods
		uniscore      = -1;
		dominanceTest = -1;
		lengthTest    = -1;
		multiexonTest = -1;
		//linkability
		linkage = false;
		updateLinkage(m);
	}
	~Island() {}

	bool canBeAddedthenAdd(int first, Mapping * m);
	bool evaluateGeneConverage(Gene * ng); //return true if bestgene found

	// merged 3 test methods into one
	void runTests();
	// annotation methods
	int estimateStrand();
	int estimateUniscore();

	string GFFline(int readlength) {
		stringstream ss;
		ss << setprecision(3);
		ss << region->region() << "\t"; //CHROMOSOME
		ss << "RNASEQ\t"; //SOURCE
		if      (rFlag == 'E') ss << "EXON\t";
		else if (rFlag == 'R') ss << "RETROGENE\t";
		else if (rFlag == 'F') ss << "FRAGMENT\t";
		else if (rFlag == 'P') ss << "PSEUDOGENE\t";
		else if (rFlag == '-') ss << "UNKNOWN\t";
		ss << from << "\t"; //START
		ss << to << "\t"; //END
		ss << this->coverage(readlength) << "\t"; //SCORE (COVERAGE)
		if (strand != 0) ss << strand << "\t"; //STRAND
		else             ss << "."    << "\t"; //STRAND
		ss << "." << "\t"; //FRAME
		ss << "Group " << connex; //GROUPINGID
		ss << " ; Island "        << islandID ;  //ISLAND_ID
		ss << " ; Type "          << flag ;      //TYPE (-1|0|+1)
		ss << " ; Length "        << to - from + 1 ; //LENGTH
		ss << " ; Reads "         << this->readCount() ; //READS
		ss << " ; Distinct "      << this->distinctReads() ; //DISTINCT_READS
		ss << " ; Unique "        << this->uniqueReads() ; //UNIQUE_READS
		ss << " ; Linkable "      << (this->linkable() ? "YES" : "NO"); //UNIQUE_READS
		if (this->bestGeneID() != 0) {
			if (flag != 1) {
				ss << " ; Gene "          << this->bestGeneID() ; //BESTGENE
				ss << " ; GeneReads "     << this->bestGeneReads() ; //BESTGENE_READS
				ss << " ; GeneSpliced "   << splicedGeneMaps ; //BESTGENE_SPLICED
				ss << " ; dominanceTest " << dominanceTest ; //FRAC OF AMBIGUOUS MAPPINGS IN BESTGENE
				ss << " ; lengthTest "    << lengthTest ; //LENGTH FRAC BESTGENE/ISLAND
				ss << " ; multiexonTest " << multiexonTest ; //MULTIEXONS
			}
		}
		return ss.str();
	}
	void updateLinkage(Mapping * mm) {
		if (!(mm->isUnspliced())) linkage = true;
		return;
	}
	bool linkable() {
		return linkage;
	}
	double coverage(int rl) {
		return double(rl) * totalReads / double(this->length());
	}
	double readCount() {
		return totalReads;
	}
	int allReadCount() {
		return allReads;
	}
	int start() {
		return from;
	}
	int end() {
		return to;
	}
	int length() {
		return to - from + 1;
	}
	int getIslandID() {
		return islandID;
	}
	int getFlag() {
		return flag;
	}
	void raiseFlag(int fl) {
		if (fl > flag) flag = fl;
		return;
	}
	int distinctReads() {
		int dRead = 0;
		int last = 0;
		for(imap::const_iterator it = posmap.begin(); it != posmap.end(); ++it){
			if (it->first != last) dRead++;
			last = it->first;
		}
		return dRead;
	}
	Region * getRegion() {
		return region;
	}

	int bestGeneReads() {
		return bGeneReads;
	}
	void bestGene(Gene * g) {
		bGene = g;
		return;
	}
	Gene * getBestGene() {
		return bGene;
	}
	int bestGeneID() {
		int returner = 0;
		if (bGene != NULL) returner =  bGene->gid();
		return returner;
	}
	int uniqueReads () {
		int u = 0;
		for(imap::const_iterator it = posmap.begin(); it != posmap.end(); ++it) if (it->second->getRead()->isUnambiguous()) u++;
		return u;
	}
	int ambiguousReads () {
		int u = 0;
		for(imap::const_iterator it = posmap.begin(); it != posmap.end(); ++it) if (!(it->second->getRead()->isUnambiguous())) u++;
		return u;
	}

	char getRflagchar () {
		return rFlag;
	}
	void setRflag (char r) {
		rFlag = r;
		return;
	}
	int connexID() {
		return connex;
	}
	void connexID(int cid) {
		connex = cid;
	}
	int leftend() {
		return leftmost;
	}
	int rightend() {
		return rightmost;
	}

	//type tests
	double dominanceTest;
	double lengthTest;
	int multiexonTest;
	int splicedGeneMaps;

	friend class Region; // for island annotation build
protected:
	const static int idist    = ISLANDIST;
	typedef map<Gene*, int> gmap;

	gmap genemap;
	gmap gm; // temporary

	imap posmap;

	char rFlag;
	bool linkage; // true if island contains a spliced read
	double totalReads;
	int allReads;
	Region * region;
	int from;
	int to;
	int leftmost; // leftmost slice (even if not in island)
	int rightmost; // rightmost slice (even if not in island)
	int connex; // connex id (same ids are connected
	int strand; // 0:both 1:fwd -1:rev
	int flag;
	int islandID; // allows 1000000 islands
	int uniscore;
	Gene * bGene;
	int bGeneReads;
};

//////////////////////////////
/////// COMMON METHODS ///////
//////////////////////////////

int Region::dicoindex(Mapping * mp) {
	int begin = 0;
	int end = gsize;
	int mid = (gsize+begin)/2;

	while (begin != end) {
		if (garray[mid]->end < mp->start()) {
			begin = mid+1;
		}
		else if (garray[mid]->end > mp->start()) {
			end = mid;
		}
		else {
			while (mid >= 0 && garray[mid]->end == mp->start()) {
				mid--;
			}
			mid++;
			end = mid;
			begin = mid;
		}
		mid = (end+begin)/2;
	}
	return mid;
}

max_stars_repo_name: preciserobot/rex

max_issues_repo_name: preciserobot/rex

max_forks_repo_name: preciserobot/rex


text:
//
// Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.
// Copyright (c) 2015-2017, University of Bremen
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#define BOOST_TEST_MODULE VizTest
#include <boost/test/included/unit_test.hpp>

#include <Eigen/Geometry>

#include "StandaloneVisualizer.hpp"
#include <maps/grid/TraversabilityMap3d.hpp>

using namespace ::maps::grid;

BOOST_AUTO_TEST_CASE(traversability_map3d_viz_test)
{
    StandaloneVisualizer app;

    TraversabilityMap3d<TraversabilityNode<double> *> map;

    map.setResolution(Eigen::Vector2d(0.5, 0.5));
    map.resize(Vector2ui(20, 20));

    map.getLocalFrame().translation() << 0.5*map.getSize(), 0;

    TraversabilityNode<double> *child1 = new TraversabilityNode<double>(0.0, Index(1,2));
    map.at(child1->getIndex()).insert(child1);
    TraversabilityNode<double> *child2 = new TraversabilityNode<double>(1.0, Index(1,3));
    map.at(child2->getIndex()).insert(child2);
    TraversabilityNode<double> *child3 = new TraversabilityNode<double>(2.0, Index(1,4));
    map.at(child3->getIndex()).insert(child3);

    TraversabilityNode<double> *parentNode = new TraversabilityNode<double>(12.0, Index(1,10));
    map.at(parentNode->getIndex()).insert(parentNode);

    child1->setType(TraversabilityNodeBase::FRONTIER);
    child1->setType(TraversabilityNodeBase::HOLE);
    child1->setType(TraversabilityNodeBase::OBSTACLE);
    parentNode->setType(TraversabilityNodeBase::TRAVERSABLE);

    parentNode->addConnection(child1);
    child1->addConnection(parentNode);

    parentNode->addConnection(child2);
    child2->addConnection(parentNode);

    parentNode->addConnection(child3);
    child3->addConnection(parentNode);

    TraversabilityMap3d<maps::grid::TraversabilityNodeBase *> base_map = map.copyCast<maps::grid::TraversabilityNodeBase *>();

    while (app.wait(1000))
    {
        app.updateData(base_map);
    }
}

ext: cpp

max_stars_repo_name: skasperski/slam-maps

max_issues_repo_name: skasperski/slam-maps

max_forks_repo_name: skasperski/slam-maps


text:
#include <boost/algorithm/string.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <algorithm>
#include <iostream>
#include <numeric>

namespace bi = boost::interprocess;
namespace bc = boost::container;

namespace common {
template <typename Alloc>
class CheckList {
    typedef typename Alloc::template rebind<double>::other double_allocator;
    typedef bc::vector<double, double_allocator> double_vector;

public:
    double_vector values;

    typedef Alloc allocator_type;
    CheckList ( const allocator_type& void_alloc = allocator_type() ) : values ( void_alloc ) {}

    template <typename Alloc2>
    CheckList ( CheckList<Alloc2> const& other, const allocator_type& void_alloc = allocator_type() )
        : values ( void_alloc ) {
        for ( auto& v : other.values ) values.emplace_back ( v );
    }

    friend std::ostream& operator<< ( std::ostream& os, const CheckList& o ) {
        for ( size_t i = 0; i < o.values.size(); i++ )
            os << ( i?", ":"" ) << o.values[i];
        return os;
    }
};

template <typename Alloc>
class Lists {
    typedef typename Alloc::template rebind<CheckList<Alloc> >::other checklist_allocator;

public:
    typedef Alloc allocator_type;
    typedef bc::vector<CheckList<Alloc>, checklist_allocator> checklist_vector;

    template <typename Alloc2>
    Lists& operator= ( Lists<Alloc2> const& other ) {
        for ( auto& cl : other.checklists ) checklists.emplace_back ( cl );
        return *this;
    }

    Lists ( const Alloc& void_alloc = allocator_type() ) : checklists ( void_alloc ) {}
    checklist_vector checklists;

    friend std::ostream& operator<< ( std::ostream& os, const Lists& o ) {
        for ( size_t i = 0; i < o.checklists.size(); i++ )
            os << o.checklists[i] << '\n';
        return os;
    }
};
}

namespace Shared {
typedef bi::managed_mapped_file::segment_manager                             segment_manager_t;
typedef bc::scoped_allocator_adaptor<bi::allocator<void, segment_manager_t> >  void_allocator;
using Lists = common::Lists<void_allocator>;
}

namespace Heap {
typedef std::allocator<void> void_allocator;
using Lists = common::Lists<void_allocator>;
}

Heap::Lists generate_local() {
    Heap::Lists lists;
    Heap::Lists::checklist_vector::value_type v;

    for ( int i=0; i<10; ++i ) {
        v.values.emplace_back ( i+1 );
        lists.checklists.push_back ( v );
    }

    return lists;
}

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

    if ( argc > 1 && ( boost::iequals ( "clear", argv[1] ) || boost::iequals ( "c", argv[1] ) ) ) {
        std::cout << "Remove shared memory" << std::endl;
        std::remove ( "MySharedMemory" );
    }

    //Create shared memory
    bi::managed_mapped_file segment ( bi::open_or_create,"MySharedMemory", 16*1024 );

    using Lists = Shared::Lists;

    //An allocator convertible to any allocator<T, segment_manager_t> type
    Lists::allocator_type alloc_inst ( segment.get_segment_manager() );
    Lists& lists = *segment.find_or_construct<Lists> ( "Lists" ) ( alloc_inst );

    if ( lists.checklists.size() != 10 ) {
        std::cout << "Create Data" << std::endl;
        auto x = generate_local();
        lists = std::move ( x );
    } else {
        std::cout << "Data Exists" << std::endl;
    }

    std::cout << lists << std::endl;
}

max_stars_repo_name: ShmFw/shmfw

max_issues_repo_name: ShmFw/shmfw

max_forks_repo_name: ShmFw/shmfw


text:
//---------------------------------------------------------------------------//
//!
//! \file   tstPolynomialDistribution.cpp
//! \author Alex Robinson
//! \brief  Polynomial distribution unit tests
//!
//---------------------------------------------------------------------------//

// Std Lib Includes
#include <iostream>

// Boost Includes
#include <boost/units/systems/si.hpp>
#include <boost/units/systems/cgs.hpp>
#include <boost/units/io.hpp>

// FRENSIE Includes
#include "Utility_PolynomialDistribution.hpp"
#include "Utility_RandomNumberGenerator.hpp"
#include "Utility_PhysicalConstants.hpp"
#include "Utility_UnitTraits.hpp"
#include "Utility_QuantityTraits.hpp"
#include "Utility_ElectronVoltUnit.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
#include "ArchiveTestHelpers.hpp"

//---------------------------------------------------------------------------//
// Testing Types
//---------------------------------------------------------------------------//

using boost::units::quantity;
using namespace Utility::Units;
namespace si = boost::units::si;
namespace cgs = boost::units::cgs;

typedef TestArchiveHelper::TestArchives TestArchives;

typedef std::tuple<
  std::tuple<si::energy,si::amount,cgs::energy,si::amount>,
  std::tuple<cgs::energy,si::amount,si::energy,si::amount>,
  std::tuple<si::length,si::energy,cgs::length,cgs::energy>,
  std::tuple<cgs::length,cgs::energy,si::length,si::energy>,
  std::tuple<si::length,si::mass,cgs::length,cgs::mass>,
  std::tuple<cgs::length,cgs::mass,si::length,si::mass>,
  std::tuple<si::length,void*,cgs::length,void*>,
  std::tuple<cgs::length,void*,si::length,void*>,
  std::tuple<void*,si::mass,void*,cgs::mass>,
  std::tuple<void*,cgs::mass,void*,si::mass>,
  std::tuple<si::length,si::dimensionless,cgs::length,cgs::dimensionless>,
  std::tuple<cgs::length,cgs::dimensionless,si::length,si::dimensionless>,
  std::tuple<si::dimensionless,si::length,cgs::dimensionless,cgs::length>,
  std::tuple<cgs::dimensionless,cgs::length,si::dimensionless,si::length>
 > TestUnitTypeQuads;

//---------------------------------------------------------------------------//
// Testing Variables
//---------------------------------------------------------------------------//

std::shared_ptr<Utility::UnivariateDistribution> distribution;

std::shared_ptr<Utility::UnitAwareUnivariateDistribution<MegaElectronVolt,si::amount> >
  unit_aware_distribution;

//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that the distribution can be evaluated
FRENSIE_UNIT_TEST( PolynomialDistribution, evaluate )
{
  FRENSIE_CHECK_EQUAL( distribution->evaluate( -1.0 ), 0.0 );
  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.0 ), 1.0 );
  FRENSIE_CHECK_EQUAL( distribution->evaluate( 0.5 ), 2.75 );
  FRENSIE_CHECK_EQUAL( distribution->evaluate( 1.0 ), 6.0 );
  FRENSIE_CHECK_EQUAL( distribution->evaluate( 2.0 ), 0.0 );
}

//---------------------------------------------------------------------------//
// Check that the unit-aware distribution can be evaluated
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution, evaluate )
{
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( -1.0*MeV ),
		       0.0*si::mole );
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.0*MeV ),
		       1.0*si::mole );
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 0.5*MeV ),
		       2.75*si::mole );
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 1.0*MeV ),
		       6.0*si::mole );
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluate( 2.0*MeV ),
		       0.0*si::mole );
}

//---------------------------------------------------------------------------//
// Check that the PDF can be evaluated
FRENSIE_UNIT_TEST( PolynomialDistribution, evaluatePDF )
{
  FRENSIE_CHECK_EQUAL( distribution->evaluatePDF( -1.0 ), 0.0 );
  FRENSIE_CHECK_EQUAL( distribution->evaluatePDF( 0.0 ), 1.0/3.0 );
  FRENSIE_CHECK_EQUAL( distribution->evaluatePDF( 0.5 ), 2.75/3.0 );
  FRENSIE_CHECK_EQUAL( distribution->evaluatePDF( 1.0 ), 2.0 );
  FRENSIE_CHECK_EQUAL( distribution->evaluatePDF( 2.0 ), 0.0 );
}

//---------------------------------------------------------------------------//
// Check that the unit-aware PDF can be evaluated
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution, evaluatePDF )
{
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluatePDF( -1.0*MeV ),
		       0.0/MeV );
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluatePDF( 0.0*MeV ),
		       (1.0/3.0)/MeV );
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluatePDF( 0.5*MeV ),
		       (2.75/3.0)/MeV );
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluatePDF( 1.0*MeV ),
		       2.0/MeV );
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->evaluatePDF( 2.0*MeV ),
		       0.0/MeV );
}

//---------------------------------------------------------------------------//
// Check that the distribution can be sampled
FRENSIE_UNIT_TEST( PolynomialDistribution, sample )
{
  std::vector<double> fake_stream( 6 );
  fake_stream[0] = 0.0;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.0;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );
  double sample = distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, 0.0 );

  sample = distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, 0.5 );

  fake_stream[0] = 0.5;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.5;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );
  sample = distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, 0.0 );

  sample = distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, sqrt(0.5) );

  fake_stream[0] = 0.7;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.7;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );
  sample = distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, 0.0 );

  sample = distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, pow( 0.5, 1.0/3.0 ) );
}

//---------------------------------------------------------------------------//
// Check that the unit-aware distribution can be sampled
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution, sample )
{
  std::vector<double> fake_stream( 6 );
  fake_stream[0] = 0.0;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.0;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );
  quantity<MegaElectronVolt> sample = unit_aware_distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, 0.0*MeV );

  sample = unit_aware_distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, 0.5*MeV );

  fake_stream[0] = 0.5;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.5;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );
  sample = unit_aware_distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, 0.0*MeV );

  sample = unit_aware_distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, sqrt(0.5)*MeV );

  fake_stream[0] = 0.7;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.7;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );
  sample = unit_aware_distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, 0.0*MeV );

  sample = unit_aware_distribution->sample();
  FRENSIE_CHECK_EQUAL( sample, pow( 0.5, (1.0/3.0) )*MeV );
}

//---------------------------------------------------------------------------//
// Check that the distribution can be sampled
FRENSIE_UNIT_TEST( PolynomialDistribution, sampleAndRecordTrials )
{
  std::vector<double> fake_stream( 6 );
  fake_stream[0] = 0.0;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.0;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  Utility::DistributionTraits::Counter trials = 0;

  double sample = distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, 0.0 );
  FRENSIE_CHECK_EQUAL( 1.0/trials, 1.0 );

  sample = distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, 0.5 );
  FRENSIE_CHECK_EQUAL( 2.0/trials, 1.0 );

  fake_stream[0] = 0.5;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.5;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  trials = 0;

  sample = distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, 0.0 );
  FRENSIE_CHECK_EQUAL( 1.0/trials, 1.0 );

  sample = distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, sqrt(0.5) );
  FRENSIE_CHECK_EQUAL( 2.0/trials, 1.0 );

  fake_stream[0] = 0.7;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.7;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  trials = 0;

  sample = distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, 0.0 );
  FRENSIE_CHECK_EQUAL( 1.0/trials, 1.0 );

  sample = distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, pow( 0.5, 1.0/3.0 ) );
  FRENSIE_CHECK_EQUAL( 2.0/trials, 1.0 );
}

//---------------------------------------------------------------------------//
// Check that the unit-aware distribution can be sampled
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution, sampleAndRecordTrials )
{
  std::vector<double> fake_stream( 6 );
  fake_stream[0] = 0.0;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.0;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  Utility::DistributionTraits::Counter trials = 0;

  quantity<MegaElectronVolt> sample =
    unit_aware_distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, 0.0*MeV );
  FRENSIE_CHECK_EQUAL( 1.0/trials, 1.0 );

  sample = unit_aware_distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, 0.5*MeV );
  FRENSIE_CHECK_EQUAL( 2.0/trials, 1.0 );

  fake_stream[0] = 0.5;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.5;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  trials = 0;

  sample = unit_aware_distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, 0.0*MeV );
  FRENSIE_CHECK_EQUAL( 1.0/trials, 1.0 );

  sample = unit_aware_distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, sqrt(0.5)*MeV );
  FRENSIE_CHECK_EQUAL( 2.0/trials, 1.0 );

  fake_stream[0] = 0.7;
  fake_stream[1] = 0.0;
  fake_stream[2] = 0.7;
  fake_stream[3] = 0.5;

  Utility::RandomNumberGenerator::setFakeStream( fake_stream );

  trials = 0;

  sample = unit_aware_distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, 0.0*MeV );
  FRENSIE_CHECK_EQUAL( 1.0/trials, 1.0 );

  sample = unit_aware_distribution->sampleAndRecordTrials( trials );
  FRENSIE_CHECK_EQUAL( sample, pow( 0.5, 1.0/3.0 )*MeV );
  FRENSIE_CHECK_EQUAL( 2.0/trials, 1.0 );
}

//---------------------------------------------------------------------------//
// Check that the upper bound of the distribution independent variable can be
// returned
FRENSIE_UNIT_TEST( PolynomialDistribution, getUpperBoundOfIndepVar )
{
  FRENSIE_CHECK_EQUAL( distribution->getUpperBoundOfIndepVar(), 1.0 );
}

//---------------------------------------------------------------------------//
// Check that the upper bound of the unit-aware distribution independent
// variable can be returned
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution, getUpperBoundOfIndepVar )
{
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getUpperBoundOfIndepVar(),
		       1.0*MeV );
}

//---------------------------------------------------------------------------//
// Check that the lower bound of the unit-aware distribution independent
// variable can be returned
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution, getLowerBoundOfIndepVar )
{
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getLowerBoundOfIndepVar(),
		       0.0*MeV );
}

//---------------------------------------------------------------------------//
// Check that the distribution type can be returned
FRENSIE_UNIT_TEST( PolynomialDistribution, getDistributionType )
{
  FRENSIE_CHECK_EQUAL( distribution->getDistributionType(),
		       Utility::POLYNOMIAL_DISTRIBUTION );
}

//---------------------------------------------------------------------------//
// Check that the unit-aware distribution type can be returned
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution, getDistributionType )
{
  FRENSIE_CHECK_EQUAL( unit_aware_distribution->getDistributionType(),
		       Utility::POLYNOMIAL_DISTRIBUTION );
}

//---------------------------------------------------------------------------//
// Check if the distribution is tabular
FRENSIE_UNIT_TEST( PolynomialDistribution, isTabular )
{
  FRENSIE_CHECK( !distribution->isTabular() );
}

//---------------------------------------------------------------------------//
// Check if the unit-aware distribution is tabular
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution, isTabular )
{
  FRENSIE_CHECK( !unit_aware_distribution->isTabular() );
}

//---------------------------------------------------------------------------//
// Check if the distribution is continuous
FRENSIE_UNIT_TEST( PolynomialDistribution, isContinuous )
{
  FRENSIE_CHECK( distribution->isContinuous() );
}

//---------------------------------------------------------------------------//
// Check if the unit-aware distribution is continuous
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution, isContinuous )
{
  FRENSIE_CHECK( unit_aware_distribution->isContinuous() );
}

//---------------------------------------------------------------------------//
// Check if the distribution is compatible with the interpolation type
FRENSIE_UNIT_TEST( PolynomialDistribution, isCompatibleWithInterpType )
{
  FRENSIE_CHECK( distribution->isCompatibleWithInterpType<Utility::LinLin>() );
  FRENSIE_CHECK( distribution->isCompatibleWithInterpType<Utility::LinLog>() );
  FRENSIE_CHECK( distribution->isCompatibleWithInterpType<Utility::LogLin>() );
  FRENSIE_CHECK( distribution->isCompatibleWithInterpType<Utility::LogLog>() );

  // Create another distribution that is compatible with all interpolation
  // types
  std::vector<double> coeffs( 4 );
  coeffs[0] = 1.0;
  coeffs[1] = 2.0;
  coeffs[2] = 3.0;
  coeffs[3] = 0.0;

  std::shared_ptr<Utility::PolynomialDistribution>
    test_dist( new Utility::PolynomialDistribution( coeffs, 1.0, 2.0 ) );

  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LinLin>() );
  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LinLog>() );
  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LogLin>() );
  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LogLog>() );

  // Create another distribution that is only compatible with lin-lin interp
  coeffs[0] = 0.0;

  test_dist.reset( new Utility::PolynomialDistribution( coeffs, 0.0, 1.0 ) );

  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LinLin>() );
  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LinLog>() );
  FRENSIE_CHECK( !test_dist->isCompatibleWithInterpType<Utility::LogLin>() );
  FRENSIE_CHECK( !test_dist->isCompatibleWithInterpType<Utility::LogLog>() );
}

//---------------------------------------------------------------------------//
// Check if the unit-aware distribution is compatible with the interp type
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution,
                   isCompatibleWithInterpType )
{
  FRENSIE_CHECK( unit_aware_distribution->isCompatibleWithInterpType<Utility::LinLin>() );
  FRENSIE_CHECK( unit_aware_distribution->isCompatibleWithInterpType<Utility::LinLog>() );
  FRENSIE_CHECK( unit_aware_distribution->isCompatibleWithInterpType<Utility::LogLin>() );
  FRENSIE_CHECK( unit_aware_distribution->isCompatibleWithInterpType<Utility::LogLog>() );

  // Create another distribution that is compatible with all interpolation
  // types
  std::vector<double> coeffs( 4 );
  coeffs[0] = 1.0;
  coeffs[1] = 2.0;
  coeffs[2] = 3.0;
  coeffs[3] = 0.0;

  std::shared_ptr<Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount> >
    test_dist( new Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount>( coeffs, 1.0*MeV, 2.0*MeV ) );

  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LinLin>() );
  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LinLog>() );
  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LogLin>() );
  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LogLog>() );

  // Create another distribution that is only compatible with lin-lin interp
  coeffs[0] = 0.0;

  test_dist.reset( new Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount>( coeffs, 0.0*MeV, 1.0*MeV ) );

  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LinLin>() );
  FRENSIE_CHECK( test_dist->isCompatibleWithInterpType<Utility::LinLog>() );
  FRENSIE_CHECK( !test_dist->isCompatibleWithInterpType<Utility::LogLin>() );
  FRENSIE_CHECK( !test_dist->isCompatibleWithInterpType<Utility::LogLog>() );
}

//---------------------------------------------------------------------------//
// Check that a distribution can be placed in a stream
FRENSIE_UNIT_TEST( PolynomialDistribution, ostream_operator )
{
  std::ostringstream oss;

  oss << Utility::PolynomialDistribution();

  Utility::VariantMap dist_data =
    Utility::fromString<Utility::VariantMap>( oss.str() );

  FRENSIE_CHECK_EQUAL( dist_data["type"].toString(),
                       "Polynomial Distribution" );
  FRENSIE_CHECK_EQUAL( dist_data["independent unit"].toString(), "void", SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["dependent unit"].toString(), "void", SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["coefficients"].toType<std::vector<double> >(),
                       std::vector<double>({1.0}),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["lower bound"].toDouble(), 0.0, SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["upper bound"].toDouble(), 1.0, SHOW_LHS );

  oss.str( "" );
  oss.clear();

  oss << Utility::PolynomialDistribution( {0.0, 1.0, 0.0, 1.0} );

  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );

  FRENSIE_CHECK_EQUAL( dist_data["type"].toString(),
                       "Polynomial Distribution" );
  FRENSIE_CHECK_EQUAL( dist_data["independent unit"].toString(), "void", SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["dependent unit"].toString(), "void", SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["coefficients"].toType<std::vector<double> >(),
                       std::vector<double>({0.0, 1.0, 0.0, 1.0}) );
  FRENSIE_CHECK_EQUAL( dist_data["lower bound"].toDouble(), 0.0 );
  FRENSIE_CHECK_EQUAL( dist_data["upper bound"].toDouble(), 1.0 );

  oss.str( "" );
  oss.clear();

  oss << Utility::PolynomialDistribution( {0.0, 1.0, 0.0, 1.0}, 1.0, 2.0 );

  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );

  FRENSIE_CHECK_EQUAL( dist_data["type"].toString(),
                       "Polynomial Distribution" );
  FRENSIE_CHECK_EQUAL( dist_data["independent unit"].toString(), "void", SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["dependent unit"].toString(), "void", SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["coefficients"].toType<std::vector<double> >(),
                       std::vector<double>({0.0, 1.0, 0.0, 1.0}) );
  FRENSIE_CHECK_EQUAL( dist_data["lower bound"].toDouble(), 1.0 );
  FRENSIE_CHECK_EQUAL( dist_data["upper bound"].toDouble(), 2.0 );

  oss.str( "" );
  oss.clear();

  oss << *distribution;

  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );

  FRENSIE_CHECK_EQUAL( dist_data["type"].toString(),
                       "Polynomial Distribution" );
  FRENSIE_CHECK_EQUAL( dist_data["independent unit"].toString(), "void", SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["dependent unit"].toString(), "void", SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["coefficients"].toType<std::vector<double> >(),
                       std::vector<double>({1.0, 2.0, 3.0, 0.0}) );
  FRENSIE_CHECK_EQUAL( dist_data["lower bound"].toDouble(), 0.0 );
  FRENSIE_CHECK_EQUAL( dist_data["upper bound"].toDouble(), 1.0 );
}

//---------------------------------------------------------------------------//
// Check that a unit-aware distribution can be placed in a stream
FRENSIE_UNIT_TEST( UnitAwarePolynomialDistribution, ostream_operator )
{
  std::ostringstream oss;

  oss << Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount>();

  Utility::VariantMap dist_data =
    Utility::fromString<Utility::VariantMap>( oss.str() );

  FRENSIE_CHECK_EQUAL( dist_data["type"].toString(),
                       "Polynomial Distribution" );
  FRENSIE_CHECK_EQUAL( dist_data["independent unit"].toString(),
                       Utility::UnitTraits<MegaElectronVolt>::name(),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["dependent unit"].toString(),
                       Utility::UnitTraits<si::amount>::name(),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["coefficients"].toType<std::vector<double> >(),
                       std::vector<double>({1.0}),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["lower bound"].toType<quantity<MegaElectronVolt> >(),
                       0.0*MeV,
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["upper bound"].toType<quantity<MegaElectronVolt> >(),
                       1.0*MeV,
                       SHOW_LHS );

  oss.str( "" );
  oss.clear();

  oss << Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount>( {0.0, 1.0, 0.0, 1.0} );

  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );

  FRENSIE_CHECK_EQUAL( dist_data["type"].toString(),
                       "Polynomial Distribution" );
  FRENSIE_CHECK_EQUAL( dist_data["independent unit"].toString(),
                       Utility::UnitTraits<MegaElectronVolt>::name(),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["dependent unit"].toString(),
                       Utility::UnitTraits<si::amount>::name(),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["coefficients"].toType<std::vector<double> >(),
                       std::vector<double>({0.0, 1.0, 0.0, 1.0}),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["lower bound"].toType<quantity<MegaElectronVolt> >(),
                       0.0*MeV,
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["upper bound"].toType<quantity<MegaElectronVolt> >(),
                       1.0*MeV,
                       SHOW_LHS );

  oss.str( "" );
  oss.clear();

  oss << Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount>( {0.0, 1.0, 0.0, 1.0}, 1.0*MeV, 2.0*MeV );

  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );

  FRENSIE_CHECK_EQUAL( dist_data["type"].toString(),
                       "Polynomial Distribution" );
  FRENSIE_CHECK_EQUAL( dist_data["independent unit"].toString(),
                       Utility::UnitTraits<MegaElectronVolt>::name(),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["dependent unit"].toString(),
                       Utility::UnitTraits<si::amount>::name(),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["coefficients"].toType<std::vector<double> >(),
                       std::vector<double>({0.0, 1.0, 0.0, 1.0}),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["lower bound"].toType<quantity<MegaElectronVolt> >(),
                       1.0*MeV,
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["upper bound"].toType<quantity<MegaElectronVolt> >(),
                       2.0*MeV,
                       SHOW_LHS );

  oss.str( "" );
  oss.clear();

  oss << *unit_aware_distribution;

  dist_data = Utility::fromString<Utility::VariantMap>( oss.str() );

  FRENSIE_CHECK_EQUAL( dist_data["type"].toString(),
                       "Polynomial Distribution" );
  FRENSIE_CHECK_EQUAL( dist_data["independent unit"].toString(),
                       Utility::UnitTraits<MegaElectronVolt>::name(),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["dependent unit"].toString(),
                       Utility::UnitTraits<si::amount>::name(),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["coefficients"].toType<std::vector<double> >(),
                       std::vector<double>({1.0, 2.0, 3.0, 0.0}),
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["lower bound"].toType<quantity<MegaElectronVolt> >(),
                       0.0*MeV,
                       SHOW_LHS );
  FRENSIE_CHECK_EQUAL( dist_data["upper bound"].toType<quantity<MegaElectronVolt> >(),
                       1.0*MeV,
                       SHOW_LHS );
}

//---------------------------------------------------------------------------//
// Check that a distribution can be archived
FRENSIE_UNIT_TEST_TEMPLATE_EXPAND( PolynomialDistribution,
                                   archive,
                                   TestArchives )
{
  FETCH_TEMPLATE_PARAM( 0, RawOArchive );
  FETCH_TEMPLATE_PARAM( 1, RawIArchive );

  typedef typename std::remove_pointer<RawOArchive>::type OArchive;
  typedef typename std::remove_pointer<RawIArchive>::type IArchive;

  std::string archive_base_name( "test_polynomial_dist" );
  std::ostringstream archive_ostream;

  // Create and archive some polynomial distributions
  {
    std::unique_ptr<OArchive> oarchive;

    createOArchive( archive_base_name, archive_ostream, oarchive );

    Utility::PolynomialDistribution dist_a( {3.0, 2.0, 1.0}, 1.0, 2.0 );

    FRENSIE_REQUIRE_NO_THROW(
                             (*oarchive) << BOOST_SERIALIZATION_NVP( dist_a ) );
    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << boost::serialization::make_nvp( "dist_b", distribution ) );
  }

  // Copy the archive ostream to an istream
  std::istringstream archive_istream( archive_ostream.str() );

  // Load the archived distributions
  std::unique_ptr<IArchive> iarchive;

  createIArchive( archive_istream, iarchive );

  Utility::PolynomialDistribution dist_a;

  FRENSIE_REQUIRE_NO_THROW(
                           (*iarchive) >> BOOST_SERIALIZATION_NVP(dist_a) );
  FRENSIE_CHECK_EQUAL( dist_a, Utility::PolynomialDistribution( {3.0, 2.0, 1.0}, 1.0, 2.0 ) );

  std::shared_ptr<Utility::UnivariateDistribution> dist_b;

  FRENSIE_REQUIRE_NO_THROW(
                           (*iarchive) >> BOOST_SERIALIZATION_NVP(dist_b) );
  FRENSIE_CHECK_EQUAL( *dynamic_cast<Utility::PolynomialDistribution*>(dist_b.get()),
                       *dynamic_cast<Utility::PolynomialDistribution*>(distribution.get()) );
}

//---------------------------------------------------------------------------//
// Check that a unit-aware distribution can be archived
FRENSIE_UNIT_TEST_TEMPLATE_EXPAND( UnitAwarePolynomialDistribution,
                                   archive,
                                   TestArchives )
{
  FETCH_TEMPLATE_PARAM( 0, RawOArchive );
  FETCH_TEMPLATE_PARAM( 1, RawIArchive );

  typedef typename std::remove_pointer<RawOArchive>::type OArchive;
  typedef typename std::remove_pointer<RawIArchive>::type IArchive;

  std::string archive_base_name( "test_unit_aware_polynomial_dist" );
  std::ostringstream archive_ostream;

  // Create and archive some polynomial distributions
  {
    std::unique_ptr<OArchive> oarchive;

    createOArchive( archive_base_name, archive_ostream, oarchive );

    Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount> dist_a( {3.0, 2.0, 1.0}, 1.0*MeV, 2.0*MeV );

    FRENSIE_REQUIRE_NO_THROW(
                             (*oarchive) << BOOST_SERIALIZATION_NVP( dist_a ) );
    FRENSIE_REQUIRE_NO_THROW( (*oarchive) << boost::serialization::make_nvp( "dist_b", unit_aware_distribution ) );
  }

  // Copy the archive ostream to an istream
  std::istringstream archive_istream( archive_ostream.str() );

  // Load the archived distributions
  std::unique_ptr<IArchive> iarchive;

  createIArchive( archive_istream, iarchive );

  Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount> dist_a;

  FRENSIE_REQUIRE_NO_THROW(
                           (*iarchive) >> BOOST_SERIALIZATION_NVP(dist_a) );
  FRENSIE_CHECK_EQUAL( dist_a, (Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount>( {3.0, 2.0, 1.0}, 1.0*MeV, 2.0*MeV )) );

  std::shared_ptr<Utility::UnitAwareUnivariateDistribution<MegaElectronVolt,si::amount> > dist_b;

  FRENSIE_REQUIRE_NO_THROW(
                           (*iarchive) >> BOOST_SERIALIZATION_NVP(dist_b) );
  FRENSIE_CHECK_EQUAL( (*dynamic_cast<Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount>*>(dist_b.get())),
                       (*dynamic_cast<Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount>*>(unit_aware_distribution.get())) );
}

//---------------------------------------------------------------------------//
// Check that a unit-aware distribution can be scaled
FRENSIE_UNIT_TEST_TEMPLATE_EXPAND( UnitAwarePolynomialDistribution,
				   explicit_conversion,
                                   TestUnitTypeQuads )
{
  FETCH_TEMPLATE_PARAM( 0, RawIndepUnitA );
  FETCH_TEMPLATE_PARAM( 1, RawDepUnitA );
  FETCH_TEMPLATE_PARAM( 2, RawIndepUnitB );
  FETCH_TEMPLATE_PARAM( 3, RawDepUnitB );

  typedef typename std::remove_pointer<RawIndepUnitA>::type IndepUnitA;
  typedef typename std::remove_pointer<RawDepUnitA>::type DepUnitA;
  typedef typename std::remove_pointer<RawIndepUnitB>::type IndepUnitB;
  typedef typename std::remove_pointer<RawDepUnitB>::type DepUnitB;

  typedef typename Utility::UnitTraits<IndepUnitA>::template GetQuantityType<double>::type IndepQuantityA;
  typedef typename Utility::UnitTraits<typename Utility::UnitTraits<IndepUnitA>::InverseUnit>::template GetQuantityType<double>::type InverseIndepQuantityA;

  typedef typename Utility::UnitTraits<IndepUnitB>::template GetQuantityType<double>::type IndepQuantityB;
  typedef typename Utility::UnitTraits<typename Utility::UnitTraits<IndepUnitB>::InverseUnit>::template GetQuantityType<double>::type InverseIndepQuantityB;

  typedef typename Utility::UnitTraits<DepUnitA>::template GetQuantityType<double>::type DepQuantityA;
  typedef typename Utility::UnitTraits<DepUnitB>::template GetQuantityType<double>::type DepQuantityB;

  // Copy from a unitless distribution to distribution type A (static method)
  Utility::UnitAwarePolynomialDistribution<IndepUnitA,DepUnitA>
    unit_aware_dist_a_copy = Utility::UnitAwarePolynomialDistribution<IndepUnitA,DepUnitA>::fromUnitlessDistribution( *dynamic_cast<Utility::PolynomialDistribution*>( distribution.get() ) );

  // Copy from distribution type A to distribution type B (explicit cast)
  Utility::UnitAwarePolynomialDistribution<IndepUnitB,DepUnitB>
    unit_aware_dist_b_copy( unit_aware_dist_a_copy );

  IndepQuantityA indep_quantity_a =
    Utility::QuantityTraits<IndepQuantityA>::initializeQuantity( 0.0 );
  InverseIndepQuantityA inv_indep_quantity_a =
    Utility::QuantityTraits<InverseIndepQuantityA>::initializeQuantity( 1/3. );
  DepQuantityA dep_quantity_a =
    Utility::QuantityTraits<DepQuantityA>::initializeQuantity( 1.0 );

  IndepQuantityB indep_quantity_b( indep_quantity_a );
  InverseIndepQuantityB inv_indep_quantity_b( inv_indep_quantity_a );
  DepQuantityB dep_quantity_b( dep_quantity_a );

  FRENSIE_CHECK_FLOATING_EQUALITY(
			   unit_aware_dist_a_copy.evaluate( indep_quantity_a ),
			   dep_quantity_a,
			   1e-15 );
  FRENSIE_CHECK_FLOATING_EQUALITY(
			unit_aware_dist_a_copy.evaluatePDF( indep_quantity_a ),
			inv_indep_quantity_a,
			1e-15 );
  FRENSIE_CHECK_FLOATING_EQUALITY(
			   unit_aware_dist_b_copy.evaluate( indep_quantity_b ),
			   dep_quantity_b,
			   1e-15 );
  FRENSIE_CHECK_FLOATING_EQUALITY(
			unit_aware_dist_b_copy.evaluatePDF( indep_quantity_b ),
			inv_indep_quantity_b,
			1e-15 );

  Utility::setQuantity( indep_quantity_a, 1.0 );
  Utility::setQuantity( inv_indep_quantity_a, 2.0 );
  Utility::setQuantity( dep_quantity_a, 6.0 );

  indep_quantity_b = IndepQuantityB( indep_quantity_a );
  inv_indep_quantity_b = InverseIndepQuantityB( inv_indep_quantity_a );
  dep_quantity_b = DepQuantityB( dep_quantity_a );

  FRENSIE_CHECK_FLOATING_EQUALITY(
			   unit_aware_dist_a_copy.evaluate( indep_quantity_a ),
			   dep_quantity_a,
			   1e-15 );
  FRENSIE_CHECK_FLOATING_EQUALITY(
			unit_aware_dist_a_copy.evaluatePDF( indep_quantity_a ),
			inv_indep_quantity_a,
			1e-15 );
  FRENSIE_CHECK_FLOATING_EQUALITY(
			   unit_aware_dist_b_copy.evaluate( indep_quantity_b ),
			   dep_quantity_b,
			   1e-15 );
  FRENSIE_CHECK_FLOATING_EQUALITY(
			unit_aware_dist_b_copy.evaluatePDF( indep_quantity_b ),
			inv_indep_quantity_b,
			1e-15 );
}

//---------------------------------------------------------------------------//
// Custom setup
//---------------------------------------------------------------------------//
FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN();

FRENSIE_CUSTOM_UNIT_TEST_INIT()
{
  // Initialize the polynomial distribution
  std::vector<double> coeffs( 4 );
  coeffs[0] = 1.0;
  coeffs[1] = 2.0;
  coeffs[2] = 3.0;
  coeffs[3] = 0.0;

  distribution.reset( new Utility::PolynomialDistribution( coeffs, 0.0, 1.0 ));

  // Initialize the unit-aware polynomial distribution
  unit_aware_distribution.reset(
     new Utility::UnitAwarePolynomialDistribution<MegaElectronVolt,si::amount>(
						  coeffs, 0.0*eV, 1e6*eV ) );

  // Initialize the random number generator
  Utility::RandomNumberGenerator::createStreams();
}

FRENSIE_CUSTOM_UNIT_TEST_SETUP_END();

//---------------------------------------------------------------------------//
// end tstPolynomialDistribution.cpp
//---------------------------------------------------------------------------//


text:
#include <boost/asio/ts/executor.hpp>
#include <boost/asio/thread_pool.hpp>
#include <iostream>
#include <string>

using boost::asio::bind_executor;
using boost::asio::dispatch;
using boost::asio::get_associated_executor;
using boost::asio::make_work_guard;
using boost::asio::post;
using boost::asio::thread_pool;

// A function to asynchronously read a single line from an input stream.
template <class Handler>
void async_getline(std::istream& is, Handler handler)
{
  // Create executor_work for the handler's associated executor.
  auto work = make_work_guard(handler);

  // Post a function object to do the work asynchronously.
  post([&is, work, handler=std::move(handler)]() mutable
      {
        std::string line;
        std::getline(is, line);

        // Pass the result to the handler, via the associated executor.
        dispatch(work.get_executor(),
            [line=std::move(line), handler=std::move(handler)]() mutable
            {
              handler(std::move(line));
            });
      });
}

// A function to asynchronously read multiple lines from an input stream.
template <class Handler>
void async_getlines(std::istream& is, std::string init, Handler handler)
{
  // Get the final handler's associated executor.
  auto ex = get_associated_executor(handler);

  // Use the associated executor for each operation in the composition.
  async_getline(is,
      bind_executor(ex,
        [&is, lines=std::move(init), handler=std::move(handler)]
        (std::string line) mutable
        {
          if (line.empty())
            handler(lines);
          else
            async_getlines(is, lines + line + "\n", std::move(handler));
        }));
}

int main()
{
  thread_pool pool;

  std::cout << "Enter text, terminating with a blank line:\n";

  async_getlines(std::cin, "",
      bind_executor(pool, [](std::string lines)
        {
          std::cout << "Lines:\n" << lines << "\n";
        }));

  pool.join();
}

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text: #include <boost/units/base_units/us/pound.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//  (C) Copyright Edward Diener 2011-2015
//  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/vmd/elem.hpp>
#include <boost/vmd/is_empty.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/preprocessor/list/at.hpp>
#include <boost/preprocessor/tuple/elem.hpp>

int main()
  {

#if BOOST_PP_VARIADICS

  #define BOOST_VMD_REGISTER_ggh (ggh)

  #define ANIDENTIFIER ggh
  #define ANUMBER 249
  #define ASEQ (25)(26)(27)
  #define ATUPLE (0,1,2,3,((a,b))((c,d))((e))((f,g,h)))
  #define ATUPLE2 (10,11,12,13)
  #define ATUPLE3 (100,101,102,103)
  #define ATUPLE5 (200,201,202,203)
  #define ALIST (0,(1,(2,(3,BOOST_PP_NIL))))
  #define ANARRAY (3,(a,b,38))
  #define ANARRAY2 (5,(c,d,133,22,15))
  #define ASEQUENCE ANUMBER ALIST ATUPLE ANIDENTIFIER ANARRAY ASEQ
  #define ASEQUENCE2 ANIDENTIFIER ANARRAY2 ALIST ASEQ ATUPLE2
  #define ASEQUENCE3 ASEQ ANIDENTIFIER ATUPLE3 ALIST
  #define ASEQUENCE4
  #define ASEQUENCE5 ALIST ASEQ ATUPLE5 ANIDENTIFIER

  BOOST_TEST(BOOST_VMD_IS_EMPTY(BOOST_PP_TUPLE_ELEM(0,BOOST_VMD_ELEM(0,ASEQUENCE,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))));
  BOOST_TEST(BOOST_VMD_IS_EMPTY(BOOST_PP_TUPLE_ELEM(1,BOOST_VMD_ELEM(0,ASEQUENCE2,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))));
  BOOST_TEST(BOOST_VMD_IS_EMPTY(BOOST_PP_TUPLE_ELEM(0,BOOST_VMD_ELEM(0,ASEQUENCE3,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))));

  BOOST_TEST(!BOOST_VMD_IS_EMPTY(BOOST_PP_TUPLE_ELEM(1,BOOST_VMD_ELEM(2,ASEQUENCE,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))));
  BOOST_TEST_EQ(BOOST_PP_TUPLE_ELEM(2,BOOST_PP_TUPLE_ELEM(0,BOOST_VMD_ELEM(2,ASEQUENCE,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))),2);
  BOOST_TEST_EQ(BOOST_PP_TUPLE_ELEM(3,BOOST_VMD_ELEM(2,ASEQUENCE,BOOST_VMD_TYPE_TUPLE)),3);

  BOOST_TEST(BOOST_VMD_IS_EMPTY(BOOST_PP_TUPLE_ELEM(1,BOOST_VMD_ELEM(4,ASEQUENCE2,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))));
  BOOST_TEST_EQ(BOOST_PP_TUPLE_ELEM(1,BOOST_VMD_ELEM(4,ASEQUENCE2,BOOST_VMD_TYPE_TUPLE)),11);

  BOOST_TEST_EQ(BOOST_PP_TUPLE_ELEM(2,BOOST_PP_TUPLE_ELEM(0,BOOST_VMD_ELEM(2,ASEQUENCE3,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))),102);
  BOOST_TEST(!BOOST_VMD_IS_EMPTY(BOOST_PP_TUPLE_ELEM(1,BOOST_VMD_ELEM(2,ASEQUENCE3,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))));
  BOOST_TEST_EQ(BOOST_PP_TUPLE_ELEM(0,BOOST_VMD_ELEM(2,ASEQUENCE3,BOOST_VMD_TYPE_TUPLE)),100);

  BOOST_TEST(BOOST_VMD_IS_EMPTY(BOOST_PP_TUPLE_ELEM(0,BOOST_VMD_ELEM(0,ASEQUENCE4,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))));
  BOOST_TEST(BOOST_VMD_IS_EMPTY(BOOST_PP_TUPLE_ELEM(1,BOOST_VMD_ELEM(0,ASEQUENCE4,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))));
  BOOST_TEST(BOOST_VMD_IS_EMPTY(BOOST_VMD_ELEM(0,ASEQUENCE4,BOOST_VMD_TYPE_TUPLE)));

  BOOST_TEST(!BOOST_VMD_IS_EMPTY(BOOST_PP_TUPLE_ELEM(1,BOOST_VMD_ELEM(2,ASEQUENCE5,BOOST_VMD_RETURN_AFTER,BOOST_VMD_TYPE_TUPLE))));
  BOOST_TEST_EQ(BOOST_PP_TUPLE_ELEM(2,BOOST_VMD_ELEM(2,ASEQUENCE5,BOOST_VMD_TYPE_TUPLE)),202);

  BOOST_TEST_EQ(BOOST_PP_TUPLE_ELEM(3,BOOST_VMD_ELEM(2,ASEQUENCE,BOOST_VMD_TYPE_TUPLE)),3);

#else

BOOST_ERROR("No variadic macro support");

#endif

  return boost::report_errors();

  }

ext: cxx


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
//
// Copyright (c) 2010-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is 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)
//
//
#ifndef QUICKBOOK_OUTPUT_HPP
#define QUICKBOOK_OUTPUT_HPP

#include <string>
#include <vector>

#include <boost/algorithm/string.hpp>

#include <doxygen_elements.hpp>
#include <parameter_predicates.hpp>

std::string qbk_escaped(std::string const& s)
{
    // Replace _ by unicode to avoid accidental quickbook underlining.
    // 1) do NOT do this in quickbook markup, so not within []
    // (e.g. to avoid [include get_point.qbk] having unicoded)
    // 2) \[ and \] should not count as []
    std::size_t const len = s.length();
    int counter = 0;
    std::string result = "";
    for (std::size_t i = 0; i < len; i++)
    {
        switch(s[i])
        {
            case '[' : counter++; break;
            case ']' : counter--; break;
            case '\\' :
                {
                    result += s[i];
                    if (i + 1 < len)
                    {
                        result += s[i + 1];
                    }
                    i++;
                    continue;
                }
            case '_' :
                if (counter == 0)
                {
                    result += "\\u005f";
                    continue;
                }
        }
        result += s[i];
    }

    return result;
}

void quickbook_template_parameter_list(std::vector<parameter> const& parameters, std::ostream& out, bool name = false)
{
    if (!parameters.empty())
    {
        out << "template<" ;
        bool first = true;
        BOOST_FOREACH(parameter const& p, parameters)
        {
            out << (first ? "" : ", ") << p.fulltype;
            first = false;
        }
        out << ">" << std::endl;
    }
}

void quickbook_synopsis(function const& f, std::ostream& out)
{
    out << "``";
    quickbook_template_parameter_list(f.template_parameters, out);
    switch(f.type)
    {
        case function_constructor :
            out << f.name;
            break;
        case function_member :
            out << f.return_type << " " << f.name;
            break;
        case function_free :
            out << f.definition;
            break;
        case function_define :
            out << "#define " << f.name;
            break;
        case function_unknown :
            // do nothing
            break;
    }

    // Output the parameters
    // Because we want to be able to skip, we cannot use the argstring
    {
        bool first = true;
        BOOST_FOREACH(parameter const& p, f.parameters)
        {
            if (! p.skip)
            {
                out
                    << (first ? "(" : ", ")
                    << p.fulltype << (p.fulltype.empty() ? "" : " ")
                    << p.name
                    << (p.default_value.empty() ? "" : " = ")
                    << p.default_value;
                first = false;
            }
        }
        if (! first)
        {
            out << ")";
        }
        else if (f.type != function_define)
        {
            out << "()";
        }
    }

    out << "``"
        << std::endl
        << std::endl;
}

void quickbook_synopsis(enumeration const& e, std::ostream& out)
{
    out << "``enum " << e.name;
    bool first = true;
    BOOST_FOREACH(enumeration_value const& value, e.enumeration_values)
    {
        out << (first ? " {" : ", ") << value.name;
        if (! value.initializer.empty())
        {
            out << " = " << boost::trim_copy(value.initializer);
        }
        first = false;
    }
    if (! first)
    {
        out << "};";
    }
    out << "``"
        << std::endl
        << std::endl;
}

inline bool includes(std::string const& filename, std::string const& header)
{
    std::string result;

    std::ifstream cpp_file(filename.c_str());
    if (cpp_file.is_open())
    {
        while (! cpp_file.eof() )
        {
            std::string line;
            std::getline(cpp_file, line);
            boost::trim(line);
            if (boost::starts_with(line, "#include")
                && boost::contains(line, header))
            {
                return true;
            }
        }
    }
    return false;
}

void quickbook_header(std::string const& location,
    configuration const& config,
    std::ostream& out)
{
    if (! location.empty())
    {
        std::vector<std::string> including_headers;

        // Select headerfiles containing to this location
        BOOST_FOREACH(std::string const& header, config.convenience_headers)
        {
            if (includes(config.convenience_header_path + header, location))
            {
                including_headers.push_back(header);
            }
        }

        out << "[heading Header]" << std::endl;
        if (! including_headers.empty())
        {
            out << "Either"
                << (including_headers.size() > 1 ? " one of" : "")
                << std::endl << std::endl;
            BOOST_FOREACH(std::string const& header, including_headers)
            {
                out << "`#include <" << config.start_include << header << ">`" << std::endl;
            }

            out << std::endl << "Or" << std::endl << std::endl;
        }
        out << "`#include <" << location << ">`" << std::endl;
        out << std::endl;
    }
}

void quickbook_markup(std::vector<markup> const& qbk_markup,
            markup_order_type order, markup_type type,
            std::ostream& out)
{
    bool has_output = false;
    BOOST_FOREACH(markup const& inc, qbk_markup)
    {
        if (inc.type == type && inc.order == order)
        {
            out << inc.value << std::endl;
            has_output = true;
        }
    }
    if (has_output)
    {
        out << std::endl;
    }
}

void quickbook_string_with_heading_if_present(std::string const& heading,
            std::string const& contents, std::ostream& out)
{
    if (! contents.empty())
    {
        out << "[heading " << heading << "]" << std::endl
            << qbk_escaped(contents) << std::endl
            << std::endl;
    }
}

inline std::string to_section_name(std::string const& name)
{
    // Make section-name lowercase and remove :: because these are filenames
    return boost::to_lower_copy(boost::replace_all_copy(name, "::", "_"));
}

void quickbook_short_output(function const& f, std::ostream& out)
{
    BOOST_FOREACH(parameter const& p, f.parameters)
    {
        if (! p.skip)
        {
            out << "[* " << p.fulltype << "]: ['" << p.name << "]:  " << p.brief_description << std::endl << std::endl;
        }
    }
    out << std::endl;
    out << std::endl;

    if (! f.return_description.empty())
    {
        out << "][" << std::endl;
        out << f.return_description << std::endl;
        out << std::endl;
    }

    out << std::endl;
}

inline std::string namespace_skipped(std::string const& name, configuration const& config)
{
    return config.skip_namespace.empty()
        ? name
        : boost::replace_all_copy(name, config.skip_namespace, "")
        ;
}

inline std::string output_if_different(std::string const& s, std::string const& s2)
{
    return boost::equals(s, s2)
        ? ""
        : s + " "
        ;
}

inline void quickbook_output_indexterm(std::string const& term, std::ostream& out
            //, std::string const& secondary = ""
            )
{
    out << "'''";
    if (boost::contains(term, "::"))
    {
        // "Unnamespace" it and add all terms (also namespaces)
        std::vector<std::string> splitted;
        std::string for_split = boost::replace_all_copy(term, "::", ":");
        boost::split(splitted, for_split, boost::is_any_of(":"), boost::token_compress_on);
        BOOST_FOREACH(std::string const& part, splitted)
        {
            out << "<indexterm><primary>" << part << "</primary></indexterm>";
        }
    }
    else
    {
        out << "<indexterm><primary>" << term;
        /*if (! secondary.empty())
        {
            out << "<secondary>" << secondary << "</secondary>";
        }*/
        out << "</primary></indexterm>";
    }
    out << "'''" << std::endl;
}

void quickbook_output(function const& f, configuration const& config, std::ostream& out)
{
    // Write the parsed function
    int arity = (int)f.parameters.size();

    std::string additional_description;

    if (! f.additional_description.empty())
    {
        additional_description = " (";
        additional_description += f.additional_description;
        additional_description += ")";
    }

    out << "[section:" << to_section_name(f.name);
    // Make section name unique if necessary by arity and additional description
    if (! f.unique)
    {
        out << "_" << arity;
        if (! f.additional_description.empty())
        {
            out << "_" << boost::to_lower_copy(boost::replace_all_copy(f.additional_description, " ", "_"));
        }
    }
    out << " " << f.name
        << additional_description
        << "]" << std::endl
        << std::endl;

    quickbook_output_indexterm(f.name, out);

    out << qbk_escaped(f.brief_description) << std::endl;
    out << std::endl;

    quickbook_string_with_heading_if_present("Description", f.detailed_description, out);

    // Synopsis
    quickbook_markup(f.qbk_markup, markup_before, markup_synopsis, out);
    out << "[heading Synopsis]" << std::endl;
    quickbook_synopsis(f, out);
    quickbook_markup(f.qbk_markup, markup_after, markup_synopsis, out);

    out << "[heading Parameters]" << std::endl
        << std::endl;

    out << "[table" << std::endl << "[";
    if (f.type != function_define)
    {
        out << "[Type] [Concept] ";
    }
    out << "[Name] [Description] ]" << std::endl;

    // First: output any template parameter which is NOT used in the normal parameter list
    BOOST_FOREACH(parameter const& tp, f.template_parameters)
    {
        if (! tp.skip)
        {
            std::vector<parameter>::const_iterator it = std::find_if(f.parameters.begin(), f.parameters.end(), par_by_type(tp.name));

            if (it == f.parameters.end())
            {
                out << "[[" << tp.name << "] [" << tp.brief_description << "] [ - ] [Must be specified]]" << std::endl;
            }
        }
    }

    BOOST_FOREACH(parameter const& p, f.parameters)
    {
        if (! p.skip)
        {
            out << "[";
            std::vector<parameter>::const_iterator it = std::find_if(f.template_parameters.begin(),
                f.template_parameters.end(), par_by_name(p.type));

            if (f.type != function_define)
            {
                out << "[" << p.fulltype
                    << "] [" << (it == f.template_parameters.end() ? "" : it->brief_description)
                    << "] ";
            }
            out << "[" << p.name
                << "] [" << p.brief_description
                << "]]"
                << std::endl;
        }
    }
    out << "]" << std::endl
        << std::endl
        << std::endl;

    quickbook_string_with_heading_if_present("Returns", f.return_description, out);

    quickbook_header(f.location, config, out);
    quickbook_markup(f.qbk_markup, markup_any, markup_default, out);

    out << std::endl;
    out << "[endsect]" << std::endl;
    out << std::endl;
}

void quickbook_output(enumeration const& e, configuration const& config, std::ostream& out)
{
    out << "[section:" << to_section_name(e.name);
    out << " " << e.name
        << "]" << std::endl
        << std::endl;

    quickbook_output_indexterm(e.name, out);
    BOOST_FOREACH(enumeration_value const& value, e.enumeration_values)
    {
        quickbook_output_indexterm(value.name, out);
    }

    out << e.brief_description << std::endl;
    out << std::endl;

    quickbook_string_with_heading_if_present("Description", e.detailed_description, out);

    // Synopsis
    quickbook_markup(e.qbk_markup, markup_before, markup_synopsis, out);
    out << "[heading Synopsis]" << std::endl;
    quickbook_synopsis(e, out);
    quickbook_markup(e.qbk_markup, markup_after, markup_synopsis, out);

    out << "[heading Values]" << std::endl
        << std::endl;

    out << "[table" << std::endl << "[";
    out << "[Value] [Description] ]" << std::endl;

    BOOST_FOREACH(enumeration_value const& value, e.enumeration_values)
    {
        out << "[[" << value.name
            << "] [" << value.brief_description
            << "]]"
            << std::endl;
    }
    out << "]" << std::endl
        << std::endl
        << std::endl;

    quickbook_header(e.location, config, out);
    quickbook_markup(e.qbk_markup, markup_any, markup_default, out);

    out << std::endl;
    out << "[endsect]" << std::endl;
    out << std::endl;
}

void quickbook_output_member(std::vector<function> const& functions,
        function_type type,
        std::string const& title,
        configuration const& config, std::ostream& out)
{
    std::string returns = type == function_constructor ? "" : " [Returns]";
    out << "[heading " << title << "(s)]" << std::endl
        << "[table" << std::endl
        << "[[Function] [Description] [Parameters] " << returns << "]" << std::endl;

    BOOST_FOREACH(function const& f, functions)
    {
        if (f.type == type)
        {
            out << "[[";
            quickbook_synopsis(f, out);
            out << "] [" << f.brief_description << "] [";
            quickbook_short_output(f, out);
            out << "]]" << std::endl;
        }
    }
    out << "]" << std::endl
        << std::endl;
}

void quickbook_output(class_or_struct const& cos, configuration const& config, std::ostream& out)
{
    // Skip namespace
    std::string short_name = namespace_skipped(cos.fullname, config);

    // Write the parsed function
    out << "[section:" << to_section_name(short_name) << " " << short_name << "]" << std::endl
        << std::endl;

    quickbook_output_indexterm(short_name, out);

    out << cos.brief_description << std::endl;
    out << std::endl;

    quickbook_string_with_heading_if_present("Description", cos.detailed_description, out);

    quickbook_markup(cos.qbk_markup, markup_before, markup_synopsis, out);
    out << "[heading Synopsis]" << std::endl
        << "``";
    quickbook_template_parameter_list(cos.template_parameters, out);
    out << (cos.is_class ? "class" : "struct")
        << " " << short_name << std::endl;

    if (! cos.base_classes.empty())
    {
        out << "      : ";
        bool first = true;
        BOOST_FOREACH(base_class const& bc, cos.base_classes)
        {
            if (! first)
            {
                out << std::endl << "      , ";
            }
            out << output_if_different(bc.derivation, "private")
                << output_if_different(bc.virtuality, "non-virtual")
                << namespace_skipped(bc.name, config);
            first = false;
        }
        out << std::endl;
    }

    out << "{" << std::endl
        << "  // ..." << std::endl
        << "};" << std::endl
        << "``" << std::endl << std::endl;
    quickbook_markup(cos.qbk_markup, markup_after, markup_synopsis, out);

    if (! cos.template_parameters.empty())
    {
        bool has_default = false;
        BOOST_FOREACH(parameter const& p, cos.template_parameters)
        {
            if (! p.default_value.empty())
            {
                has_default = true;
            }
        }

        out << "[heading Template parameter(s)]" << std::endl
            << "[table" << std::endl
            << "[[Parameter]";
        if (has_default)
        {
            out << " [Default]";
        }
        out << " [Description]]" << std::endl;

        BOOST_FOREACH(parameter const& p, cos.template_parameters)
        {
            out << "[[" << p.fulltype;
            if (has_default)
            {
                out << "] [" << p.default_value;
            }
            out << "] [" << p.brief_description << "]]" << std::endl;
        }
        out << "]" << std::endl
            << std::endl;
    }

    std::map<function_type, int> counts;
    BOOST_FOREACH(function const& f, cos.functions)
    {
        counts[f.type]++;
    }

    if (counts[function_constructor] > 0)
    {
        quickbook_output_member(cos.functions, function_constructor, "Constructor", config, out);
    }

    if (counts[function_member] > 0)
    {
        quickbook_output_member(cos.functions, function_member, "Member Function", config, out);
    }

    quickbook_header(cos.location, config, out);
    quickbook_markup(cos.qbk_markup, markup_any, markup_default, out);

    out << "[endsect]" << std::endl
        << std::endl;
}

#endif // QUICKBOOK_OUTPUT_HPP

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#ifndef PARMCB_SPVECGF2_HPP_
#define PARMCB_SPVECGF2_HPP_

//    Copyright (C) Dimitrios Michail 2019 - 2021.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          https://www.boost.org/LICENSE_1_0.txt)

#include <vector>
#include <set>
#include <iostream>
#include <cassert>

#include <boost/serialization/vector.hpp>

namespace parmcb {

    template<typename U>
    class SpVecGF2 {

    public:

        typedef typename std::vector<U>::size_type size_type;
        typedef typename std::vector<U>::const_iterator const_iterator;

        SpVecGF2() {
        }

        SpVecGF2(const U &i) {
            ones.push_back(i);
        }

        SpVecGF2(const SpVecGF2<U> &v) {
            ones = v.ones;
        }

        SpVecGF2(const SpVecGF2<U> &&v) {
            ones = std::move(v.ones);
        }

        SpVecGF2(const std::set<U> &v) {
            std::copy(v.begin(), v.end(), std::back_inserter(ones));
        }

        ~SpVecGF2(void) {
        }

        SpVecGF2<U>& operator=(const SpVecGF2<U> &v) {
            if (this == &v) {
                return *this;
            }
            ones = v.ones;
            return *this;
        }

        SpVecGF2<U>& operator=(const SpVecGF2<U> &&v) {
            if (this == &v) {
                return *this;
            }
            ones = std::move(v.ones);
            return *this;
        }

        int operator*(const SpVecGF2<U> &v) const {
            int res = 0;

            auto it = ones.begin(), it_e = ones.end();
            auto v_it = v.ones.begin(), v_it_e = v.ones.end();

            while (it != it_e && v_it != v_it_e) {
                U index = *it;
                U v_index = *v_it;
                if (index > v_index) {
                    v_it++;
                } else if (index < v_index) {
                    it++;
                } else {
                    res = (res + 1) % 2;
                    it++;
                    v_it++;
                }
            }
            return res;
        }

        int operator*(const std::set<U> &v) const {
            int res = 0;

            auto it = ones.begin(), it_e = ones.end();
            auto v_it = v.begin(), v_it_e = v.end();

            while (it != it_e && v_it != v_it_e) {
                U index = *it;
                U v_index = *v_it;
                if (index > v_index) {
                    v_it++;
                } else if (index < v_index) {
                    it++;
                } else {
                    res = (res + 1) % 2;
                    it++;
                    v_it++;
                }
            }
            return res;
        }

        SpVecGF2<U> operator+(const SpVecGF2<U> &v) const {
            SpVecGF2<U> res;
            auto it = ones.begin(), it_e = ones.end();
            auto v_it = v.ones.begin(), v_it_e = v.ones.end();

            // now add them
            while (it != it_e && v_it != v_it_e) {
                U index = *it;
                U v_index = *v_it;

                if (index > v_index) {
                    res.ones.push_back(v_index);
                    v_it++;
                } else if (index < v_index) {
                    res.ones.push_back(index);
                    it++;
                } else {
                    // 1 + 1 = 0, don't add anything
                    it++;
                    v_it++;
                }
            }

            // append remaining stuff
            while (it != it_e) {
                res.ones.push_back(*it);
                it++;
            }
            while (v_it != v_it_e) {
                res.ones.push_back(*v_it);
                v_it++;
            }

            return res;
        }

        SpVecGF2<U>& operator+=(const SpVecGF2<U> &v) {
            *this = *this + v;
            return *this;
        }

        void add(U pos) {
            assert(ones.empty() || pos >= *(ones.end()));

            ones.push_back(pos);
        }

        size_type size() const {
            return ones.size();
        }

        const_iterator begin() const
        {
            return ones.begin();
        }

        const_iterator end() const
        {
            return ones.end();
        }

        void clear() {
            ones.clear();
        }

    private:
        friend class boost::serialization::access;

        template<class Archive>
        void serialize(Archive & ar, const unsigned int version)
        {
          ar & ones;
        }

        std::vector<U> ones;
    };

    template<typename U>
    std::ostream& operator<<(std::ostream &o, const SpVecGF2<U> &v) {
        if (v.size() > 0)
            o << "(" << v.size() << ") ";
        std::copy(v.begin(), v.end(), std::ostream_iterator<U> { o, " " });
        return o;
    }

} // parmcb

#endif

max_stars_repo_name: d-michail/parmcb

max_issues_repo_name: d-michail/parmcb

max_forks_repo_name: d-michail/parmcb


text:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Copyright 2019 TeMoto Telerobotics
 *
 * 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 "temoto_action_assistant/widgets/parameter_group_edit_widget.h"
#include "temoto_action_engine/action_parameter.h"
#include <boost/algorithm/string.hpp>

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>

namespace temoto_action_assistant
{

// ******************************************************************************************
// Constructor
// ******************************************************************************************
ParameterGroupEditWidget::ParameterGroupEditWidget(QWidget *parent, std::shared_ptr<UmrfNode> umrf)
: QWidget(parent)
, umrf_(umrf)
{
  QFormLayout* parameter_form_layout = new QFormLayout();
  parameter_form_layout->setContentsMargins(0, 0, 0, 0);

  /*
   * Create the name editing field
   */
  parameter_group_name_field_ = new QLineEdit(this);
  parameter_group_name_field_->setMaximumWidth(400);
  parameter_form_layout->addRow("Name:", parameter_group_name_field_);

  connect(parameter_group_name_field_, &QLineEdit::textChanged, this, &ParameterGroupEditWidget::modifyName);

  this->setLayout(parameter_form_layout);
}

// ******************************************************************************************
//
// ******************************************************************************************
std::string ParameterGroupEditWidget::getGroupName(const std::string& group_name_full)
{
  std::vector<std::string> name_comp_vec;
  boost::split(name_comp_vec, group_name_full, boost::is_any_of("::"));
  return name_comp_vec.back();
}

// ******************************************************************************************
//
// ******************************************************************************************
void ParameterGroupEditWidget::modifyName()
{
  tree_data_ = tree_item_ptr_->data(0, Qt::UserRole).value<UmrfTreeData>();
  std::string parameter_group_name_full = boost::any_cast<std::string>(tree_data_.payload_);
  std::string parameter_group_name = getGroupName(parameter_group_name_full);
  std::string new_group_name = parameter_group_name_field_->text().toStdString();
  std::string new_group_name_full = parameter_group_name_full;

  if (new_group_name.empty() || new_group_name == parameter_group_name)
  {
    return;
  }

  ActionParameters* parameters;
  UmrfTreeData::ElementType type = tree_data_.type_;
  if (type == UmrfTreeData::PARAMETER_GROUP_IN)
  {
    parameters = &umrf_->getInputParametersNc();
  }
  else if (type == UmrfTreeData::PARAMETER_GROUP_OUT)
  {
    parameters = &umrf_->getOutputParametersNc();
  }
  else
  {
    return;
  }

  boost::replace_all(new_group_name_full, parameter_group_name, new_group_name);
  UmrfTreeData tree_item_group_pl = UmrfTreeData(type, new_group_name_full);
  tree_item_ptr_->setData(0, Qt::UserRole, QVariant::fromValue(tree_item_group_pl));

  for (auto& parameter : *parameters)
  {
    ActionParameters::ParameterContainer& param = const_cast<ActionParameters::ParameterContainer&>(parameter);
    std::string param_name_new = param.getName();
    boost::replace_all(param_name_new, parameter_group_name_full, new_group_name_full);
    param.setName(param_name_new);
  }

  QString text = QString::fromStdString(new_group_name);
  tree_item_ptr_->setText(0, text);
  //Q_EMIT refreshUmrfTree();
}

// ******************************************************************************************
//
// ******************************************************************************************
void ParameterGroupEditWidget::focusGiven(QTreeWidgetItem* tree_item_ptr)
{
  // Set the tree item pointer to active element
  tree_item_ptr_ = tree_item_ptr;
  tree_data_ = tree_item_ptr_->data(0, Qt::UserRole).value<UmrfTreeData>();
  std::string parameter_group_name_full = boost::any_cast<std::string>(tree_data_.payload_);

  // Get the name of the group wihout preceeding groups
  std::string parameter_group_name = getGroupName(parameter_group_name_full);

  // Update the name field
  parameter_group_name_field_->setText(QString::fromStdString(parameter_group_name));
}

// ******************************************************************************************
//
// ******************************************************************************************
void ParameterGroupEditWidget::setUmrf( std::shared_ptr<UmrfNode> umrf)
{
  umrf_ = umrf;
}

} // temoto_action_assistant namespace