CXXGraph icon indicating copy to clipboard operation
CXXGraph copied to clipboard

Inclusion of "sink nodes" in adjacency map

Open sbaldu opened this issue 1 year ago • 1 comments

This issue is related to the discussion in issue #367. When we build the adjacency matrix for a directed graph we only add an element for the source node.

template <typename T>
shared<AdjacencyMatrix<T>> Graph<T>::getAdjMatrix() const {
  auto adj = std::make_shared<AdjacencyMatrix<T>>();
  auto addElementToAdjMatrix = [&adj](shared<const Node<T>> nodeFrom,
                                      shared<const Node<T>> nodeTo,
                                      shared<const Edge<T>> edge) {
    std::pair<shared<const Node<T>>, shared<const Edge<T>>> elem = {nodeTo,
                                                                    edge};
    (*adj)[nodeFrom].push_back(std::move(elem));
  };
  for (const auto &edgeSetIt : edgeSet) {
    if (edgeSetIt->isDirected().has_value() &&
        edgeSetIt->isDirected().value()) {
      shared<const DirectedEdge<T>> d_edge =
          std::static_pointer_cast<const DirectedEdge<T>>(edgeSetIt);
      addElementToAdjMatrix(d_edge->getNodePair().first,
                            d_edge->getNodePair().second, d_edge);
    } else if (edgeSetIt->isDirected().has_value() &&
               !edgeSetIt->isDirected().value()) {
      shared<const UndirectedEdge<T>> ud_edge =
          std::static_pointer_cast<const UndirectedEdge<T>>(edgeSetIt);
      ;
      addElementToAdjMatrix(ud_edge->getNodePair().first,
                            ud_edge->getNodePair().second, ud_edge);
      addElementToAdjMatrix(ud_edge->getNodePair().second,
                            ud_edge->getNodePair().first, ud_edge);
    } else {  // is a simple edge we cannot create adj matrix
      return adj;
    }
  }
  return adj;
}

This means that nodes that are only destination and never source of any edge are difficult to find using the adjacency matrix, because they are not in the set of keys. We could maybe add empty vectors for destination nodes of directed edges, using something like try_emplace to avoid re-assignments. This would cause a small overhead when building the adjacency matrix, but would make populating the nodeSet as in issue #367 quicker and easier.

Wdyt @nrkramer @ZigRazor ?

sbaldu avatar Dec 05 '23 10:12 sbaldu

This could be a good enhancement for me

ZigRazor avatar Jan 08 '24 07:01 ZigRazor