Class: MOSAIK::Graph::Reducer

Inherits:
Object
  • Object
show all
Defined in:
lib/mosaik/graph/reducer.rb

Overview

Reduce the graph (aggregate common edges and normalize weights)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options, graph) ⇒ Reducer

Returns a new instance of Reducer.



13
14
15
16
# File 'lib/mosaik/graph/reducer.rb', line 13

def initialize(options, graph)
  @options = options
  @graph = graph
end

Instance Attribute Details

#graphObject (readonly)

Returns the value of attribute graph.



11
12
13
# File 'lib/mosaik/graph/reducer.rb', line 11

def graph
  @graph
end

#optionsObject (readonly)

Returns the value of attribute options.



11
12
13
# File 'lib/mosaik/graph/reducer.rb', line 11

def options
  @options
end

Instance Method Details

#call(directed: false) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/mosaik/graph/reducer.rb', line 18

def call(directed: false)
  # Iterate over all combinations of vertices
  weights = graph.vertices.keys.combination(2).filter_map do |v1, v2|
    # Find all edges between the two vertices
    edges = Set.new(graph.find_edges(v1, v2) + graph.find_edges(v2, v1))

    # Calculate the weight for the aggregate edge
    weight = 0.0

    # Add weight for structural coupling
    weight += options[:structural] * edges
      .select { |e| e.attributes[:type] == "structural" }
      .sum { |e| e.attributes.fetch(:weight, 0.0) }

    # Add weight for logical coupling
    weight += options[:logical] * edges
      .select { |e| e.attributes[:type] == "logical" }
      .sum { |e| e.attributes.fetch(:weight, 0.0) }

    # Add weight for contributor coupling
    weight += options[:contributor] * edges
      .select { |e| e.attributes[:type] == "contributor" }
      .sum { |e| e.attributes.fetch(:weight, 0.0) }

    # Don't add zero weights
    next if weight.zero?

    # Return vertices and weights
    [v1, v2, weight]
  end

  # Remove all existing edges
  graph.vertices.each_value { |v| v.edges.clear }

  # Set graph directionality
  graph.directed = directed

  # Add new edges
  weights.each { |v1, v2, weight| graph.add_edge(v1, v2, weight:) unless weight.zero? }
end