class GraphMatching::Visualize

Renders `GraphMatching::Graph` objects using `graphviz`.

Constants

TMP_DIR
USR_BIN_ENV

Attributes

graph[R]

Public Class Methods

new(graph) click to toggle source
# File lib/graph_matching/visualize.rb, line 14
def initialize(graph)
  @graph = graph
end

Public Instance Methods

dot() click to toggle source

`dot` returns a string representing the graph, in .dot format. www.graphviz.org/content/dot-language

# File lib/graph_matching/visualize.rb, line 20
def dot
  RGL::DOT::Graph.new('elements' => dot_edges).to_s
end
png(base_filename) click to toggle source

`png` writes a “.png” file with graphviz and opens it

# File lib/graph_matching/visualize.rb, line 25
def png(base_filename)
  check_that_dot_is_installed
  mk_tmp_dir
  abs_path = "#{TMP_DIR}/#{base_filename}.png"
  write_png(abs_path)
  system "open #{abs_path}"
end

Private Instance Methods

assert_usr_bin_env_exists() click to toggle source
# File lib/graph_matching/visualize.rb, line 57
def assert_usr_bin_env_exists
  return if File.exist?(USR_BIN_ENV)
  warn "File not found: #{USR_BIN_ENV}"
  exit(1)
end
check_that_dot_is_installed() click to toggle source
# File lib/graph_matching/visualize.rb, line 35
def check_that_dot_is_installed
  return if dot_installed?
  warn 'Executable not found: dot'
  warn 'Please install graphviz'
  exit(1)
end
dot_edge(u, v, label) click to toggle source
# File lib/graph_matching/visualize.rb, line 42
def dot_edge(u, v, label)
  RGL::DOT::Edge.new(
    { 'from' => u, 'to' => v, 'label' => label },
    ['label']
  )
end
dot_edge_label(edge) click to toggle source
# File lib/graph_matching/visualize.rb, line 53
def dot_edge_label(edge)
  graph.is_a?(GraphMatching::Graph::Weighted) ? graph.w([*edge]) : nil
end
dot_edges() click to toggle source
# File lib/graph_matching/visualize.rb, line 49
def dot_edges
  graph.edges.map { |e| dot_edge(e.source, e.target, dot_edge_label(e)) }
end
dot_installed?() click to toggle source

`dot_installed?` returns true if `dot` is installed, otherwise false. Note that `system` returns true if the command gives zero exit status, false for non-zero exit status.

# File lib/graph_matching/visualize.rb, line 66
def dot_installed?
  assert_usr_bin_env_exists
  system "#{USR_BIN_ENV} which dot > /dev/null"
end
mk_tmp_dir() click to toggle source
# File lib/graph_matching/visualize.rb, line 71
def mk_tmp_dir
  Dir.mkdir(TMP_DIR) unless Dir.exist?(TMP_DIR)
end
safe_vertex(v) click to toggle source
# File lib/graph_matching/visualize.rb, line 75
def safe_vertex(v)
  if v.is_a?(Integer)
    v
  elsif v.respond_to?(:to_dot)
    v.to_dot
  else
    v.to_s.gsub(/[^a-zA-Z0-9]/, '')
  end
end
write_png(abs_path) click to toggle source
# File lib/graph_matching/visualize.rb, line 85
def write_png(abs_path)
  _so, se, st = Open3.capture3("dot -T png > #{abs_path}", stdin_data: dot)
  return if st.success?
  warn 'Failed to generate .png'
  warn se
  exit(1)
end