Class: DbClustering::Algorithms::Dbscan

Inherits:
Object
  • Object
show all
Defined in:
lib/algorithms/density_based/dbscan.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(datasource:, distance_metric:) ⇒ Dbscan

Returns a new instance of Dbscan.



9
10
11
12
13
# File 'lib/algorithms/density_based/dbscan.rb', line 9

def initialize(datasource:, distance_metric:)
  @datasource = datasource
  @distance_metric = distance_metric
  @clusters = []
end

Instance Attribute Details

#clustersObject

Returns the value of attribute clusters.



7
8
9
# File 'lib/algorithms/density_based/dbscan.rb', line 7

def clusters
  @clusters
end

#datasourceObject

Returns the value of attribute datasource.



7
8
9
# File 'lib/algorithms/density_based/dbscan.rb', line 7

def datasource
  @datasource
end

Instance Method Details

#cluster(max_distance:, min_neighbors:) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/algorithms/density_based/dbscan.rb', line 15

def cluster(max_distance:, min_neighbors:)
  @clusters = []
  cluster = nil

  @datasource.iterate_all_points do |point|
    neighbors = @datasource.neighbors(point: point, distance_metric: @distance_metric, max_distance: max_distance)

    if neighbors.count < min_neighbors
      point.is_noise = true
    else
      if point.cluster.nil?
        cluster = DbClustering::Models::Cluster.new
        @clusters << cluster
      else
        cluster = point.cluster
      end
      expand_cluster(cluster: cluster, neighbors: neighbors)
    end

  end
end

#expand_cluster(cluster:, neighbors:) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/algorithms/density_based/dbscan.rb', line 37

def expand_cluster(cluster:, neighbors:)
  # Important: If neighbors do not include point itself, then point must be added to cluster, too.
  neighbors.each do |neighbor|
    if !neighbor.visited?
      cluster.add(neighbor)
    end
  end
end