typename graph_traits<VertexListGraph>::size_type
  sequential_vertex_color_ting(const VertexListGraph& G, OrderPA order, 
                             ColorMap color)
  {
    using graph_traits;
    using boost::tie;
    typedef graph_traits<VertexListGraph> GraphTraits;
    typedef typename GraphTraits::vertex_descriptor Vertex;
    typedef typename GraphTraits::size_type size_type;
    
    size_type max_color = 0;
    const size_type V = num_vertices(G);

    // We need to keep track of which colors are used by
    // adjacent vertices. We do this by marking the colors
    // that are used. The mark array contains the mark
    // for each color. The length of mark is the
    // number of vertices since the maximum possible number of colors
    // is the number of vertices.
    std::vector<size_type> mark(V, numeric_limits_max(max_color));
    
    //Initialize colors 
    typename GraphTraits::vertex_iterator v, vend;
    for (tie(v, vend) = vertices(G); v != vend; ++v)
      put(color, *v, V-1);
    
    //Determine the color for every vertex one by one
    for ( size_type i = 0; i < V; i++) {
      Vertex current = get(order,i);
      typename GraphTraits::adjacency_iterator v, vend;
      
      //Mark the colors of vertices adjacent to current.
      //i can be the value for marking since i increases successively
      for (tie(v,vend) = adjacent_vertices(current, G); v != vend; ++v)
        mark[get(color,*v)] = i; 
      
      //Next step is to assign the smallest un-marked color
      //to the current vertex.
      size_type j = 0;

      //Scan through all useable colors, find the smallest possible
      //color which is not used by neighbors.  Note that if mark[j]
      //is equal to i, color j is used by one of the current vertex's
      //neighbors.
      while ( j < max_color && mark[j] == i ) 
        ++j;
      
      if ( j == max_color )  //All colors are used up. Add one more color
        ++max_color;

      //At this point, j is the smallest possible color
      put(color, current, j);  //Save the color of vertex current
      
    }
    
    return max_color;
  }
Example #2
0
/** Return the most likely distance between two contigs and the number
 * of pairs that support that distance estimate.
 * @param len0 the length of the first contig in bp
 * @param len1 the length of the second contig in bp
 * @param rf whether the fragment library is oriented reverse-forward
 * @param[out] n the number of samples with a non-zero probability
 */
int maximumLikelihoodEstimate(unsigned l,
		int first, int last,
		const vector<int>& samples, const PMF& pmf,
		unsigned len0, unsigned len1, bool rf,
		unsigned& n)
{
	assert(first < last);
	assert(!samples.empty());

	// The aligner is unable to map reads to the ends of the sequence.
	// Correct for this lack of sensitivity by subtracting l-1 bp from
	// the length of each sequence, where the aligner requires a match
	// of at least l bp. When the fragment library is oriented
	// forward-reverse, subtract 2*(l-1) from each sample.
	assert(l > 0);
	assert(len0 >= l);
	assert(len1 >= l);
	len0 -= l - 1;
	len1 -= l - 1;

	if (len0 > len1)
		swap(len0, len1);

	if (rf) {
		// This library is oriented reverse-forward.
		Histogram h(samples.begin(), samples.end());
		int d;
		tie(d, n) = maximumLikelihoodEstimate(
				first, last, h,
				pmf, len0, len1);
		return d;
	} else {
		// This library is oriented forward-reverse.
		// Subtract 2*(l-1) from each sample.
		Histogram h;
		typedef vector<int> Samples;
		for (Samples::const_iterator it = samples.begin();
				it != samples.end(); ++it) {
			assert(*it > 2 * (int)(l - 1));
			h.insert(*it - 2 * (l - 1));
		}
		int d;
		tie(d, n) = maximumLikelihoodEstimate(
				first, last, h,
				pmf, len0, len1);
		return max(first, d - 2 * (int)(l - 1));
	}
}
Example #3
0
void UniversalUpdates::PerformUniversalUpdates( bool resources_already_loaded,
                                                const QList< Resource* > &resources,
                                                const QHash< QString, QString > &updates )
{
    QHash< QString, QString > html_updates;
    QHash< QString, QString > css_updates;
    QHash< QString, QString > xml_updates;
    tie( html_updates, css_updates, xml_updates ) = SeparateHtmlCssXmlUpdates( updates );

    QList< HTMLResource* > html_resources;
    QList< CSSResource* > css_resources;
    OPFResource *opf_resource = NULL;
    NCXResource *ncx_resource = NULL;

    int num_files = resources.count();

    for ( int i = 0; i < num_files; ++i )
    {
        Resource *resource = resources.at( i );

        if ( resource->Type() == Resource::HTMLResourceType )

            html_resources.append( qobject_cast< HTMLResource* >( resource ) );

        else if ( resource->Type() == Resource::CSSResourceType )

            css_resources.append( qobject_cast< CSSResource* >( resource ) );

        else if ( resource->Type() == Resource::OPFResourceType )
        
            opf_resource = qobject_cast< OPFResource* >( resource );
        
        else if ( resource->Type() == Resource::NCXResourceType )
        
            ncx_resource = qobject_cast< NCXResource* >( resource );      
    }

    QFutureSynchronizer<void> sync;

    if ( resources_already_loaded )
    {
        sync.addFuture( QtConcurrent::map( html_resources, boost::bind( UpdateOneHTMLFile, _1, html_updates, css_updates ) ) );
        sync.addFuture( QtConcurrent::map( css_resources,  boost::bind( UpdateOneCSSFile,  _1, css_updates ) ) );
    }

    else
    {
        sync.addFuture( QtConcurrent::map( html_resources, boost::bind( LoadAndUpdateOneHTMLFile, _1, html_updates, css_updates ) ) );
        sync.addFuture( QtConcurrent::map( css_resources,  boost::bind( LoadAndUpdateOneCSSFile,  _1, css_updates ) ) );
    }

    // We can't schedule these with QtConcurrent because they
    // will (indirectly) call QTextDocument::setPlainText, and if
    // a tab is open for the ncx/opf, then an event needs to be sent
    // to the tab widget. Events can't cross threads, and we crash.
    UpdateNCXFile( ncx_resource, xml_updates );
    UpdateOPFFile( opf_resource, xml_updates );

    sync.waitForFinished();
}
tuple<int, int, bool> feed_bytes(http_parser& parser, char const* str)
{
	tuple<int, int, bool> ret(0, 0, false);
	tuple<int, int, bool> prev(0, 0, false);
	for (int chunks = 1; chunks < 70; ++chunks)
	{
		ret = make_tuple(0, 0, false);
		parser.reset();
		buffer::const_interval recv_buf(str, str);
		for (; *str;)
		{
			int chunk_size = (std::min)(chunks, int(strlen(recv_buf.end)));
			if (chunk_size == 0) break;
			recv_buf.end += chunk_size;
			int payload, protocol;
			bool error = false;
			tie(payload, protocol) = parser.incoming(recv_buf, error);
			ret.get<0>() += payload;
			ret.get<1>() += protocol;
			ret.get<2>() |= error;
//			std::cerr << payload << ", " << protocol << ", " << chunk_size << std::endl;
			TORRENT_ASSERT(payload + protocol == chunk_size || ret.get<2>());
		}
		TEST_CHECK(prev == make_tuple(0, 0, false) || ret == prev || ret.get<2>());
		if (!ret.get<2>())
		{
			TEST_EQUAL(ret.get<0>() + ret.get<1>(), strlen(str));
		}

		prev = ret;
	}
	return ret;
}
Example #5
0
void CellGraph::evolve()
{
    CellIterator vi, vi_end;
    graph_t::adjacency_iterator ni, ni_end;
    
    unsigned long arg = 0;
    for (tie(vi,vi_end) = vertices(m_graph); vi != vi_end; ++vi)
    {
        int i = 0;
        for (tie(ni, ni_end) = adjacent_vertices(*vi, m_graph); ni != ni_end; ++ni)
        {
            arg |= m_graph[*ni].cellValue;
            arg <<= 1;
            ++i;
        }
        m_graph[*vi].cellValue = arg % 2;
    }
}
Example #6
0
GraphState CellGraph::getCurrentState() const
{
    CellIterator vi, viend;
    GraphState state(getVertexCount());
    
    int i = 0;
    for (tie(vi,viend) = vertices(m_graph); vi != viend; ++vi)
        state[i++] = m_graph[*vi].cellValue;
    return state;
}
Example #7
0
/** Return the most likely distance between two contigs and the number
 * of pairs that support that estimate. */
static pair<int, unsigned>
maximumLikelihoodEstimate(int first, int last,
		const Histogram& samples,
		const PMF& pmf,
		unsigned len0, unsigned len1)
{
	int filterSize = 2 * (int)(0.05 * pmf.mean()) + 3; // want an odd filter size
	first = max(first, (int)pmf.minValue() - samples.maximum()) - filterSize/2;
	last = min(last, (int)pmf.maxValue() - samples.minimum()) + filterSize/2 + 1;

	/* When randomly selecting fragments that span a given point,
	 * longer fragments are more likely to be selected than
	 * shorter fragments.
	 */
	WindowFunction window(len0, len1);

	unsigned nsamples = samples.size();
	double bestLikelihood = -numeric_limits<double>::max();
	int bestTheta = first;
	unsigned bestn = 0;
	vector<double> le;
	vector<unsigned> le_n;
	vector<int> le_theta;
	for (int theta = first; theta <= last; theta++) {
		// Calculate the normalizing constant of the PMF, f_theta(x).
		double c = 0;
		for (int i = pmf.minValue(); i <= (int)pmf.maxValue(); ++i)
			c += pmf[i] * window(i - theta);

		double likelihood;
		unsigned n;
	   	tie(likelihood, n) = computeLikelihood(theta, samples, pmf);
		likelihood -= nsamples * log(c);
		le.push_back(likelihood);
		le_n.push_back(n);
		le_theta.push_back(theta);
	}

	HannWindow filter(filterSize);
	for (int i = filterSize / 2; i < (int)le.size()-(filterSize / 2); i++) {
		double likelihood = 0;
		for (int j = -filterSize / 2; j <= filterSize / 2; j++) {
			assert((unsigned)(i + j) < le.size() && i + j >= 0);
			likelihood += filter(j) * le[i + j];
		}

		if (le_n[i] > 0 && likelihood > bestLikelihood) {
			bestLikelihood = likelihood;
			bestTheta = le_theta[i];
			bestn = le_n[i];
		}
	}
	return make_pair(bestTheta, bestn);
}
Example #8
0
QString GuideSemantics::GetGuideName(GuideSemantics::GuideSemanticType type)
{
    if (m_GuideTypeMapping.contains(type)) {
        QString abbrev;
        QString name;
        tie(abbrev, name) = m_GuideTypeMapping[type];
        return name;
    }

    return "";
}
Example #9
0
	void file_pool::release(void* st)
	{
		boost::mutex::scoped_lock l(m_mutex);
		assert(st != 0);
		using boost::tie;

		typedef nth_index<file_set, 2>::type key_view;
		key_view& kt = get<2>(m_files);

		key_view::iterator start, end;
		tie(start, end) = kt.equal_range(st);
		kt.erase(start, end);
	}
Example #10
0
static float getAlignmentIdentity(const Graph& g,
		vertex_descriptor t, vertex_descriptor v,
		It first, It last)
{
	unsigned nbranches = distance(first, last);
	vector<int> inDists(nbranches);
	transform(first, last, inDists.begin(),
			bind(getDistance, boost::cref(g), t, _1));
	vector<int> outDists(nbranches);
	transform(first, last, outDists.begin(),
			bind(getDistance, boost::cref(g), _1, v));
	vector<int> insertLens(nbranches);
	transform(first, last, insertLens.begin(),
			bind(getDistance, boost::cref(g), t, _1)
				+ bind(getLength, &g, _1)
				+ bind(getDistance, boost::cref(g), _1, v));

	int max_in_overlap = -(*min_element(inDists.begin(),
			inDists.end()));
	assert(max_in_overlap >= 0);
	int max_out_overlap = -(*min_element(outDists.begin(),
			outDists.end()));
	assert(max_out_overlap >= 0);
	int min_insert_len = *min_element(insertLens.begin(),
			insertLens.end());
	int max_insert_len = *max_element(insertLens.begin(),
			insertLens.end());

	float max_identity =
		(float)(min_insert_len + max_in_overlap + max_out_overlap) /
		(max_insert_len + max_in_overlap + max_out_overlap);
	if (min_insert_len <= 0 || max_identity < opt::identity)
		return max_identity;

	vector<string> seqs(nbranches);
	transform(first, last, seqs.begin(), bind(getSequence, &g, _1));
	for (unsigned i = 0; i < seqs.size(); i++) {
		// Remove the overlapping sequence.
		int n = seqs[i].size();
		int l = -inDists[i], r = -outDists[i];
		assert(n > l + r);
		seqs[i] = seqs[i].substr(l, n - l - r);
	}

	unsigned matches, consensusSize;
	tie(matches, consensusSize) = align(seqs);
	return (float)(matches + max_in_overlap + max_out_overlap) /
		(consensusSize + max_in_overlap + max_out_overlap);
}
Example #11
0
// Cleans CSS; currently it removes the redundant CSS classes
// that Tidy sometimes adds because it doesn't parse existing
// CSS classes, it only adds new ones; this also merges smaller
// style tags into larger ones
QString CleanSource::CleanCSS(const QString &source, int old_num_styles)
{
    QString newsource           = source;
    QStringList css_style_tags  = CSSStyleTags(newsource);

    // If Tidy added a new tag, we remove the redundant ones
    if (css_style_tags.count() > old_num_styles) {
        tie(newsource, css_style_tags) = RemoveRedundantClasses(newsource, css_style_tags);
    }

    css_style_tags = RemoveEmptyComments(css_style_tags);
    css_style_tags = MergeSmallerStyles(css_style_tags);
    newsource = WriteNewCSSStyleTags(newsource, css_style_tags);
    return newsource;
}
/*!
Generate the __init__ function.
Generate Constuctor which creates the parameters as member variables
 */
void siml::PyProcessGenerator::genConstructor()
{
    m_PyFile << format("%|4t|def __init__(self):") << '\n';

    //call base class' constructor
    m_PyFile << format("%|8t|#call base class' constructor.\n");
    m_PyFile << format("%|8t|SimulatorBase.__init__(self)\n\n");

    //Map for converting variable names to indices or slices
    //necessary for convenient access to the simulation results from Python.
    //used by Python functions: get(...), graph(...)
    //loop produces: self._resultArrayMap = { 'reactor.S':1, 'reactor.X':0, 'reactor.mu':2,  }
    m_PyFile << format("%|8t|#Map for converting variable names to indices or slices.\n");
    m_PyFile << format("%|8t|self._resultArrayMap = {");
    map<CmPath, string>::const_iterator itMa;
    for( itMa = m_ResultArrayMap.begin(); itMa != m_ResultArrayMap.end(); ++itMa )
    {
        CmPath path;
        string simlName, index;
        tie(path, index) = *itMa;
        simlName = path.toString(); //the Python access function uses the Siml name
        m_PyFile << format(" '%1%':%2%,") % simlName % index; ///@todo the algo writes one comma too much (after the last element)
    }
    m_PyFile << " }\n\n";

    //Set the solution parameters
    m_PyFile << format("%|8t|#Set the solution parameters.\n");
    m_PyFile << format("%|8t|self.reportingInterval = float(%1%)\n") % m_FlatProcess.solutionParameters.reportingInterval;
    m_PyFile << format("%|8t|self.simulationTime    = float(%1%)\n\n") % m_FlatProcess.solutionParameters.simulationTime;

    //Compute parameter values
    m_PyFile << format("%|8t|#Compute parameter values.\n");
    m_PyFile << format("%|8t|self.setParameters()\n\n");

//     //Compute the initial values
//     m_PyFile << format("%|8t|#Compute the initial values.\n");
//     m_PyFile << format("%|8t|self.setInitialValues()\n");

    //Easy access to number of state variables and total number of variables
    m_PyFile << format("%|8t|#Number of state variables and total number of variables.\n");
    m_PyFile << format("%|8t|self._numStates    = %1%\n") % m_StateVectorSize;
    m_PyFile << format("%|8t|self._numVariables = %1%\n") % m_ResultArrayColls;

    m_PyFile << '\n';

    ///@todo initialize _resultArray with the right dimensions. Now get() dfails prior to a simulation run.
}
Example #13
0
CellGraph::CellGraph(size_t vertexCount):
//    m_graph(new graph_t(vertexCount)),
    m_graph(vertexCount),
    key(0x1234567890),
    constant(vertexCount - (blockSize/2 + keySize/2), 0x42123345643ul)
{
    // TODO: add correct method to fill the cells
    CellIterator vi, viend;

    for (tie(vi,viend) = vertices(m_graph); vi != viend; ++vi)
        m_graph[*vi].cellValue = 0;//rand()%2;
        
    cout << "key: " << key << endl;
    cout << "round constant: "<< constant << endl;
    
    offset = 0;
}
Example #14
0
int main()
{
    tuple<int, double> a, b, c;
    a = tuple<int, double>();
    b = tuple<int, double>(1);
    c = tuple<int, double>(1, 3.14);
    a = make_tuple(1, 2.57);

    int i;
    double d;
    tie(i, d) = a;
    i = a.get<0>();
    d = a.get<1>();

    std::cout << "version=" << BOOST_VERSION/100000 << "."
              << ((BOOST_VERSION / 100) % 100) << "."
              << BOOST_VERSION % 100 << std::endl;

    return 0;
}
Example #15
0
/** Return the length of the longest path through the bubble. */
static int longestPath(const Graph& g, const Bubble& topo)
{
	typedef graph_traits<Graph>::edge_descriptor E;
	typedef graph_traits<Graph>::out_edge_iterator Eit;
	typedef graph_traits<Graph>::vertex_descriptor V;

	EdgeWeightMap<Graph> weight(g);
	map<ContigNode, int> distance;
	distance[topo.front()] = 0;
	for (Bubble::const_iterator it = topo.begin();
			it != topo.end(); ++it) {
		V u = *it;
		Eit eit, elast;
		for (tie(eit, elast) = out_edges(u, g); eit != elast; ++eit) {
			E e = *eit;
			V v = target(e, g);
			distance[v] = max(distance[v], distance[u] + weight[e]);
		}
	}
	V v = topo.back();
	return distance[v] - g[v].length;
}
/** Find an equivalent region of the two specified paths.
 * @param[out] orientation the orientation of the alignment
 * @return the consensus sequence
 */
static ContigPath align(const Lengths& lengths,
		const ContigPath& path1, const ContigPath& path2,
		ContigNode pivot, dir_type& orientation)
{
	if (&path1 == &path2) {
		// Ignore the trivial alignment when aligning a path to
		// itself.
	} else if (path1 == path2) {
		// These two paths are identical.
		orientation = DIR_B;
		return path1;
	} else {
		ContigPath::const_iterator it
			= search(path1.begin(), path1.end(),
				path2.begin(), path2.end());
		if (it != path1.end()) {
			// path2 is subsumed in path1.
			// Determine the orientation of the edge.
			orientation
				= it == path1.begin() ? DIR_R
				: it + path2.size() == path1.end() ? DIR_F
				: DIR_B;
			return path1;
		}
	}

	// Find a suitable pivot.
	if (find(path1.begin(), path1.end(), pivot) == path1.end()
			|| find(path2.begin(), path2.end(), pivot)
				== path2.end()) {
		bool good;
		tie(pivot, good) = findPivot(path1, path2);
		if (!good)
			return ContigPath();
	}
	assert(find(path1.begin(), path1.end(), pivot) != path1.end());

	ContigPath::const_iterator it2 = find(path2.begin(), path2.end(),
			pivot);
	assert(it2 != path2.end());
	if (&path1 != &path2) {
		// The seed must be unique in path2, unless we're aligning a
		// path to itself.
		assert(count(it2+1, path2.end(), pivot) == 0);
	}

	ContigPath consensus;
	for (ContigPath::const_iterator it1 = find_if(
				path1.begin(), path1.end(),
				bind2nd(equal_to<ContigNode>(), pivot));
			it1 != path1.end();
			it1 = find_if(it1+1, path1.end(),
				bind2nd(equal_to<ContigNode>(), pivot))) {
		if (&*it1 == &*it2) {
			// We are aligning a path to itself, and this is the
			// trivial alignment, which we'll ignore.
			continue;
		}
		consensus = align(lengths,
				path1, path2, it1, it2, orientation);
		if (!consensus.empty())
			return consensus;
	}
	return consensus;
}