Turi Create  4.0
dot_graph.hpp
1 /* Copyright © 2017 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5  */
6 #ifndef TURI_DOT_GRAPH_HPP
7 #define TURI_DOT_GRAPH_HPP
8 #include <string>
9 #include <vector>
10 #include <set>
11 #include <map>
12 #include <iostream>
13 namespace turi {
14 class dot_graph {
15  public:
16  dot_graph() { }
17 
18  /**
19  * Returns true if the vertex was succesfully added.
20  * False if the vertex already exists.
21  */
22  inline bool add_vertex(const std::string& vid, const std::string& vlabel="") {
23  if (m_vertices.count(vid)) return false;
24  m_vertices.insert(vid);
25  m_vertex_label[vid] = vlabel;
26  return true;
27  }
28 
29  inline void add_edge(const std::string& src, const std::string& dest) {
30  m_edges.push_back({src, dest});
31  }
32 
33  inline void print(std::ostream& out) {
34  out << "digraph G {\n";
35  for(auto vertex: m_vertices) {
36  out << "\t\"" << vertex << "\" ";
37  // output the label
38  out << "[label=\"" << m_vertex_label[vertex] << "\"]\n";
39  }
40  for(auto edge: m_edges) {
41  out << "\t\"" << edge.first << "\" -> \"" << edge.second << "\"\n";
42  }
43  out << "}";
44  }
45 
46 
47  private:
48  std::set<std::string> m_vertices;
49  std::vector<std::pair<std::string, std::string>> m_edges;
50  std::map<std::string, std::string> m_vertex_label;
51 };
52 
53 } // namespace turi;
54 #endif