Class: DSP::Spectrum

Inherits:
Object
  • Object
show all
Defined in:
lib/dsprb/spectrum.rb,
sig/dsprb.rbs

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size, transform: nil) ⇒ Spectrum

Defaults to the real-input transform; a complex one such as Fourier::Radix2 may be injected instead.

Parameters:

  • (::Integer)
  • transform: (_Transform, nil) (defaults to: nil)


9
10
11
12
13
14
15
# File 'lib/dsprb/spectrum.rb', line 9

def initialize(size, transform: nil)
  @size = Integer(size)
  @bins = (@size / 2) + 1
  @transform = transform || Fourier::Real.new(@size)
  @real_input = @transform.respond_to?(:power)
  freeze
end

Instance Attribute Details

#bins::Integer (readonly)

Returns the value of attribute bins.

Returns:

  • (::Integer)


5
6
7
# File 'lib/dsprb/spectrum.rb', line 5

def bins
  @bins
end

#size::Integer (readonly)

Returns the value of attribute size.

Returns:

  • (::Integer)


5
6
7
# File 'lib/dsprb/spectrum.rb', line 5

def size
  @size
end

#transform_Transform (readonly)

Returns the value of attribute transform.

Returns:



5
6
7
# File 'lib/dsprb/spectrum.rb', line 5

def transform
  @transform
end

Instance Method Details

#bin_of(frequency, sample_rate) ⇒ ::Integer

Parameters:

  • (::Numeric)
  • (::Numeric)

Returns:

  • (::Integer)


23
# File 'lib/dsprb/spectrum.rb', line 23

def bin_of(frequency, sample_rate) = (frequency * @size / sample_rate.to_f).round

#frequencies(sample_rate) ⇒ ::Array[::Float]

Parameters:

  • (::Numeric)

Returns:

  • (::Array[::Float])


21
# File 'lib/dsprb/spectrum.rb', line 21

def frequencies(sample_rate) = Array.new(@bins) { |bin| bin * sample_rate / @size.to_f }

#magnitude(frame) ⇒ spectrum

Parameters:

  • (frame)

Returns:

  • (spectrum)


19
# File 'lib/dsprb/spectrum.rb', line 19

def magnitude(frame) = power(frame).map { |value| Math.sqrt(value) }

#power(frame) ⇒ spectrum

Parameters:

  • (frame)

Returns:

  • (spectrum)


17
# File 'lib/dsprb/spectrum.rb', line 17

def power(frame) = @real_input ? @transform.power(frame) : complex_power(frame)