dsprb 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSP
4
+ module Check
5
+ module_function
6
+
7
+ def positive!(value, name)
8
+ return value if value.positive?
9
+
10
+ raise ArgumentError, "#{name} must be positive, got #{value}"
11
+ end
12
+
13
+ def non_negative!(value, name)
14
+ return value unless value.negative?
15
+
16
+ raise ArgumentError, "#{name} must be non-negative, got #{value}"
17
+ end
18
+
19
+ def at_least!(value, minimum, name)
20
+ return value if value >= minimum
21
+
22
+ raise ArgumentError, "#{name} must be at least #{minimum}, got #{value}"
23
+ end
24
+
25
+ def power_of_two!(value, name)
26
+ return value if value.positive? && (value & (value - 1)).zero?
27
+
28
+ raise ArgumentError, "#{name} must be a positive power of two, got #{value}"
29
+ end
30
+
31
+ def below!(value, limit, name, limit_name)
32
+ return value if value < limit
33
+
34
+ raise ArgumentError, "#{name} must be below #{limit_name}, got #{value} and #{limit}"
35
+ end
36
+
37
+ def present!(collection, name)
38
+ return collection unless collection.empty?
39
+
40
+ raise ArgumentError, "#{name} must not be empty"
41
+ end
42
+ end
43
+ end
data/lib/dsprb/curve.rb CHANGED
@@ -4,10 +4,10 @@ module DSP
4
4
  module Curve
5
5
  module_function
6
6
 
7
- # Linear interpolation onto a uniform grid of the requested length, used to
8
- # bring contours of differing duration onto a common time base.
7
+ # Linear interpolation onto a uniform grid, bringing contours of differing
8
+ # duration onto a common time base.
9
9
  def resample(values, length)
10
- raise ArgumentError, "length must be positive, got #{length}" unless length.positive?
10
+ Check.positive!(length, "length")
11
11
  return Array.new(length, 0.0) if values.empty?
12
12
  return Array.new(length) { values.first.to_f } if values.length == 1 || length == 1
13
13
 
data/lib/dsprb/dct.rb CHANGED
@@ -2,23 +2,43 @@
2
2
 
3
3
  module DSP
4
4
  module Dct
5
- module_function
5
+ # X[k] = sum_i x[i] cos(pi k (i + 1/2) / N), unnormalized DCT-II.
6
+ class Two
7
+ extend Prepared
6
8
 
7
- # Unnormalized DCT-II: X[k] = sum_i x[i] cos(pi k (i + 1/2) / N).
8
- def two(values, count)
9
- length = values.length
10
- raise ArgumentError, "count must be positive, got #{count}" unless count.positive?
11
-
12
- Array.new(count) do |coefficient|
13
- total = 0.0
14
- index = 0
15
- while index < length
16
- total += values[index] * Math.cos(Math::PI * coefficient * (index + 0.5) / length)
17
- index += 1
18
- end
9
+ attr_reader :length, :count
10
+
11
+ def self.for(length, count) = prepared([length, count]) { new(length, count) }
19
12
 
20
- total
13
+ def initialize(length, count)
14
+ @length = Check.positive!(Integer(length), "length")
15
+ @count = Check.positive!(Integer(count), "count")
16
+
17
+ @basis = Array
18
+ .new(@count) do |coefficient|
19
+ Array.new(@length) { |index| Math.cos(Math::PI * coefficient * (index + 0.5) / @length) }.freeze
20
+ end
21
+ .freeze
22
+ freeze
23
+ end
24
+
25
+ def call(values)
26
+ Array.new(@count) do |coefficient|
27
+ row = @basis[coefficient]
28
+ total = 0.0
29
+ index = 0
30
+ while index < @length
31
+ total += values[index] * row[index]
32
+ index += 1
33
+ end
34
+
35
+ total
36
+ end
21
37
  end
22
38
  end
39
+
40
+ module_function
41
+
42
+ def two(values, count) = Two.for(values.length, count).call(values)
23
43
  end
24
44
  end
@@ -2,21 +2,28 @@
2
2
 
3
3
  module DSP
4
4
  class Decimator
5
- # An odd tap count keeps the FIR linear phase, so decimation adds no group delay skew.
5
+ # An odd tap count centers the symmetric kernel on a sample, so the output is not shifted in time.
6
6
  DEFAULT_TAPS = 31
7
7
 
8
- # Cutoff as a fraction of the decimated sample rate, leaving a transition margin below Nyquist.
8
+ # Cutoff as a fraction of the decimated rate, leaving a transition margin below Nyquist.
9
9
  CUTOFF_RATIO = 0.45
10
10
 
11
+ extend Prepared
12
+
11
13
  attr_reader :factor, :taps, :kernel
12
14
 
13
15
  def self.factor_for(sample_rate, target) = [(sample_rate / target).floor, 1].max
14
16
 
17
+ def self.for(factor, taps: DEFAULT_TAPS) = prepared([factor, taps]) { new(factor, taps: taps) }
18
+
19
+ def self.to(waveform, target, taps: DEFAULT_TAPS)
20
+ self.for(factor_for(waveform.sample_rate, target), taps: taps).call(waveform)
21
+ end
22
+
15
23
  def initialize(factor, taps: DEFAULT_TAPS)
16
- @factor = Integer(factor)
24
+ @factor = Check.at_least!(Integer(factor), 1, "factor")
17
25
  @taps = Integer(taps)
18
26
 
19
- raise ArgumentError, "factor must be at least one, got #{@factor}" unless @factor >= 1
20
27
  raise ArgumentError, "taps must be a positive odd number, got #{@taps}" unless @taps.positive? && @taps.odd?
21
28
 
22
29
  @middle = (@taps - 1) / 2
@@ -38,12 +45,7 @@ module DSP
38
45
 
39
46
  raw = Array.new(@taps) do |index|
40
47
  offset = index - @middle
41
- sinc = if offset.zero?
42
- 2.0 * cutoff
43
- else
44
- Math.sin(2.0 * Math::PI * cutoff * offset) / (Math::PI * offset)
45
- end
46
-
48
+ sinc = offset.zero? ? 2.0 * cutoff : Math.sin(2.0 * Math::PI * cutoff * offset) / (Math::PI * offset)
47
49
  sinc * taper[index]
48
50
  end
49
51
 
@@ -51,19 +53,36 @@ module DSP
51
53
  raw.map { |value| value / total }
52
54
  end
53
55
 
56
+ # Only the first and last few outputs reach past the signal, so the bound
57
+ # test is hoisted out of the interior and paid for by those alone.
54
58
  def filter(samples)
55
- out = []
59
+ length = samples.length
60
+ kernel = @kernel
61
+ taps = @taps
62
+ out = Array.new((length + @factor - 1) / @factor)
63
+
64
+ cursor = 0
56
65
  position = 0
57
- while position < samples.length
66
+ while position < length
67
+ first = position - @middle
58
68
  total = 0.0
59
- tap = 0
60
- while tap < @taps
61
- index = position + tap - @middle
62
- total += @kernel[tap] * samples[index] if index >= 0 && index < samples.length
63
- tap += 1
69
+ if first >= 0 && first + taps <= length
70
+ tap = 0
71
+ while tap < taps
72
+ total += kernel[tap] * samples[first + tap]
73
+ tap += 1
74
+ end
75
+ else
76
+ tap = 0
77
+ while tap < taps
78
+ index = first + tap
79
+ total += kernel[tap] * samples[index] if index >= 0 && index < length
80
+ tap += 1
81
+ end
64
82
  end
65
83
 
66
- out << total
84
+ out[cursor] = total
85
+ cursor += 1
67
86
  position += @factor
68
87
  end
69
88
 
data/lib/dsprb/energy.rb CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  module DSP
4
4
  module Energy
5
- # Keeps the logarithm of a silent frame finite, placing digital silence near -120 dB.
5
+ # Places digital silence near -120 dB instead of negative infinity.
6
6
  FLOOR = 1e-12
7
7
 
8
8
  module_function
9
9
 
10
10
  def frame_db(frame)
11
- raise ArgumentError, "frame must not be empty" if frame.empty?
11
+ Check.present!(frame, "frame")
12
12
 
13
13
  total = 0.0
14
14
  index = 0
@@ -34,8 +34,8 @@ module DSP
34
34
  end
35
35
 
36
36
  def envelope_db(samples, window:, hop:)
37
- raise ArgumentError, "window must be positive, got #{window}" unless window.positive?
38
- raise ArgumentError, "hop must be positive, got #{hop}" unless hop.positive?
37
+ Check.positive!(window, "window")
38
+ Check.positive!(hop, "hop")
39
39
  return [] if samples.length < window
40
40
 
41
41
  running = 0.0
@@ -2,28 +2,31 @@
2
2
 
3
3
  module DSP
4
4
  class Formants
5
- Peak = Data.define(:frequency, :amplitude)
5
+ Peak = Data.define(:frequency, :amplitude, :bandwidth) do
6
+ def initialize(frequency:, amplitude:, bandwidth: nil) = super
7
+ end
6
8
 
7
9
  # Conventional ceiling for adult speech; the first four formants fall below it.
8
10
  DEFAULT_MAXIMUM_HZ = 5500.0
9
11
  DEFAULT_COUNT = 4
10
12
 
11
- # Envelope samples taken over [0, Nyquist].
13
+ # Deprecated and ignored.
12
14
  DEFAULT_RESOLUTION = 512
13
-
14
- # One resonance can split into twin envelope peaks; peaks closer than this are merged.
15
15
  DEFAULT_SEPARATION_HZ = 250.0
16
16
 
17
- # Peaks pinned against the band edges are artifacts of the truncated envelope.
18
- DEFAULT_EDGE_MARGIN_HZ = 150.0
17
+ # Praat's margin: a root this close to 0 Hz or Nyquist shapes the spectral slope.
18
+ DEFAULT_EDGE_MARGIN_HZ = 50.0
19
+
20
+ # Above the bandwidth of 99 % of F1 and F2 in recorded vowels, below that of the spare
21
+ # pole pair a tenth-order fit leaves in the wide F1-F2 gap of [i].
22
+ MAXIMUM_BANDWIDTH_HZ = 1000.0
19
23
 
20
- # Below this the frame is too short to fit the predictor reliably.
21
24
  MINIMUM_SAMPLES = 40
22
25
 
23
26
  ENERGY_FLOOR = 1e-10
24
27
  LOG_FLOOR = 1e-18
25
28
 
26
- attr_reader :maximum_frequency, :count, :resolution, :separation, :edge_margin
29
+ attr_reader :maximum_frequency, :count, :resolution, :separation, :edge_margin, :order
27
30
 
28
31
  def initialize(
29
32
  maximum_frequency: DEFAULT_MAXIMUM_HZ,
@@ -38,9 +41,11 @@ module DSP
38
41
  @separation = Float(separation)
39
42
  @edge_margin = Float(edge_margin)
40
43
 
41
- raise ArgumentError, "count must be positive, got #{@count}" unless @count.positive?
42
- raise ArgumentError, "resolution must be at least two, got #{@resolution}" unless @resolution >= 2
44
+ Check.positive!(@count, "count")
45
+ Check.at_least!(@resolution, 2, "resolution")
46
+ Check.non_negative!(@edge_margin, "edge_margin")
43
47
 
48
+ @order = (2 * @count) + 2
44
49
  freeze
45
50
  end
46
51
 
@@ -53,60 +58,52 @@ module DSP
53
58
  model = fit(reduced)
54
59
  return [] if model.nil?
55
60
 
56
- merge(extrema(model.envelope(points: @resolution), reduced.sample_rate)).first(@count)
61
+ resonances(model.coefficients, reduced.sample_rate).first(@count)
57
62
  end
58
63
 
59
64
  private
60
65
 
61
- def reduce(waveform)
62
- Decimator.new(Decimator.factor_for(waveform.sample_rate, 2.0 * @maximum_frequency)).call(waveform)
63
- end
66
+ def reduce(waveform) = Decimator.to(waveform, 2.0 * @maximum_frequency)
64
67
 
65
68
  def fit(waveform)
66
- order = (2 * @count) + 2
67
69
  windowed = Window.apply(waveform.samples, Window.hamming(waveform.length))
68
- correlation = Autocorrelation.call(Framing.preemphasis(windowed), order)
70
+ correlation = Autocorrelation.call(Framing.preemphasis(windowed), @order)
69
71
  return nil if correlation[0] <= ENERGY_FLOOR
70
72
 
71
- Lpc.levinson(correlation, order)
73
+ Lpc.levinson(correlation, @order)
72
74
  end
73
75
 
74
- def extrema(envelope, sample_rate)
76
+ # A pole r e^{i w} of the predictor resonates at w fs / 2 pi with a
77
+ # bandwidth of -ln(r) fs / pi.
78
+ def resonances(coefficients, sample_rate)
75
79
  nyquist = sample_rate / 2.0
76
- span = envelope.length - 1
77
- found = []
78
-
79
- index = 1
80
- while index < span
81
- found << refine(envelope, index, nyquist, span) if rising?(envelope, index)
82
- index += 1
83
- end
84
80
 
85
- found.compact
86
- end
87
-
88
- def rising?(envelope, index)
89
- envelope[index] > envelope[index - 1] && envelope[index] >= envelope[index + 1]
90
- end
81
+ Polynomial
82
+ .roots(coefficients)
83
+ .filter_map do |root|
84
+ next unless root.imaginary.positive?
91
85
 
92
- def refine(envelope, index, nyquist, span)
93
- previous = Math.log(envelope[index - 1] + LOG_FLOOR)
94
- current = Math.log(envelope[index] + LOG_FLOOR)
95
- following = Math.log(envelope[index + 1] + LOG_FLOOR)
96
- frequency = nyquist * (index + Parabolic.vertex_offset(previous, current, following)) / span
97
- return nil unless frequency > @edge_margin && frequency < nyquist - @edge_margin
86
+ frequency = root.arg * nyquist / Math::PI
87
+ bandwidth = -Math.log(root.abs) * sample_rate / Math::PI
88
+ next unless frequency > @edge_margin && frequency < nyquist - @edge_margin
89
+ next unless bandwidth < MAXIMUM_BANDWIDTH_HZ
98
90
 
99
- Peak.new(frequency: frequency, amplitude: current)
91
+ Peak.new(frequency: frequency, amplitude: level(coefficients, root.arg), bandwidth: bandwidth)
92
+ end
93
+ .sort_by(&:frequency)
100
94
  end
101
95
 
102
- def merge(found)
103
- found.sort_by(&:frequency).each_with_object([]) do |peak, merged|
104
- if merged.any? && (peak.frequency - merged.last.frequency) < @separation
105
- merged[-1] = peak if peak.amplitude > merged.last.amplitude
106
- else
107
- merged << peak
108
- end
96
+ # ln 1 / |A(e^{i w})|^2, the all-pole envelope at the resonance.
97
+ def level(coefficients, angle)
98
+ real = 0.0
99
+ imaginary = 0.0
100
+ coefficients.each_with_index do |coefficient, lag|
101
+ real += coefficient * Math.cos(angle * lag)
102
+ imaginary -= coefficient * Math.sin(angle * lag)
109
103
  end
104
+
105
+ total = (real * real) + (imaginary * imaginary)
106
+ Math.log((total < Lpc::DENOMINATOR_FLOOR ? Lpc::UNBOUNDED_MAGNITUDE : 1.0 / total) + LOG_FLOOR)
110
107
  end
111
108
  end
112
109
  end
data/lib/dsprb/fourier.rb CHANGED
@@ -6,9 +6,7 @@ module DSP
6
6
  attr_reader :size
7
7
 
8
8
  def initialize(size)
9
- @size = Integer(size)
10
- raise ArgumentError, "FFT size must be a positive power of two, got #{@size}" unless power_of_two?(@size)
11
-
9
+ @size = Check.power_of_two!(Integer(size), "FFT size")
12
10
  @stages = build_stages(@size)
13
11
  freeze
14
12
  end
@@ -25,7 +23,19 @@ module DSP
25
23
  while block < @size
26
24
  index = 0
27
25
  while index < half
28
- butterfly(real, imaginary, block + index, half, cosines[index], sines[index])
26
+ top = block + index
27
+ bottom = top + half
28
+ cosine = cosines[index]
29
+ sine = sines[index]
30
+ real_bottom = real[bottom]
31
+ imaginary_bottom = imaginary[bottom]
32
+ rotated_real = (real_bottom * cosine) - (imaginary_bottom * sine)
33
+ rotated_imaginary = (real_bottom * sine) + (imaginary_bottom * cosine)
34
+
35
+ real[bottom] = real[top] - rotated_real
36
+ imaginary[bottom] = imaginary[top] - rotated_imaginary
37
+ real[top] += rotated_real
38
+ imaginary[top] += rotated_imaginary
29
39
  index += 1
30
40
  end
31
41
 
@@ -40,8 +50,6 @@ module DSP
40
50
 
41
51
  private
42
52
 
43
- def power_of_two?(value) = value.positive? && (value & (value - 1)).zero?
44
-
45
53
  def build_stages(size)
46
54
  stages = {}
47
55
  span = 2
@@ -89,18 +97,84 @@ module DSP
89
97
  source += 1
90
98
  end
91
99
  end
100
+ end
101
+
102
+ # Transform of a real signal. The even and odd samples are packed into one
103
+ # complex sequence of half the length and untangled afterwards, so a real
104
+ # frame costs about half of the complex transform.
105
+ class Real
106
+ MINIMUM_SIZE = 4
107
+
108
+ attr_reader :size, :bins
109
+
110
+ def initialize(size)
111
+ @size = Check.power_of_two!(Check.at_least!(Integer(size), MINIMUM_SIZE, "size"), "FFT size")
112
+ @half = @size / 2
113
+ @inner = Radix2.new(@half)
114
+ @bins = @half + 1
115
+ @cosines = Array.new(@half) { |bin| Math.cos(-Math::PI * bin / @half) }.freeze
116
+ @sines = Array.new(@half) { |bin| Math.sin(-Math::PI * bin / @half) }.freeze
117
+ freeze
118
+ end
119
+
120
+ # Bins 0..size/2, the non-redundant half. The frame is read up to size
121
+ # samples and zero padded.
122
+ def call(frame)
123
+ real, imaginary = pack(frame)
124
+ @inner.call(real, imaginary)
125
+ untangle(real, imaginary)
126
+ end
127
+
128
+ def power(frame)
129
+ real, imaginary = call(frame)
130
+
131
+ Array.new(@bins) { |bin| (real[bin] * real[bin]) + (imaginary[bin] * imaginary[bin]) }
132
+ end
133
+
134
+ private
135
+
136
+ def pack(frame)
137
+ real = Array.new(@half, 0.0)
138
+ imaginary = Array.new(@half, 0.0)
139
+ limit = frame.length < @size ? frame.length : @size
140
+ index = 0
141
+ while index < limit
142
+ if index.even?
143
+ real[index >> 1] = frame[index].to_f
144
+ else
145
+ imaginary[index >> 1] = frame[index].to_f
146
+ end
147
+
148
+ index += 1
149
+ end
150
+
151
+ [real, imaginary]
152
+ end
153
+
154
+ def untangle(real, imaginary)
155
+ out_real = Array.new(@bins)
156
+ out_imaginary = Array.new(@bins)
157
+
158
+ bin = 0
159
+ while bin <= @half
160
+ low = bin == @half ? 0 : bin
161
+ high = (@half - bin) % @half
162
+
163
+ even_real = (real[low] + real[high]) * 0.5
164
+ even_imaginary = (imaginary[low] - imaginary[high]) * 0.5
165
+ odd_real = (imaginary[low] + imaginary[high]) * 0.5
166
+ odd_imaginary = (real[high] - real[low]) * 0.5
167
+
168
+ # The Nyquist twiddle is -1, which a half length table cannot hold.
169
+ cosine = bin == @half ? -1.0 : @cosines[bin]
170
+ sine = bin == @half ? 0.0 : @sines[bin]
171
+
172
+ out_real[bin] = even_real + ((odd_real * cosine) - (odd_imaginary * sine))
173
+ out_imaginary[bin] = even_imaginary + ((odd_real * sine) + (odd_imaginary * cosine))
174
+ bin += 1
175
+ end
92
176
 
93
- def butterfly(real, imaginary, top, half, cosine, sine)
94
- bottom = top + half
95
- real_bottom = real[bottom]
96
- imaginary_bottom = imaginary[bottom]
97
- rotated_real = (real_bottom * cosine) - (imaginary_bottom * sine)
98
- rotated_imaginary = (real_bottom * sine) + (imaginary_bottom * cosine)
99
-
100
- real[bottom] = real[top] - rotated_real
101
- imaginary[bottom] = imaginary[top] - rotated_imaginary
102
- real[top] += rotated_real
103
- imaginary[top] += rotated_imaginary
177
+ [out_real, out_imaginary]
104
178
  end
105
179
  end
106
180
  end
data/lib/dsprb/framing.rb CHANGED
@@ -8,8 +8,8 @@ module DSP
8
8
  module_function
9
9
 
10
10
  def frames(samples, window:, hop:)
11
- raise ArgumentError, "window must be positive, got #{window}" unless window.positive?
12
- raise ArgumentError, "hop must be positive, got #{hop}" unless hop.positive?
11
+ Check.positive!(window, "window")
12
+ Check.positive!(hop, "hop")
13
13
 
14
14
  out = []
15
15
  position = 0
data/lib/dsprb/lpc.rb CHANGED
@@ -2,51 +2,73 @@
2
2
 
3
3
  module DSP
4
4
  module Lpc
5
- # Below this the all-pole denominator is treated as a pole on the unit circle.
6
5
  DENOMINATOR_FLOOR = 1e-18
7
-
8
6
  UNBOUNDED_MAGNITUDE = 1e9
9
7
 
10
- Model = Data.define(:coefficients, :error) do
11
- def order = coefficients.length - 1
12
-
13
- # Magnitude of the all-pole transfer function 1 / |A(e^{i w})|^2 sampled
14
- # over [0, pi], the spectral envelope the predictor implies.
15
- def envelope(points:)
16
- raise ArgumentError, "points must be at least two, got #{points}" unless points >= 2
17
-
18
- span = points - 1
8
+ # Samples 1 / |A(e^{i w})|^2 over [0, pi] on a fixed grid. Squaring the
9
+ # polynomial first leaves a sum over its autocorrelation, which is real and
10
+ # even, so only cosines remain and the grid precomputes once:
11
+ #
12
+ # |A(w)|^2 = c[0] + 2 sum_{m=1..order} c[m] cos(w m)
13
+ class Envelope
14
+ extend Prepared
15
+
16
+ attr_reader :points, :order
17
+
18
+ def self.for(points:, order:) = prepared([points, order]) { new(points: points, order: order) }
19
+
20
+ def initialize(points:, order:)
21
+ @points = Check.at_least!(Integer(points), 2, "points")
22
+ @order = Check.non_negative!(Integer(order), "order")
23
+
24
+ span = (@points - 1).to_f
25
+ @cosines = Array
26
+ .new(@points) do |point|
27
+ Array.new(@order + 1) { |lag| Math.cos(Math::PI * point * lag / span) }.freeze
28
+ end
29
+ .freeze
30
+ freeze
31
+ end
19
32
 
20
- Array.new(points) do |index|
21
- real, imaginary = response(Math::PI * index / span)
22
- denominator = (real * real) + (imaginary * imaginary)
23
- denominator < DENOMINATOR_FLOOR ? UNBOUNDED_MAGNITUDE : 1.0 / denominator
33
+ def call(coefficients)
34
+ highest = coefficients.length - 1
35
+ if highest > @order
36
+ raise ArgumentError, "expected at most #{@order + 1} coefficients, got #{coefficients.length}"
24
37
  end
25
- end
26
38
 
27
- private
28
-
29
- def response(omega)
30
- real = 0.0
31
- imaginary = 0.0
32
- index = 0
33
- while index < coefficients.length
34
- angle = -omega * index
35
- real += coefficients[index] * Math.cos(angle)
36
- imaginary += coefficients[index] * Math.sin(angle)
37
- index += 1
39
+ correlation = Autocorrelation.call(coefficients, highest)
40
+ out = Array.new(@points)
41
+
42
+ point = 0
43
+ while point < @points
44
+ row = @cosines[point]
45
+ total = correlation[0]
46
+ lag = 1
47
+ while lag <= highest
48
+ total += 2.0 * correlation[lag] * row[lag]
49
+ lag += 1
50
+ end
51
+
52
+ out[point] = total < DENOMINATOR_FLOOR ? UNBOUNDED_MAGNITUDE : 1.0 / total
53
+ point += 1
38
54
  end
39
55
 
40
- [real, imaginary]
56
+ out
41
57
  end
42
58
  end
43
59
 
60
+ Model = Data.define(:coefficients, :error) do
61
+ def order = coefficients.length - 1
62
+
63
+ def envelope(points:) = Envelope.for(points: points, order: order).call(coefficients)
64
+ end
65
+
44
66
  module_function
45
67
 
46
68
  def solve(frame, order:) = levinson(Autocorrelation.call(frame, order), order)
47
69
 
48
- # Levinson-Durbin recursion: solves the Yule-Walker system in O(order^2),
49
- # stopping early when a reflection coefficient leaves the unit circle.
70
+ # Levinson-Durbin recursion, O(order^2), stopping early when a reflection
71
+ # coefficient leaves the unit circle.
50
72
  def levinson(autocorrelation, order)
51
73
  coefficients = Array.new(order + 1, 0.0)
52
74
  coefficients[0] = 1.0
@@ -9,13 +9,12 @@ module DSP
9
9
  DEFAULT_FILTERS = 26
10
10
  DEFAULT_LOW_HZ = 50.0
11
11
 
12
- # Keeps the logarithm of a band that collected no energy finite.
13
12
  ENERGY_FLOOR = 1e-12
14
13
 
15
14
  attr_reader :sample_rate, :size, :filters, :low, :high, :warp, :bands
16
15
 
17
- # warp rescales the band centers for vocal tract length normalization:
18
- # values above 1 shift the bank upwards, suiting shorter vocal tracts.
16
+ # warp rescales the band centers for vocal tract length normalization;
17
+ # above 1 the bank shifts upwards, suiting shorter vocal tracts.
19
18
  def initialize(sample_rate:, size:, filters: DEFAULT_FILTERS, low: DEFAULT_LOW_HZ, high: nil, warp: 1.0)
20
19
  @sample_rate = Float(sample_rate)
21
20
  @size = Integer(size)
@@ -51,9 +50,9 @@ module DSP
51
50
  private
52
51
 
53
52
  def validate!
54
- raise ArgumentError, "filters must be positive, got #{@filters}" unless @filters.positive?
55
- raise ArgumentError, "warp must be positive, got #{@warp}" unless @warp.positive?
56
- raise ArgumentError, "low must be below high, got #{@low} and #{@high}" unless @low < @high
53
+ Check.positive!(@filters, "filters")
54
+ Check.positive!(@warp, "warp")
55
+ Check.below!(@low, @high, "low", "high")
57
56
  end
58
57
 
59
58
  def build_bands