Sparse - Incidence Matrix

The incidence matrix is a rectangular matrix which entries can vary depending on whether the graph is directed or undirected, and whether the incidence matrix is oriented or not. The sparse version applies the same logic used by the dense version.

As you can see in Mendz.Graphs, the dense and sparse matrices follow more or less the same coding patterns. This is intentional and by design.

IncidenceMatrix.cs
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

namespace Mendz.Graphs.Representations.Matrices.Sparse
{
    public class IncidenceMatrix : SparseGraphMatrixBase<int>
    {
        public bool Oriented { get; set; }

        public IncidenceMatrix(Graph graph)
            : base(graph, (graph.Order, graph.Size))
        {

        }

        public override ConcurrentDictionary<(int row, int column), int> Fill()
        {
            Initialize();
            var indexedVertices = Graph.IndexVertices();
            var indexedEdges = Graph.IndexEdges();
            Parallel.For(0, indexedEdges.Length, (z) =>
                {
                    Edge edge = indexedEdges[z];
                    SetEntries(Matrix,
                        Array.BinarySearch<Vertex>(indexedVertices, edge.Tail),
                        Array.BinarySearch<Vertex>(indexedVertices, edge.Head),
                        z, edge.Directed, Oriented);
                });
            return Matrix;
        }

        private static void SetEntries(
            ConcurrentDictionary<(int row, int column), int> matrix, 
            int x, int y, int z, bool directed, bool oriented)
        {
            if (x == y)
            {
                matrix.TryAdd((x, z), (directed ? 0 : (oriented ? 0 : 2)));
            }
            else
            {
                matrix.TryAdd((x, z), (directed ? -1 : (oriented ? -1 : 1)));
                matrix.TryAdd((y, z), 1);
            }
        }
    }
}

Give it a try and compare this code with Mendz.Graphs.Representations.Matrices.Dense.IncidenceMatrix. Interesting isn't it?

Comments