forked from jaakkopasanen/AutoEq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
frequency_response.py
1892 lines (1660 loc) · 81.4 KB
/
frequency_response.py
1
2
3
4
5
6
7
8
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*_
import os
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import math
import pandas as pd
from io import StringIO
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy.signal import savgol_filter, find_peaks, minimum_phase, firwin2
from scipy.special import expit
from scipy.stats import linregress
from scipy.fftpack import next_fast_len
import numpy as np
import urllib
from time import time
from tabulate import tabulate
from PIL import Image
import re
import warnings
import biquad
from constants import DEFAULT_F_MIN, DEFAULT_F_MAX, DEFAULT_STEP, DEFAULT_MAX_GAIN, DEFAULT_TREBLE_F_LOWER, \
DEFAULT_TREBLE_F_UPPER, DEFAULT_TREBLE_MAX_GAIN, DEFAULT_TREBLE_GAIN_K, DEFAULT_SMOOTHING_WINDOW_SIZE, \
DEFAULT_SMOOTHING_ITERATIONS, DEFAULT_TREBLE_SMOOTHING_F_LOWER, DEFAULT_TREBLE_SMOOTHING_F_UPPER, \
DEFAULT_TREBLE_SMOOTHING_WINDOW_SIZE, DEFAULT_TREBLE_SMOOTHING_ITERATIONS, DEFAULT_TILT, DEFAULT_FS, \
DEFAULT_F_RES, DEFAULT_BASS_BOOST_GAIN, DEFAULT_BASS_BOOST_FC, \
DEFAULT_BASS_BOOST_Q, DEFAULT_GRAPHIC_EQ_STEP, HARMAN_INEAR_PREFENCE_FREQUENCIES, \
HARMAN_ONEAR_PREFERENCE_FREQUENCIES, PREAMP_HEADROOM
class FrequencyResponse:
def __init__(self,
name=None,
frequency=None,
raw=None,
error=None,
smoothed=None,
error_smoothed=None,
equalization=None,
parametric_eq=None,
fixed_band_eq=None,
equalized_raw=None,
equalized_smoothed=None,
target=None):
if not name:
raise TypeError('Name must not be a non-empty string.')
self.name = name.strip()
self.frequency = self._init_data(frequency)
if not len(self.frequency):
self.frequency = self.generate_frequencies()
self.raw = self._init_data(raw)
self.smoothed = self._init_data(smoothed)
self.error = self._init_data(error)
self.error_smoothed = self._init_data(error_smoothed)
self.equalization = self._init_data(equalization)
self.parametric_eq = self._init_data(parametric_eq)
self.fixed_band_eq = self._init_data(fixed_band_eq)
self.equalized_raw = self._init_data(equalized_raw)
self.equalized_smoothed = self._init_data(equalized_smoothed)
self.target = self._init_data(target)
self._sort()
def copy(self, name=None):
return self.__class__(
name=self.name + '_copy' if name is None else name,
frequency=self._init_data(self.frequency),
raw=self._init_data(self.raw),
error=self._init_data(self.error),
smoothed=self._init_data(self.smoothed),
error_smoothed=self._init_data(self.error_smoothed),
equalization=self._init_data(self.equalization),
parametric_eq=self._init_data(self.parametric_eq),
fixed_band_eq=self._init_data(self.fixed_band_eq),
equalized_raw=self._init_data(self.equalized_raw),
equalized_smoothed=self._init_data(self.equalized_smoothed),
target=self._init_data(self.target)
)
def _init_data(self, data):
"""Initializes data to a clean format. If None is passed and empty array is created. Non-numbers are removed."""
if data is None:
# None means empty array
data = []
elif type(data) == float or type(data) == int:
# Scalar means all values are that, same shape as frequency
data = np.ones(self.frequency.shape) * data
# Replace nans with Nones
data = [None if x is None or math.isnan(x) else x for x in data]
# Wrap in Numpy array
data = np.array(data)
return data
def _sort(self):
sorted_inds = self.frequency.argsort()
self.frequency = self.frequency[sorted_inds]
for i in range(1, len(self.frequency)):
if self.frequency[i] == self.frequency[i-1]:
raise ValueError('Duplicate values found at frequency {}. Remove duplicates manually.'.format(
self.frequency[i])
)
if len(self.raw):
self.raw = self.raw[sorted_inds]
if len(self.error):
self.error = self.error[sorted_inds]
if len(self.smoothed):
self.smoothed = self.smoothed[sorted_inds]
if len(self.error_smoothed):
self.error_smoothed = self.error_smoothed[sorted_inds]
if len(self.equalization):
self.equalization = self.equalization[sorted_inds]
if len(self.parametric_eq):
self.parametric_eq = self.parametric_eq[sorted_inds]
if len(self.fixed_band_eq):
self.fixed_band_eq = self.fixed_band_eq[sorted_inds]
if len(self.equalized_raw):
self.equalized_raw = self.equalized_raw[sorted_inds]
if len(self.equalized_smoothed):
self.equalized_smoothed = self.equalized_smoothed[sorted_inds]
if len(self.target):
self.target = self.target[sorted_inds]
def reset(self,
raw=False,
smoothed=True,
error=True,
error_smoothed=True,
equalization=True,
fixed_band_eq=True,
parametric_eq=True,
equalized_raw=True,
equalized_smoothed=True,
target=True):
"""Resets data."""
if raw:
self.raw = self._init_data(None)
if smoothed:
self.smoothed = self._init_data(None)
if error:
self.error = self._init_data(None)
if error_smoothed:
self.error_smoothed = self._init_data(None)
if equalization:
self.equalization = self._init_data(None)
if parametric_eq:
self.parametric_eq = self._init_data(None)
if fixed_band_eq:
self.fixed_band_eq = self._init_data(None)
if equalized_raw:
self.equalized_raw = self._init_data(None)
if equalized_smoothed:
self.equalized_smoothed = self._init_data(None)
if target:
self.target = self._init_data(None)
@classmethod
def read_from_csv(cls, file_path):
"""Reads data from CSV file and constructs class instance."""
name = '.'.join(os.path.split(file_path)[1].split('.')[:-1])
# Read file
f = open(file_path, 'r', encoding='utf-8')
s = f.read()
# Regex for AutoEq style CSV
header_pattern = r'frequency(,(raw|smoothed|error|error_smoothed|equalization|parametric_eq|fixed_band_eq|equalized_raw|equalized_smoothed|target))+'
float_pattern = r'-?\d+\.?\d+'
data_2_pattern = r'{fl}[ ,;:\t]+{fl}?'.format(fl=float_pattern)
data_n_pattern = r'{fl}([ ,;:\t]+{fl})+?'.format(fl=float_pattern)
autoeq_pattern = r'^{header}(\n{data})+\n*$'.format(header=header_pattern, data=data_n_pattern)
if re.match(autoeq_pattern, s):
# Known AutoEq CSV format
df = pd.read_csv(StringIO(s), sep=',', header=0)
frequency = list(df['frequency'])
raw = list(df['raw']) if 'raw' in df else None
smoothed = list(df['smoothed']) if 'smoothed' in df else None
error = list(df['error']) if 'error' in df else None
error_smoothed = list(df['error_smoothed']) if 'error_smoothed' in df else None
equalization = list(df['equalization']) if 'equalization' in df else None
parametric_eq = list(df['parametric_eq']) if 'parametric_eq' in df else None
fixed_band_eq = list(df['fixed_band_eq']) if 'fixed_band_eq' in df else None
equalized_raw = list(df['equalized_raw']) if 'equalized_raw' in df else None
equalized_smoothed = list(df['equalized_smoothed']) if 'equalized_smoothed' in df else None
target = list(df['target']) if 'target' in df else None
return cls(
name=name,
frequency=frequency,
raw=raw,
smoothed=smoothed,
error=error,
error_smoothed=error_smoothed,
equalization=equalization,
parametric_eq=parametric_eq,
fixed_band_eq=fixed_band_eq,
equalized_raw=equalized_raw,
equalized_smoothed=equalized_smoothed,
target=target
)
else:
# Unknown format, try to guess
lines = s.split('\n')
frequency = []
raw = []
for line in lines:
if re.match(data_2_pattern, line): # float separator float
floats = re.findall(float_pattern, line)
frequency.append(float(floats[0])) # Assume first to be frequency
raw.append(float(floats[1])) # Assume second to be raw
# Discard all lines which don't match data pattern
return cls(name=name, frequency=frequency, raw=raw)
def to_dict(self):
d = dict()
if len(self.frequency):
d['frequency'] = self.frequency.tolist()
if len(self.raw):
d['raw'] = [x if x is not None else 'NaN' for x in self.raw]
if len(self.error):
d['error'] = [x if x is not None else 'NaN' for x in self.error]
if len(self.smoothed):
d['smoothed'] = [x if x is not None else 'NaN' for x in self.smoothed]
if len(self.error_smoothed):
d['error_smoothed'] = [x if x is not None else 'NaN' for x in self.error_smoothed]
if len(self.equalization):
d['equalization'] = [x if x is not None else 'NaN' for x in self.equalization]
if len(self.parametric_eq):
d['parametric_eq'] = [x if x is not None else 'NaN' for x in self.parametric_eq]
if len(self.fixed_band_eq):
d['fixed_band_eq'] = [x if x is not None else 'NaN' for x in self.fixed_band_eq]
if len(self.equalized_raw):
d['equalized_raw'] = [x if x is not None else 'NaN' for x in self.equalized_raw]
if len(self.equalized_smoothed):
d['equalized_smoothed'] = [x if x is not None else 'NaN' for x in self.equalized_smoothed]
if len(self.target):
d['target'] = [x if x is not None else 'NaN' for x in self.target]
return d
def write_to_csv(self, file_path=None):
"""Writes data to files as CSV."""
file_path = os.path.abspath(file_path)
df = pd.DataFrame(self.to_dict())
df.to_csv(file_path, header=True, index=False, float_format='%.2f')
def eqapo_graphic_eq(self, normalize=True, f_step=DEFAULT_GRAPHIC_EQ_STEP):
"""Generates EqualizerAPO GraphicEQ string from equalization curve."""
fr = self.__class__(name='hack', frequency=self.frequency, raw=self.equalization)
n = np.ceil(np.log(20000 / 20) / np.log(f_step))
f = 20 * f_step**np.arange(n)
f = np.sort(np.unique(f.astype('int')))
fr.interpolate(f=f)
if normalize:
fr.raw -= np.max(fr.raw) + PREAMP_HEADROOM
if fr.raw[0] > 0.0:
# Prevent bass boost below lowest frequency
fr.raw[0] = 0.0
# Remove leading zeros
while np.abs(fr.raw[-1]) < 0.1 and np.abs(fr.raw[-2]) < 0.1: # Last two are zeros
fr.raw = fr.raw[:-1]
s = '; '.join(['{f} {a:.1f}'.format(f=f, a=a) for f, a in zip(fr.frequency, fr.raw)])
s = 'GraphicEQ: ' + s
return s
def write_eqapo_graphic_eq(self, file_path, normalize=True):
"""Writes equalization graph to a file as Equalizer APO config."""
file_path = os.path.abspath(file_path)
s = self.eqapo_graphic_eq(normalize=normalize)
with open(file_path, 'w', encoding='utf-8') as f:
f.write(s)
return s
@classmethod
def optimize_biquad_filters(cls, frequency, target, max_time=5, max_filters=None, fs=DEFAULT_FS, fc=None, q=None):
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow.compat.v1 as tf
tf.get_logger().setLevel('ERROR')
tf.disable_v2_behavior()
if fc is not None or q is not None:
if fc is None:
raise TypeError('"fc" must be given if "q" is given.')
if q is None:
raise TypeError('"q" must be give nif "fc" is given.')
if max_filters is not None:
raise TypeError('"max_filters" must not be given when "fc" and "q" are given.')
fc = np.array(fc, dtype='float32')
q = np.array(q, dtype='float32')
parametric = fc is None
# Reset graph to be able to run this again
tf.reset_default_graph()
# Sampling frequency
fs_tf = tf.constant(fs, name='f', dtype='float32')
# Smoothen heavily
fr_target = cls(name='Filter Initialization', frequency=frequency, raw=target)
fr_target.smoothen_fractional_octave(window_size=1 / 7, iterations=1000)
# Equalization target
eq_target = tf.constant(target, name='eq_target', dtype='float32')
n_ls = n_hs = 0
if parametric:
# Fc and Q not given, parametric equalizer, find initial estimation of peaks and gains
fr_target_pos = np.clip(fr_target.smoothed, a_min=0.0, a_max=None)
peak_inds = find_peaks(fr_target_pos)[0]
fr_target_neg = np.clip(-fr_target.smoothed, a_min=0.0, a_max=None)
peak_inds = np.concatenate((peak_inds, find_peaks(fr_target_neg)[0]))
peak_inds.sort()
peak_inds = peak_inds[np.abs(fr_target.smoothed[peak_inds]) > 0.1]
# Peak center frequencies and gains
peak_fc = frequency[peak_inds].astype('float32')
if peak_fc[0] > 80:
# First peak is beyond 80Hz, add peaks to 20Hz and 60Hz
peak_fc = np.concatenate((np.array([20, 60], dtype='float32'), peak_fc))
elif peak_fc[0] > 40:
# First peak is beyond 40Hz, add peak to 20Hz
peak_fc = np.concatenate((np.array([20], dtype='float32'), peak_fc))
# Gains at peak center frequencies
interpolator = InterpolatedUnivariateSpline(np.log10(frequency), fr_target.smoothed, k=1)
peak_g = interpolator(np.log10(peak_fc)).astype('float32')
def remove_small_filters(min_gain):
# Remove peaks with too little gain
nonlocal peak_fc, peak_g
peak_fc = peak_fc[np.abs(peak_g) > min_gain]
peak_g = peak_g[np.abs(peak_g) > min_gain]
def merge_filters():
# Merge two filters which have small integral between them
nonlocal peak_fc, peak_g
# Form filter pairs, select only filters with equal gain sign
pair_inds = []
for j in range(len(peak_fc) - 1):
if np.sign(peak_g[j]) == np.sign(peak_g[j + 1]):
pair_inds.append(j)
min_err = None
min_err_ind = None
for pair_ind in pair_inds:
# Interpolate between the two points
f_0 = peak_fc[pair_ind]
g_0 = peak_g[pair_ind]
i_0 = np.argmin(np.abs(frequency - f_0))
f_1 = peak_fc[pair_ind + 1]
i_1 = np.argmin(np.abs(frequency - f_1))
g_1 = peak_g[pair_ind]
interp = InterpolatedUnivariateSpline(np.log10([f_0, f_1]), [g_0, g_1], k=1)
line = interp(frequency[i_0:i_1 + 1])
err = line - fr_target.smoothed[i_0:i_1 + 1]
err = np.sqrt(np.mean(np.square(err))) # Root mean squared error
if min_err is None or err < min_err:
min_err = err
min_err_ind = pair_ind
if min_err is None:
# No pairs detected
return False
# Select smallest error if err < threshold
if min_err < 0.3:
# New filter
c = peak_fc[min_err_ind] * np.sqrt(peak_fc[min_err_ind + 1] / peak_fc[min_err_ind])
c = frequency[np.argmin(np.abs(frequency - c))]
g = np.mean([peak_g[min_err_ind], peak_g[min_err_ind + 1]])
# Remove filters
peak_fc = np.delete(peak_fc, [min_err_ind, min_err_ind + 1])
peak_g = np.delete(peak_g, [min_err_ind, min_err_ind + 1])
# Add filter in-between
peak_fc = np.insert(peak_fc, min_err_ind, c)
peak_g = np.insert(peak_g, min_err_ind, g)
return True
return False # No prominent filter pairs
# Remove insignificant filters
remove_small_filters(0.1)
if len(peak_fc) == 0:
# All filters were insignificant, exit
return np.zeros(frequency.shape), 0.0, np.array([]), np.array([]), np.array([])
# Limit filter number to max_filters by removing least significant filters and merging close filters
if max_filters is not None:
if len(peak_fc) > max_filters:
# Remove too small filters
remove_small_filters(0.2)
if len(peak_fc) > max_filters:
# Try to remove some more
remove_small_filters(0.33)
# Merge filters if needed
while merge_filters() and len(peak_fc) > max_filters:
pass
if len(peak_fc) > max_filters:
# Remove smallest filters
sorted_inds = np.flip(np.argsort(np.abs(peak_g)))
sorted_inds = sorted_inds[:max_filters]
peak_fc = peak_fc[sorted_inds]
peak_g = peak_g[sorted_inds]
sorted_inds = np.argsort(peak_fc)
peak_fc = peak_fc[sorted_inds]
peak_g = peak_g[sorted_inds]
n = n_pk = len(peak_fc)
# Frequencies
f = tf.constant(np.repeat(np.expand_dims(frequency, axis=0), n, axis=0), name='f', dtype='float32')
# Center frequencies
fc = tf.get_variable('fc', initializer=np.expand_dims(np.log10(peak_fc), axis=1), dtype='float32')
# Q
Q_init = np.ones([n, 1], dtype='float32') * np.ones([n_pk, 1], dtype='float32')
Q = tf.get_variable('Q', initializer=Q_init, dtype='float32')
else:
# Fc and Q given, fixed band equalizer
Q = tf.get_variable(
'Q',
initializer=np.expand_dims(q, axis=1),
dtype='float32',
trainable=False
)
# Gains at peak center frequencies
interpolator = InterpolatedUnivariateSpline(np.log10(frequency), fr_target.smoothed, k=1)
peak_g = interpolator(np.log10(fc)).astype('float32')
# Number of filters
n = n_pk = len(fc)
# Frequencies
f = tf.constant(np.repeat(np.expand_dims(frequency, axis=0), n, axis=0), name='f', dtype='float32')
# Center frequencies
fc = tf.get_variable(
'fc',
initializer=np.expand_dims(np.log10(fc), axis=1),
dtype='float32',
trainable=False
)
# Gain
gain = tf.get_variable('gain', initializer=np.expand_dims(peak_g, axis=1), dtype='float32')
# Filter design
# Low shelf filter
# This is not used at the moment but is kept for future
A = 10 ** (gain[:n_ls, :] / 40)
w0 = 2 * np.pi * tf.pow(10.0, fc[:n_ls, :]) / fs_tf
alpha = tf.sin(w0) / (2 * Q[:n_ls, :])
a0_ls = ((A + 1) + (A - 1) * tf.cos(w0) + 2 * tf.sqrt(A) * alpha)
a1_ls = (-(-2 * ((A - 1) + (A + 1) * tf.cos(w0))) / a0_ls)
a2_ls = (-((A + 1) + (A - 1) * tf.cos(w0) - 2 * tf.sqrt(A) * alpha) / a0_ls)
b0_ls = ((A * ((A + 1) - (A - 1) * tf.cos(w0) + 2 * tf.sqrt(A) * alpha)) / a0_ls)
b1_ls = ((2 * A * ((A - 1) - (A + 1) * tf.cos(w0))) / a0_ls)
b2_ls = ((A * ((A + 1) - (A - 1) * tf.cos(w0) - 2 * tf.sqrt(A) * alpha)) / a0_ls)
# Peak filter
A = 10 ** (gain[n_ls:n_ls+n_pk, :] / 40)
w0 = 2 * np.pi * tf.pow(10.0, fc[n_ls:n_ls+n_pk, :]) / fs_tf
alpha = tf.sin(w0) / (2 * Q[n_ls:n_ls+n_pk, :])
a0_pk = (1 + alpha / A)
a1_pk = -(-2 * tf.cos(w0)) / a0_pk
a2_pk = -(1 - alpha / A) / a0_pk
b0_pk = (1 + alpha * A) / a0_pk
b1_pk = (-2 * tf.cos(w0)) / a0_pk
b2_pk = (1 - alpha * A) / a0_pk
# High self filter
# This is not kept at the moment but kept for future
A = 10 ** (gain[n_ls+n_pk:, :] / 40)
w0 = 2 * np.pi * tf.pow(10.0, fc[n_ls+n_pk:, :]) / fs_tf
alpha = tf.sin(w0) / (2 * Q[n_ls+n_pk:, :])
a0_hs = (A + 1) - (A - 1) * tf.cos(w0) + 2 * tf.sqrt(A) * alpha
a1_hs = -(2 * ((A - 1) - (A + 1) * tf.cos(w0))) / a0_hs
a2_hs = -((A + 1) - (A - 1) * tf.cos(w0) - 2 * tf.sqrt(A) * alpha) / a0_hs
b0_hs = (A * ((A + 1) + (A - 1) * tf.cos(w0) + 2 * tf.sqrt(A) * alpha)) / a0_hs
b1_hs = (-2 * A * ((A - 1) + (A + 1) * tf.cos(w0))) / a0_hs
b2_hs = (A * ((A + 1) + (A - 1) * tf.cos(w0) - 2 * tf.sqrt(A) * alpha)) / a0_hs
# Concatenate all
a0 = tf.concat([a0_ls, a0_pk, a0_hs], axis=0)
a1 = tf.concat([a1_ls, a1_pk, a1_hs], axis=0)
a2 = tf.concat([a2_ls, a2_pk, a2_hs], axis=0)
b0 = tf.concat([b0_ls, b0_pk, b0_hs], axis=0)
b1 = tf.concat([b1_ls, b1_pk, b1_hs], axis=0)
b2 = tf.concat([b2_ls, b2_pk, b2_hs], axis=0)
w = 2 * np.pi * f / fs_tf
phi = 4 * tf.sin(w / 2) ** 2
a0 = 1.0
a1 *= -1
a2 *= -1
# Equalizer frequency response
eq_op = 10 * tf.log(
(b0 + b1 + b2) ** 2 + (b0 * b2 * phi - (b1 * (b0 + b2) + 4 * b0 * b2)) * phi
) / tf.log(10.0) - 10 * tf.log(
(a0 + a1 + a2) ** 2 + (a0 * a2 * phi - (a1 * (a0 + a2) + 4 * a0 * a2)) * phi
) / tf.log(10.0)
eq_op = tf.reduce_sum(eq_op, axis=0)
# RMSE as loss
loss = tf.reduce_mean(tf.square(eq_op - eq_target))
learning_rate_value = 0.1
decay = 0.9995
learning_rate = tf.placeholder('float32', shape=(), name='learning_rate')
train_step = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
# Optimization loop
min_loss = None
threshold = 0.01
momentum = 100
bad_steps = 0
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
t = time()
while time() - t < max_time:
step_loss, _ = sess.run([loss, train_step], feed_dict={learning_rate: learning_rate_value})
if min_loss is None or step_loss < min_loss:
# Improvement, update model
_eq, _fc, _Q, _gain = sess.run([eq_op, fc, Q, gain])
_fc = 10**_fc
if min_loss is None or min_loss - step_loss > threshold:
# Loss improved
min_loss = step_loss
bad_steps = 0
else:
# No improvement, increment bad step counter
bad_steps += 1
if bad_steps > momentum:
# Bad steps exceed maximum number of bad steps, break
break
learning_rate_value = learning_rate_value * decay
rmse = np.sqrt(min_loss) # RMSE
# Fold center frequencies back to normal
_fc = np.abs(np.round(_fc / fs) * fs - _fc)
# Squeeze to rank-1 arrays
_fc = np.squeeze(_fc)
_Q = np.squeeze(_Q)
_gain = np.squeeze(_gain)
if parametric:
# Filter selection slice
sl = np.logical_and(np.abs(_gain) > 0.1, _fc > 10)
_fc = _fc[sl]
_Q = np.abs(_Q[sl])
_gain = _gain[sl]
# Sort filters by center frequency
sorted_inds = np.argsort(_fc)
_fc = _fc[sorted_inds]
_Q = _Q[sorted_inds]
_gain = _gain[sorted_inds]
# Expand dimensionality for biquad
_fc = np.expand_dims(_fc, axis=1)
_Q = np.expand_dims(np.abs(_Q), axis=1)
_gain = np.expand_dims(_gain, axis=1)
# Re-compute eq
a0, a1, a2, b0, b1, b2 = biquad.peaking(_fc, _Q, _gain, fs=fs)
frequency = np.repeat(np.expand_dims(frequency, axis=0), len(_fc), axis=0)
_eq = np.sum(biquad.digital_coeffs(frequency, fs, a0, a1, a2, b0, b1, b2), axis=0)
coeffs_a = np.hstack((np.tile(a0, a1.shape), a1, a2))
coeffs_b = np.hstack((b0, b1, b2))
return _eq, rmse, np.squeeze(_fc, axis=1), np.squeeze(_Q, axis=1), np.squeeze(_gain, axis=1), coeffs_a, coeffs_b
def optimize_parametric_eq(self, max_filters=None, fs=DEFAULT_FS):
"""Fits multiple biquad filters to equalization curve. If max_filters is a list with more than one element, one
optimization run will be ran for each element. Each optimization run will continue from the previous. Each
optimization run results must be combined with results of all the previous runs but can be used independently of
the preceeding runs' results. If max_filters is [5, 5, 5] the first 5, 10 and 15 filters can be used
independently.
Args:
max_filters: List of maximum number of filters available for each filter group optimization.
fs: Sampling frequency
Returns:
- **filters:** Numpy array of filters where each row contains one filter fc, Q and gain
- **n_produced:** Actual number of filters produced for each filter group. Calling with [5, 5] max_filters
might actually produce [4, 5] filters meaning that first 4 filters can be used
independently.
- **max_gains:** Maximum gain value of the equalizer frequency response after each filter group
optimization. When using sub-set of filters independently the actual max gain of that
sub-set's frequency response must be applied as a negative digital preamp to avoid
clipping.
"""
if not len(self.equalization):
raise ValueError('Equalization has not been done yet.')
if type(max_filters) != list:
max_filters = [max_filters]
self.parametric_eq = np.zeros(self.frequency.shape)
fc = Q = gain = np.array([])
coeffs_a = coeffs_b = np.empty((0, 3))
n_produced = []
max_gains = []
for n in max_filters:
_eq, rmse, _fc, _Q, _gain, _coeffs_a, _coeffs_b = self.optimize_biquad_filters(
frequency=self.frequency,
target=self.equalization - self.parametric_eq,
max_filters=n,
fs=fs
)
n_produced.append(len(_fc))
# print('RMSE: {:.2f}dB'.format(rmse))
self.parametric_eq += _eq
max_gains.append(np.max(self.parametric_eq))
fc = np.concatenate((fc, _fc))
Q = np.concatenate((Q, _Q))
gain = np.concatenate((gain, _gain))
coeffs_a = np.vstack((coeffs_a, _coeffs_a))
coeffs_b = np.vstack((coeffs_b, _coeffs_b))
filters = np.transpose(np.vstack([fc, Q, gain]))
return filters, n_produced, max_gains
def optimize_fixed_band_eq(self, fc=None, q=None, fs=DEFAULT_FS):
"""Fits multiple fixed Fc and Q biquad filters to equalization curve.
Args:
fc: List of center frequencies for the filters
q: List of Q values for the filters
fs: Sampling frequency
Returns:
- **filters:** Numpy array of filters where each row contains one filter fc, Q and gain
- **n_produced:** Number of filters. Equals to length or inputs.
- **max_gains:** Maximum gain value of the equalizer frequency response.
"""
eq, rmse, fc, Q, gain, coeffs_a, coeffs_b = self.optimize_biquad_filters(
frequency=self.frequency,
target=self.equalization,
fc=fc,
q=q,
fs=fs
)
self.fixed_band_eq = eq
filters = np.transpose(np.vstack([fc, Q, gain]))
return filters, len(fc), np.max(self.fixed_band_eq)
def write_eqapo_parametric_eq(self, file_path, filters, preamp=None):
"""Writes EqualizerAPO Parameteric eq settings to a file."""
file_path = os.path.abspath(file_path)
if preamp is None:
# Calculate preamp from the cascade frequency response
fr = np.zeros(self.frequency.shape)
for filt in filters:
a0, a1, a2, b0, b1, b2 = biquad.peaking(filt[0], filt[1], filt[2], fs=44100)
fr += biquad.digital_coeffs(self.frequency, 44100, a0, a1, a2, b0, b1, b2)
preamp = np.min([0.0, -(np.max(fr) + PREAMP_HEADROOM)])
with open(file_path, 'w', encoding='utf-8') as f:
s = f'Preamp: {preamp:.1f} dB\n'
for i, filt in enumerate(filters):
s += f'Filter {i+1}: ON PK Fc {filt[0]:.0f} Hz Gain {filt[2]:.1f} dB Q {filt[1]:.2f}\n'
f.write(s)
def write_rockbox_10_band_fixed_eq(self, file_path, filters, preamp=None):
"""Writes Rockbox 10 band eq settings to a file."""
file_path = os.path.abspath(file_path)
if preamp is None:
# Calculate preamp from the cascade frequency response
fr = np.zeros(self.frequency.shape)
for filt in filters:
a0, a1, a2, b0, b1, b2 = biquad.peaking(filt[0], filt[1], filt[2], fs=44100)
fr += biquad.digital_coeffs(self.frequency, 44100, a0, a1, a2, b0, b1, b2)
preamp = np.min([0.0, -(np.max(fr) + PREAMP_HEADROOM)])
with open(file_path, 'w', encoding='utf-8') as f:
s = f'eq enabled: on\neq precut: {round(abs(preamp), 1) * 10:.0f}\n'
for i, filt in enumerate(filters):
if i == 0:
s += f'eq low shelf filter: {filt[0]:.0f}, {round(filt[1], 1) * 10:.0f}, {round(filt[2], 1) * 10:.0f}\n'
elif i == len(filters) - 1:
s += f'eq high shelf filter: {filt[0]:.0f}, {round(filt[1], 1) * 10:.0f}, {round(filt[2], 1) * 10:.0f}\n'
else:
s += f'eq peak filter {i}: {filt[0]:.0f}, {round(filt[1], 1) * 10:.0f}, {round(filt[2], 1) * 10:.0f}\n'
f.write(s)
@staticmethod
def _split_path(path):
"""Splits file system path into components."""
folders = []
while 1:
path, folder = os.path.split(path)
if folder != "":
folders.append(folder)
else:
if path != "":
folders.append(path)
break
folders.reverse()
return folders
def minimum_phase_impulse_response(self, fs=DEFAULT_FS, f_res=DEFAULT_F_RES, normalize=True):
"""Generates minimum phase impulse response
Inspired by:
https://sourceforge.net/p/equalizerapo/code/HEAD/tree/tags/1.2/filters/GraphicEQFilter.cpp#l45
Args:
fs: Sampling frequency in Hz
f_res: Frequency resolution as sampling interval. 20 would result in sampling at 0 Hz, 20 Hz, 40 Hz, ...
normalize: Normalize gain to -0.2 dB
Returns:
Minimum phase impulse response
"""
# Double frequency resolution because it will be halved when converting linear phase IR to minimum phase
f_res /= 2
# Interpolate to even sample interval
fr = self.__class__(name='fr_data', frequency=self.frequency.copy(), raw=self.equalization.copy())
# Save gain at lowest available frequency
f_min = np.max([fr.frequency[0], f_res])
interpolator = InterpolatedUnivariateSpline(np.log10(fr.frequency), fr.raw, k=1)
gain_f_min = interpolator(np.log10(f_min))
# Filter length, optimized for FFT speed
n = round(fs // 2 / f_res)
n = next_fast_len(n)
f = np.linspace(0.0, fs // 2, n)
# Run interpolation
fr.interpolate(f, pol_order=1)
# Set gain for all frequencies below original minimum frequency to match gain at the original minimum frequency
fr.raw[fr.frequency <= f_min] = gain_f_min
if normalize:
# Reduce by max gain to avoid clipping with 1 dB of headroom
fr.raw -= np.max(fr.raw)
fr.raw -= PREAMP_HEADROOM
# Minimum phase transformation by scipy's homomorphic method halves dB gain
fr.raw *= 2
# Convert amplitude to linear scale
fr.raw = 10**(fr.raw / 20)
# Zero gain at Nyquist frequency
fr.raw[-1] = 0.0
# Calculate response
ir = firwin2(len(fr.frequency)*2, fr.frequency, fr.raw, fs=fs)
# Convert to minimum phase
ir = minimum_phase(ir, n_fft=len(ir))
return ir
def linear_phase_impulse_response(self, fs=DEFAULT_FS, f_res=DEFAULT_F_RES, normalize=True):
"""Generates impulse response implementation of equalization filter."""
# Interpolate to even sample interval
fr = self.__class__(name='fr_data', frequency=self.frequency, raw=self.equalization)
# Save gain at lowest available frequency
f_min = np.max([fr.frequency[0], f_res])
interpolator = InterpolatedUnivariateSpline(np.log10(fr.frequency), fr.raw, k=1)
gain_f_min = interpolator(np.log10(f_min))
# Run interpolation
fr.interpolate(np.arange(0.0, fs // 2, f_res), pol_order=1)
# Set gain for all frequencies below original minimum frequency to match gain at the original minimum frequency
fr.raw[fr.frequency <= f_min] = gain_f_min
if normalize:
# Reduce by max gain to avoid clipping with 1 dB of headroom
fr.raw -= np.max(fr.raw)
fr.raw -= PREAMP_HEADROOM
# Convert amplitude to linear scale
fr.raw = 10**(fr.raw / 20)
# Calculate response
fr.frequency = np.append(fr.frequency, fs // 2)
fr.raw = np.append(fr.raw, 0.0)
ir = firwin2(len(fr.frequency)*2, fr.frequency, fr.raw, fs=fs)
return ir
def write_readme(self, file_path, max_filters=None, max_gains=None):
"""Writes README.md with picture and Equalizer APO settings."""
file_path = os.path.abspath(file_path)
dir_path = os.path.dirname(file_path)
model = self.name
# Write model
s = '# {}\n'.format(model)
s += 'See [usage instructions](https://github.com/jaakkopasanen/AutoEq#usage) for more options and ' \
'info.\n'
# Add parametric EQ settings
parametric_eq_path = os.path.join(dir_path, model + ' ParametricEQ.txt')
if os.path.isfile(parametric_eq_path) and self.parametric_eq is not None and len(self.parametric_eq):
# Read Parametric eq
with open(parametric_eq_path, 'r', encoding='utf-8') as f:
parametric_eq_str = f.read().strip()
# Filters as Markdown table
filters = []
for line in parametric_eq_str.split('\n'):
if line == '' or line.split()[0] != 'Filter':
continue
filter_type = line[line.index('ON')+3:line.index('Fc')-1]
if filter_type == 'PK':
filter_type = 'Peaking'
if filter_type == 'LS':
filter_type = 'Low Shelf'
if filter_type == 'HS':
filter_type = 'High Shelf'
fc = line[line.index('Fc')+3:line.index('Gain')-1]
gain = line[line.index('Gain')+5:line.index('Q')-1]
q = line[line.index('Q')+2:]
filters.append([filter_type, fc, q, gain])
filters_table_str = tabulate(
filters,
headers=['Type', 'Fc', 'Q', 'Gain'],
tablefmt='orgtbl'
).replace('+', '|').replace('|-', '|:')
max_filters_str = ''
if type(max_filters) == list and len(max_filters) > 1:
n = [0]
for x in max_filters:
n.append(n[-1] + x)
del n[0]
if len(max_filters) > 3:
max_filters_str = ', '.join([str(x) for x in n[:-2]]) + f' or {n[-2]}'
if len(max_filters) == 3:
max_filters_str = f'{n[0]} or {n[1]}'
if len(max_filters) == 2:
max_filters_str = str(n[0])
max_filters_str = f'The first {max_filters_str} filters can be used independently.'
preamp_str = ''
if type(max_gains) == list and len(max_gains) > 1:
if len(max_gains) > 3:
strs = f', '.join([f'{-(x + PREAMP_HEADROOM):.1f} dB' for x in max_gains[:-2]]) + f' or -{max_gains[-2]:.1f} dB'
preamp_str = f'When using independent subset of filters, apply preamp of {strs}, respectively.'
elif len(max_gains) == 3:
preamp_str = f'When using independent subset of filters, apply preamp of ' \
f'{-(max_gains[0] + PREAMP_HEADROOM):.1f} dB ' \
f'or {-(max_gains[1] + PREAMP_HEADROOM):.1f} dB, respectively.'
elif len(max_gains) == 2:
preamp_str = f'When using independent subset of filters, apply preamp of ' \
f'**{-(max_gains[0] + PREAMP_HEADROOM):.1f} dB**.'
s += '''
### Parametric EQs
In case of using parametric equalizer, apply preamp of **{preamp:.1f}dB** and build filters manually
with these parameters. {max_filters_str}
{preamp_str}
{filters_table}
'''.format(
model=model,
preamp=-(max_gains[-1] + PREAMP_HEADROOM),
max_filters_str=max_filters_str,
preamp_str=preamp_str,
filters_table=filters_table_str
)
# Add fixed band eq
fixed_band_eq_path = os.path.join(dir_path, model + ' FixedBandEQ.txt')
if os.path.isfile(fixed_band_eq_path) and self.fixed_band_eq is not None and len(self.fixed_band_eq):
preamp = np.min([0.0, -np.max(self.fixed_band_eq) - PREAMP_HEADROOM])
# Read Parametric eq
with open(fixed_band_eq_path, 'r', encoding='utf-8') as f:
fixed_band_eq_str = f.read().strip()
# Filters as Markdown table
filters = []
for line in fixed_band_eq_str.split('\n'):
if line == '' or line.split()[0] != 'Filter':
continue
filter_type = line[line.index('ON') + 3:line.index('Fc') - 1]
if filter_type == 'PK':
filter_type = 'Peaking'
if filter_type == 'LS':
filter_type = 'Low Shelf'
if filter_type == 'HS':
filter_type = 'High Shelf'
fc = line[line.index('Fc') + 3:line.index('Gain') - 1]
gain = line[line.index('Gain') + 5:line.index('Q') - 1]
q = line[line.index('Q') + 2:]
filters.append([filter_type, fc, q, gain])
filters_table_str = tabulate(
filters,
headers=['Type', 'Fc', 'Q', 'Gain'],
tablefmt='orgtbl'
).replace('+', '|').replace('|-', '|:')
s += '''
### Fixed Band EQs
In case of using fixed band (also called graphic) equalizer, apply preamp of **{preamp:.1f}dB**
(if available) and set gains manually with these parameters.
{filters_table}
'''.format(
model=model,
preamp=preamp,
filters_table=filters_table_str
)
# Write image link
img_path = os.path.join(dir_path, model + '.png')
if os.path.isfile(img_path):
img_url = f'./{os.path.split(img_path)[1]}'
img_url = urllib.parse.quote(img_url, safe="%/:=&?~#+!$,;'@()*[]")
s += '''
### Graphs
![]({})
'''.format(img_url)
# Write file
with open(file_path, 'w', encoding='utf-8') as f:
f.write(re.sub('\n[ \t]+', '\n', s).strip())
@staticmethod
def generate_frequencies(f_min=DEFAULT_F_MIN, f_max=DEFAULT_F_MAX, f_step=DEFAULT_STEP):
freq = []
f = f_min
while f <= f_max:
freq.append(f)
f *= f_step
return np.array(freq)
def interpolate(self, f=None, f_step=DEFAULT_STEP, pol_order=1, f_min=DEFAULT_F_MIN, f_max=DEFAULT_F_MAX):
"""Interpolates missing values from previous and next value. Resets all but raw data."""
# Remove None values
i = 0
while i < len(self.raw):
if self.raw[i] is None:
self.raw = np.delete(self.raw, i)
self.frequency = np.delete(self.frequency, i)
else:
i += 1
# Interpolation functions
keys = 'raw error error_smoothed equalization equalized_raw equalized_smoothed target'.split()
interpolators = dict()
log_f = np.log10(self.frequency)
for key in keys:
if len(self.__dict__[key]):
interpolators[key] = InterpolatedUnivariateSpline(log_f, self.__dict__[key], k=pol_order)
if f is None:
self.frequency = self.generate_frequencies(f_min=f_min, f_max=f_max, f_step=f_step)
else:
self.frequency = np.array(f)
# Prevent log10 from exploding by replacing zero frequency with small value
zero_freq_fix = False
if self.frequency[0] == 0:
self.frequency[0] = 0.001
zero_freq_fix = True
# Run interpolators
log_f = np.log10(self.frequency)
for key in keys:
if len(self.__dict__[key]) and key in interpolators:
self.__dict__[key] = interpolators[key](log_f)
if zero_freq_fix:
# Restore zero frequency
self.frequency[0] = 0
# Everything but the interpolated data is affected by interpolating, reset them
self.reset(**{key: False for key in keys})
def center(self, frequency=1000):
"""Removed bias from frequency response.
Args:
frequency: Frequency which is set to 0 dB. If this is a list with two values then an average between the two
frequencies is set to 0 dB.
Returns:
Gain shifted
"""
equal_energy_fr = self.__class__(name='equal_energy', frequency=self.frequency.copy(), raw=self.raw.copy())