Class: Geospatial::Peaks

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/geospatial/histogram.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values) ⇒ Peaks

Returns a new instance of Peaks.



110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/geospatial/histogram.rb', line 110

def initialize(values)
	@values = values
	@derivative = []
	
	s = @values.size
	
	@values.size.times do |i|
		# Apply the Laplacian of Gaussians to compute the gradient changes:
		# @derivative << (@values[i-2] * -1) + (@values[i-1] * -1) + (@values[i] * 4) + (@values[i+1-s] * -1) + (@values[i+2-s] * -1)
		@derivative << (2.0 * @values[i-1]) + (-2.0 * @values[i+1-s])
	end
end

Instance Attribute Details

#derivativeObject (readonly)

Returns the value of attribute derivative.



123
124
125
# File 'lib/geospatial/histogram.rb', line 123

def derivative
  @derivative
end

Instance Method Details

#eachObject



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/geospatial/histogram.rb', line 125

def each
	return to_enum unless block_given?
	
	@derivative.each_with_index do |y2, x2|
		x1 = x2 - 1
		y1 = @derivative[x1]
		
		if (y1 <= 0 and y2 > 0) or (y1 > 0 and y2 <= 0)
			# There has been a zero crossing, so we have a peak somewhere here:
			g = (y2.to_f - y1.to_f)
			m = (-y1.to_f / g)
			
			yield x1 + m, g
		end
	end
end

#peaksObject



142
143
144
# File 'lib/geospatial/histogram.rb', line 142

def peaks
	self.class.new(@derivative)
end

#segmentsObject



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/geospatial/histogram.rb', line 146

def segments
	return to_enum(:segments) unless block_given?
	
	peaks = self.peaks
	gradients = peaks.to_a
	
	return if gradients.empty?
	
	index, gradient = gradients.first
	
	if gradient > 0
		gradients.push gradients.shift
	end
	
	gradients.each_slice(2) do |up, down|
		yield up, down
	end
end