Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7760377
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T13:52:17+00:00 2026-06-01T13:52:17+00:00

I have a bipartite graph and I’m looking for the most efficient iterative way

  • 0

I have a bipartite graph and I’m looking for the most efficient iterative way to divide it into connected components. My recursive version has started overflowing the stack on large data sets. I’m willing to port from any language/pseudocode but for completeness I’ll be coding in C#.

My existing code is specialized for my data types. One partition is proteins, the other is spectra. Map and Set are C++ stdlib workalikes.

void recursivelyAssignProteinToCluster (long proteinId,
                                        long clusterId,
                                        Set<long> spectrumSet,
                                        Map<long, Set<long>> spectrumSetByProteinId,
                                        Map<long, Set<long>> proteinSetBySpectrumId,
                                        Map<long, long> clusterByProteinId)
{
    // try to assign the protein to the current cluster
    var insertResult = clusterByProteinId.Insert(proteinId, clusterId);
    if (!insertResult.WasInserted)
        return;

    // recursively add all "cousin" proteins to the current cluster
    foreach (long spectrumId in spectrumSet)
        foreach (var cousinProteinId in proteinSetBySpectrumId[spectrumId])
        {
            if (proteinId != cousinProteinId)
            {
                Set<long> cousinSpectrumSet = spectrumSetByProteinId[cousinProteinId];
                recursivelyAssignProteinToCluster(cousinProteinId,
                                                  clusterId,
                                                  cousinSpectrumSet,
                                                  spectrumSetByProteinId,
                                                  proteinSetBySpectrumId,
                                                  clusterByProteinId);
            }
        }
}

Map<long, long> calculateProteinClusters (NHibernate.ISession session)
{
    var spectrumSetByProteinId = new Map<long, Set<long>>();
    var proteinSetBySpectrumId = new Map<long, Set<long>>();

    var query = session.CreateQuery("SELECT pi.Protein.id, psm.Spectrum.id " + GetFilteredQueryString(FromProtein, ProteinToPeptideSpectrumMatch));

    foreach (var queryRow in query.List<object[]>())
    {
        long proteinId = (long) queryRow[0];
        long spectrumId = (long) queryRow[1];

        spectrumSetByProteinId[proteinId].Add(spectrumId);
        proteinSetBySpectrumId[spectrumId].Add(proteinId);
    }

    var clusterByProteinId = new Map<long, long>();
    int clusterId = 0;

    foreach (var pair in spectrumSetByProteinId)
    {
        long proteinId = pair.Key;

        // for each protein without a cluster assignment, make a new cluster
        if (!clusterByProteinId.Contains(proteinId))
        {
            ++clusterId;

            recursivelyAssignProteinToCluster(proteinId,
                                              clusterId,
                                              pair.Value,
                                              spectrumSetByProteinId,
                                              proteinSetBySpectrumId,
                                              clusterByProteinId);
        }
    }

    return clusterByProteinId;
}

As ShinTakezou suggested I refactored to put the stack on the heap and it works great. I used the DepthFirstSearch approach from digEmAll’s example.

var clusterByProteinId = new Map<long, long>();
int clusterId = 0;
var clusterStack = new Stack<KeyValuePair<long, Set<long>>>();

foreach (var pair in spectrumSetByProteinId)
{
    long proteinId = pair.Key;

    if (clusterByProteinId.Contains(proteinId))
        continue;

    // for each protein without a cluster assignment, make a new cluster
    ++clusterId;
    clusterStack.Push(new KeyValuePair<long, Set<long>>(proteinId, spectrumSetByProteinId[proteinId]));
    while (clusterStack.Count > 0)
    {
        var kvp = clusterStack.Pop();

        // try to assign the protein to the current cluster
        var insertResult = clusterByProteinId.Insert(kvp.Key, clusterId);
        if (!insertResult.WasInserted)
            continue;

        // add all "cousin" proteins to the current cluster
        foreach (long spectrumId in kvp.Value)
            foreach (var cousinProteinId in proteinSetBySpectrumId[spectrumId])
                if (!clusterByProteinId.Contains(cousinProteinId))
                    clusterStack.Push(new KeyValuePair<long, Set<long>>(cousinProteinId, spectrumSetByProteinId[cousinProteinId]));
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T13:52:18+00:00Added an answer on June 1, 2026 at 1:52 pm

    Here’s an example of an helper class that holds an undirected Graph and allows to get the connected components of it (iteratively):

    public class Graph<T>
    {
        public Dictionary<T, HashSet<T>> nodesNeighbors;
        public IEnumerable<T> Nodes
        {
            get { return nodesNeighbors.Keys; }
        }
        public Graph()
        {
            this.nodesNeighbors = new Dictionary<T, HashSet<T>>();
        }
        public void AddNode(T node)
        {
            this.nodesNeighbors.Add(node, new HashSet<T>());
        }
        public void AddNodes(IEnumerable<T> nodes)
        {
            foreach (var n in nodes)
                this.AddNode(n);
        }
        public void AddArc(T from, T to)
        {
            this.nodesNeighbors[from].Add(to);
            this.nodesNeighbors[to].Add(from);
        }
        public bool ContainsNode(T node)
        {
            return this.nodesNeighbors.ContainsKey(node);
        }
        public IEnumerable<T> GetNeighbors(T node)
        {
            return nodesNeighbors[node];
        }
        public IEnumerable<T> DepthFirstSearch(T nodeStart)
        {
            var stack = new Stack<T>();
            var visitedNodes = new HashSet<T>();
            stack.Push(nodeStart);
            while (stack.Count > 0)
            {
                var curr = stack.Pop();
                if (!visitedNodes.Contains(curr))
                {
                    visitedNodes.Add(curr);
                    yield return curr;
                    foreach (var next in this.GetNeighbors(curr))
                    {
                        if (!visitedNodes.Contains(next))
                            stack.Push(next);
                    }
                }
            }
        }
        public Graph<T> GetSubGraph(IEnumerable<T> nodes)
        {
            Graph<T> g = new Graph<T>();
            g.AddNodes(nodes);
            foreach (var n in g.Nodes.ToList())
            {
                foreach (var neigh in this.GetNeighbors(n))
                    g.AddArc(n, neigh);
            }
            return g;
        }
    
        public IEnumerable<Graph<T>> GetConnectedComponents()
        {
            var visitedNodes = new HashSet<T>();
            var components = new List<Graph<T>>();
    
            foreach (var node in this.Nodes)
            {
                if (!visitedNodes.Contains(node))
                {
                    var subGraph = GetSubGraph(this.DepthFirstSearch(node));
                    components.Add(subGraph);
                    visitedNodes.UnionWith(subGraph.Nodes);
                }
            }
            return components;
        }
    }
    

    Usage:

    static void Main(string[] args)
    {
        var g = new Graph<long>();
        g.AddNodes(new long[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
        g.AddArc(1, 2);
        g.AddArc(1, 3);
    
        g.AddArc(9, 6);
        g.AddArc(6, 7);
        g.AddArc(6, 8);
    
        g.AddArc(4, 5);
    
        var subGraphs = g.GetConnectedComponents();
    
    } 
    

    You could use the Graph<> class instead of your maps, or if you want to stick with your maps have a look at the code that is quite easy to understand (inside the class it is used a Dictionary<T,HashSet<T>> to hold nodes and arcs, so is very similar to your approach)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a bipartite graph. I am looking for a maximum (1,n) matching, which
I am new to graphs. I have two sets in a bipartite graph. I
Have you tried to use SharePoint with version control such as Perforce (or Subversion),
Have a rather abstract question for you all. I'm looking at getting involved in
I need to implement a 3 dimensional bipartite matching algorithm. I have this code
Lets say I have a graph G with its adjacency matrix A. I know
Consider the following question relative to graph theory : Let G a bipartite graph.
Have just started to get into CakePHP since a couple of weeks back. I
For a bipartite graph , you can substitute the adjacency matrix with what is
I have the following code which is an implementation of BPM (bipartite matching, from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.