Class: MOSAIK::Metrics::Cohesion

Inherits:
MOSAIK::Metric show all
Defined in:
lib/mosaik/metrics/cohesion.rb

Overview

Cohesion (S. Chidamber and C. Kemerer, 1994)

Instance Attribute Summary

Attributes inherited from MOSAIK::Metric

#graph, #options

Instance Method Summary collapse

Methods inherited from MOSAIK::Metric

#initialize

Constructor Details

This class inherits a constructor from MOSAIK::Metric

Instance Method Details

#evaluateObject



9
10
11
12
13
14
15
16
17
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
58
# File 'lib/mosaik/metrics/cohesion.rb', line 9

def evaluate
  # Total cohesion
  cohesion = 0.0

  # Iterate over each cluster
  graph.clusters.each_value do |cluster|
    # Find all vertices in the cluster
    vertices_in_cluster = cluster.vertices
    vertices_in_cluster_id = vertices_in_cluster.map(&:id)

    # Calculate the cardinality of the cluster
    cardinality_c = vertices_in_cluster.sum do |v|
      warn "No `methods` attribute found for #{v.id}" if v.attributes[:methods].nil?

      v.attributes[:methods] || 0.0
    end

    # Skip if the vertex has less than 2 methods (denominator would be 0)
    if cardinality_c < 2
      debug "Cluster #{cluster.id} has less than 2 methods, skipping cohesion calculation"

      # Store cohesion value in the cluster
      cluster.attributes[:cohesion] = 0.0

      next
    end

    # Calculate sum of edges between vertices in the cluster
    sum = vertices_in_cluster
      .map { |v| v.edges.slice(*vertices_in_cluster_id).values }
      .flatten(2)
      .uniq
      .size

    # Calculate cohesion value for the cluster
    cohesion_c = sum.to_f / (cardinality_c * (cardinality_c - 1) / 2)

    # Store cohesion value in the cluster
    cluster.attributes[:cohesion] = cohesion_c

    # Calculate cohesion contribution from this cluster
    cohesion += cohesion_c
  end

  # Store cohesion value in the graph
  graph.attributes[:cohesion] = cohesion

  # Return the total cohesion
  cohesion
end