Class: Tangle::Graph

Inherits:
Object
  • Object
show all
Includes:
GraphEdges, GraphVertices, Mixin::Initialize
Defined in:
lib/tangle/graph.rb

Overview

Base class for all kinds of graphs

Direct Known Subclasses

Directed::Graph, Simple::Graph

Constant Summary collapse

Edge =
Tangle::Edge
DEFAULT_MIXINS =
Tangle::Mixin::Connectedness::MIXINS

Instance Attribute Summary

Attributes included from Mixin::Initialize

#mixins

Class Method Summary collapse

Instance Method Summary collapse

Methods included from GraphEdges

#add_edge, #edges, #remove_edge

Methods included from GraphVertices

#[], #add_vertex, #fetch, #remove_vertex, #select, #vertices

Constructor Details

#initialize(mixins: self.class::DEFAULT_MIXINS, **kwargs) ⇒ Graph

Initialize a new graph, optionally preloading it with vertices and edges

Graph.new() => Graph Graph.new(mixins: [MixinModule, …], …) => Graph

mixins is an array of modules that can be mixed into the various classes that makes up a graph. Initialization of a Graph, Vertex or Edge looks for submodules in each mixin, with the same name and extends any created object. Defaults to [Tangle::Mixin::Connectedness].

Any subclass of Graph should also subclass Edge to manage its unique constraints.



52
53
54
55
56
# File 'lib/tangle/graph.rb', line 52

def initialize(mixins: self.class::DEFAULT_MIXINS, **kwargs)
  initialize_vertices
  initialize_edges
  initialize_mixins(mixins: mixins, **kwargs)
end

Class Method Details

.[](vertices, edges = {}, **kwargs) ⇒ Object

Initialize a new graph, preloading it with vertices and edges

Graph[vertices] => Graph Graph[vertices, edges) => Graph

When vertices is a hash, it contains initialization kwargs as values and vertex names as keys. When vertices is an array of initialization kwargs, the vertices will be be anonymous.

edges can contain an array of exactly two, either names of vertices or vertices.

Any kwarg supported by Graph.new is also allowed.



32
33
34
35
36
37
# File 'lib/tangle/graph.rb', line 32

def self.[](vertices, edges = {}, **kwargs)
  graph = new(**kwargs)
  vertices.each { |vertex| graph.add_vertex(vertex) }
  edges.each { |from, to| graph.add_edge(from, to) }
  graph
end

Instance Method Details

#subgraph(included = nil, &selector) ⇒ Object

Return a subgraph, optionally filtered by a vertex selector block

subgraph => Graph subgraph { |vertex| … } => Graph

Unless a selector is provided, the subgraph contains the entire graph.



65
66
67
68
69
70
# File 'lib/tangle/graph.rb', line 65

def subgraph(included = nil, &selector)
  result = clone
  result.select_vertices!(included) unless included.nil?
  result.select_vertices!(&selector) if block_given?
  result
end

#to_sObject Also known as: inspect



72
73
74
# File 'lib/tangle/graph.rb', line 72

def to_s
  "#<#{self.class}: #{vertices.count} vertices, #{edges.count} edges>"
end