-
Notifications
You must be signed in to change notification settings - Fork 9
/
Asig.py
1687 lines (1521 loc) · 65.4 KB
/
Asig.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
import numbers
from warnings import warn
import logging
from itertools import compress
import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate
import scipy.signal
from scipy.fftpack import fft, fftfreq, ifft
from scipy.io import wavfile
from .Aserver import Aserver
from . import Aspec
from . import Astft
from .helper import ampdb, dbamp, cpsmidi, midicps, linlin, clip, buf_to_float
from .helper import spectrum, audio_from_file
from copy import copy, deepcopy
_LOGGER = logging.getLogger(__name__)
_LOGGER.addHandler(logging.NullHandler())
class Asig:
"""Audio signal class. Asig enables manipulation of audio signals in the style of numpy and more.
Asig offer functions for plotting (via matplotlib) and playing audio (using the pya.Aserver class)
Attributes
----------
sig : numpy.array
Array for the audio signal. Can be mono or multichannel.
sr : int
Sampling rate
label : str
A string label to give the object a unique identifier.
channels : int
Number of channels
cn : list of str, None
cn short for channel names is a list of string of size channels,
to give each channel a unique name.
channel names can be used to subset signal channels in a more readible way,
e.g. asig[:, ['left', 'front']] subsets the left and front channels of the signal.
mix_mode : str or None
used to extend numpy __setitem__() operation to frequent audio manipulations such as
mixing, extending, boundary, replacing. Current Asig supports the mix_modes:
bound, extend, overwrite. mix_mode should not be set directly but is set temporarilty when using
the .bound, .extend and .overwrite properties.
"""
def __init__(self, sig, sr=44100, label="", channels=1, cn=None):
"""__init__ method
Parameters
----------
sig: numpy.array or int or float or str
numpy.array for audio signal, str for filepath, int create x samples of silence,
float creates x seconds of seconds.
sr : int
Sampling rate
label : str
Label for the object
channels : int
Number of channels, no need to set it if you already have a signal for the sig argument.
cn : list or None
A list of channel names, size should match the channels.
"""
self.sr = sr
self.mix_mode = None
self._ = {} # dictionary for further return values
if isinstance(sig, str):
self._load_audio_file(sig)
elif isinstance(sig, int): # sample length
if channels == 1:
self.sig = np.zeros(sig).astype("float32")
else:
self.sig = np.zeros((sig, channels)).astype("float32")
elif isinstance(sig, float): # if float interpret as duration
if channels == 1:
self.sig = np.zeros(int(sig * sr)).astype("float32")
else:
self.sig = np.zeros(
(int(sig * sr), channels)).astype("float32")
else:
self.sig = np.array(sig).astype("float32")
self.label = label
self.cn = cn
self._set_col_names()
@property
def channels(self):
"""Channel property"""
try:
return self.sig.shape[1]
except IndexError:
return 1
@property
def samples(self):
"""Return the length of signal in samples"""
return np.shape(self.sig)[0] # Update it.
@property
def cn(self):
"""Channel names getter"""
return self._cn
@cn.setter
def cn(self, val):
"""Channel names setter"""
if val is None:
self._cn = None
else:
if len(val) == self.channels:
if all(isinstance(x, str) for x in val): # check if all elements are str
self._cn = val
else:
raise TypeError(
"channel names cn need to be a list of string(s).")
else:
raise ValueError(
"list size doesn't match channel numbers {}".format(self.channels))
def _load_audio_file(self, fname):
"""Load audio file, and set self.sig to the signal and self.sr to the sampling rate.
Currently support two types of audio loader: 1) Standard library for .wav, .aiff,
and ffmpeg for other such as .mp3.
Parameters
----------
fname : str
Path to file."""
self.sig, self.sr = audio_from_file(fname)
def save_wavfile(self, fname="asig.wav", dtype='float32'):
"""Save signal as .wav file, return self.
Parameters
----------
fname : str
name of the file with .wav (Default value = "asig.wav")
dtype : str
datatype (Default value = 'float32')
"""
if dtype == 'int16':
data = (self.sig * 32767).astype('int16')
elif dtype == 'int32':
data = (self.sig * 2147483647).astype('int32')
elif dtype == 'uint8':
data = (self.sig * 127 + 128).astype('uint8')
elif dtype == 'float32':
data = self.sig.astype('float32')
scipy.io.wavfile.write(fname, self.sr, data)
return self
def _set_col_names(self):
# Currently, every newly returned asig has a cn argument that is the same as self.
if self.cn is None:
self.cn = [str(i) for i in range(self.channels)]
else:
if isinstance(self.cn[0], str):
self.col_name = {self.cn[i]: i for i in range(len(self.cn))}
else:
raise TypeError("column names need to be a list of strings")
def __getitem__(self, index):
""" Accessing array elements through slicing.
* int, get signal row asig[4];
* slice, range and step slicing asig[4:40:2] # from 4 to 40 every 2 samples;
* list, subset rows, asig[[2, 4, 6]] # pick out index 2, 4, 6 as a new asig
* tuple, row and column specific slicing, asig[4:40, 3:5] # from 4 to 40, channel 3 and 4
* Time slicing (unit in seconds) using dict asig[{1:2.5}, :] creates indexing of 1s to 2.5s.
* Channel name slicing: asig['l'] returns channel 'l' as a new mono asig. asig[['front', 'rear']], etc...
* bool, subset channels: asig[:, [True, False]]
Parameters
----------
index : Number or slice or list or tuple or dict
Slicing argument.
Returns
-------
a : Asig
__getitem__ returns a subset of the self based on the slicing.
"""
if isinstance(index, tuple):
_LOGGER.debug(" getitem: index is tuple")
rindex = index[0]
cindex = index[1] if len(index) > 1 else None
elif isinstance(index, str):
_LOGGER.debug(" getitem: index is string")
# ToDo: decide whether to solve differently, e.g. only via ._[str] or via a .attribute(str) fn
return self._[index]
else: # if only slice, list, dict, int or float given for row selection
rindex = index
cindex = None
# parse row index rindex into ridx
# e.g. a[[4,5,7,8,9]], or a[[True, False, True...]]
if isinstance(rindex, list):
_LOGGER.debug("list slicing of index.")
ridx = rindex
sr = self.sr
elif isinstance(rindex, int): # picking a single row
ridx = rindex
_LOGGER.debug("integer slicing of index: %d", ridx)
sr = self.sr
elif isinstance(rindex, slice):
_LOGGER.debug(" getitem: row index is slice.")
_, _, step = rindex.indices(len(self.sig))
sr = int(self.sr / abs(step))
ridx = rindex
elif isinstance(rindex, dict): # time slicing
_LOGGER.debug(" getitem: row index is dict. Time slicing.")
for key, val in rindex.items():
try:
start = int(key * self.sr)
except TypeError: # if it is None
start = None
try:
stop = int(val * self.sr)
except TypeError:
stop = None
ridx = slice(start, stop, 1)
sr = self.sr
_LOGGER.debug("Time slicing, start: %s, stop: %s",
str(start), str(stop))
else: # Dont think there is a usecase.
ridx = rindex
sr = self.sr
# now parse cindex
if isinstance(cindex, list):
_LOGGER.debug(" getitem: column index is list.")
if isinstance(cindex[0], str):
cidx = [self.col_name.get(s) for s in cindex]
if cidx is None:
_LOGGER.error("Input column names does not exist")
cn_new = [self.cn[i]
for i in cidx] if self.cn is not None else None
elif isinstance(cindex[0], bool):
cidx = cindex
cn_new = list(compress(self.cn, cindex))
elif isinstance(cindex[0], int):
cidx = cindex
cn_new = [self.cn[i]
for i in cindex] if self.cn is not None else None
elif isinstance(cindex, int):
_LOGGER.debug(" getitem: column index is int.")
cidx = cindex
cn_new = [self.cn[cindex]] if self.cn is not None else None
elif isinstance(cindex, slice):
_LOGGER.debug(" getitem: column index is slice.")
cidx = cindex
cn_new = self.cn[cindex] if self.cn is not None else None
# if only a single channel name is given.
elif isinstance(cindex, str):
_LOGGER.debug(" getitem: column index is string.")
cidx = self.col_name.get(cindex)
cn_new = [cindex]
else: # if nothing is given, e.g. index = (ridx,) on calling a[:]
cidx = slice(None, None, None)
cn_new = self.cn
# apply ridx and cidx and return result
sig = self.sig[ridx, cidx] if self.channels > 1 else self.sig[ridx]
# Squeezing shouldn't be performed here.
# this is because: a[:10, 0] and a[:10,[True, False]] return
# (10,) and (10, 1) respectively. Which should be dealt with individually.
if sig.ndim == 2 and sig.shape[1] == 1:
# Hot fix this to be consistent with bool slciing
if not isinstance(cindex[0], bool):
_LOGGER.debug(
"ndim is 2 and channel num is 1, performa np.squeeze")
sig = np.squeeze(sig)
if isinstance(sig, numbers.Number):
_LOGGER.debug("signal is scalar, convert to array")
sig = np.array(sig)
a = Asig(sig, sr=sr, label=self.label + '_arrayindexed', cn=cn_new)
a.mix_mode = self.mix_mode
return a
# new setitem implementation (TH): in analogy to new __getitem__ and with mix modes
# work in progress
@property
def x(self):
"""Extend mode: this mode allows destination sig size in assignment to be extended through setitem"""
# Set setitem mode to extend
self.mix_mode = 'extend'
return self
extend = x # better readable synonym
@property
def b(self):
"""Bound mode: this mode allows to truncate a source signal in assignment to a limited destination in setitem."""
# Set setitem mode to bound
self.mix_mode = 'bound'
return self
bound = b # better readable synonym
@property
def o(self):
"""Overwrite mode: this mode cuts and replaces target selection by source signal on assignment via setitem"""
self.mix_mode = 'overwrite'
return self
overwrite = o
def __setitem__(self, index, value):
"""setitem: asig[index] = value. This allows all the methods from getitem:
* numpy style slicing
* string/string_list slicing for subsetting channels based on channel name self.cn
* time slicing (unit seconds) via dict.
* bool slicing to filter out specific channels.
In addition, there are 4 possible modes: (referring to asig as 'dest', and value as 'src'
1. standard pythonic way that the src und dest dimensions need to match
asig[...] = value
2. bound mode where src is copied up to the bounds of dest
asig.b[...] = value
3. extend mode where dest is dynamically extended to make space for src
asig.x[...] = value
4. overwrite mode where selected dest subset is replaced by specified src regardless the length.
asig.o[...] = value
row index:
* list: e.g. [1,2,3,4,5,6,7,8] or [True, ..., False] (modes b and x possible)
* int: e.g. 0 (i.e. a single sample, so no need for extra modes)
* slice: e.g. 100:5000:2 (can be used with all modes)
* dict: e.g. {0.5: 2.5} (modes o, b possible, x only if step==1, or if step==None and stop=None)
Parameters
----------
index : Number or slice or list or tuple or dict
Slicing argument.
value : Asig or numpy.ndarray or list
value to set
Returns
-------
_: Asig
Updated asig
"""
# TODOs:
# check if mix_mode copy required on each fn output: if yes implement
# check all sig = [[no numpy array]] cases
# a.x[300:,1:2] = 0.5*b with 1-ch b to 4-ch a: shape problem (600, ) to (600, 1)
mode = self.mix_mode
self.mix_mode = None # reset when done
if isinstance(index, tuple):
rindex = index[0]
cindex = index[1] if len(index) > 1 else None
else: # if only slice, list, dict, int or float given for row selection
rindex = index
cindex = None
# parse row index rindex into ridx
# sr = self.sr # unused default case for conversion if not changed by special case
# e.g. a[[4,5,7,8,9]], or a[[True, False, True...]]
if isinstance(rindex, list):
ridx = rindex
elif isinstance(rindex, int): # picking a single row
ridx = rindex
elif isinstance(rindex, slice):
# _, _, step = rindex.indices(len(self.sig))
# sr = int(self.sr / abs(step)) # This is unused.
ridx = rindex
elif isinstance(rindex, dict): # time slicing
for key, val in rindex.items():
try:
start = int(key * self.sr)
except TypeError: # if it is None
start = None
try:
stop = int(val * self.sr)
except TypeError:
stop = None
ridx = slice(start, stop, 1)
else: # Dont think there is a usecase.
ridx = rindex
# now parse cindex
if isinstance(cindex, list):
if isinstance(cindex[0], str):
cidx = [self.col_name.get(s) for s in cindex]
cidx = cidx[0] if len(cidx) == 1 else cidx # hotfix for now.
elif isinstance(cindex[0], bool):
cidx = cindex
elif isinstance(cindex[0], int):
cidx = cindex
# int, slice are the same.
elif isinstance(cindex, int) or isinstance(cindex, slice):
cidx = cindex
# if only a single channel name is given.
elif isinstance(cindex, str):
cidx = self.col_name.get(cindex)
else:
cidx = slice(None)
# cidx = None
_LOGGER.debug("self.sig.ndim == %d", self.sig.ndim)
if self.sig.ndim == 1:
final_index = (ridx)
else:
final_index = (ridx, cidx)
# apply setitem: set dest[ridx,cidx] = src return self
if isinstance(value, Asig):
_LOGGER.debug("value is asig")
src = value.sig
elif isinstance(value, np.ndarray): # numpy array if not Asig, default: sr fits
_LOGGER.debug("value is ndarray")
src = value
elif isinstance(value, list): # if list
_LOGGER.debug("value is list")
src = value
# for list (assume values for channels), mode makes no sense...
mode = None
# TODO: check if useful behavior also for numpy arrays
else:
_LOGGER.debug("value not asig, ndarray, list")
src = value
mode = None # for scalar types, mode makes no sense...
if mode is None:
_LOGGER.debug("Default setitem mode")
if isinstance(src, numbers.Number):
self.sig[final_index] = src
elif isinstance(src, list): # for multichannel signals that is value for each column
self.sig[final_index] = src
else: # numpy.ndarray
try:
self.sig[final_index] = np.broadcast_to(
src, self.sig[final_index].shape)
except ValueError:
self.sig[final_index] = src
elif mode == 'bound':
_LOGGER.debug("setitem bound mode")
dshape = self.sig[final_index].shape
dn = dshape[0] # ToDo: howto get that faster from ridx alone?
sn = src.shape[0]
if sn > dn:
self.sig[final_index] = src[:dn] if len(
dshape) == 1 else src[:dn, :]
else:
self.sig[final_index][:sn] = src if len(
dshape) == 1 else src[:, :]
elif mode == 'extend':
_LOGGER.debug("setitem extend mode")
if isinstance(ridx, list):
_LOGGER.error(
"Asig.setitem Error: extend mode not available for row index list")
return self
if isinstance(ridx, slice):
if ridx.step not in [1, None]:
raise AttributeError("Asig.setitem Error: extend mode only available for step-1 slices")
if ridx.stop is not None and ridx.stop < self.samples:
raise AttributeError("Extend mode is meant for extending array beyond the end. The current slice does not stop at the end of array.")
dshape = self.sig[final_index].shape # d for destination
# ToDo: howto compute dn faster from ridx shape(self.sig) alone?
dn = dshape[0]
sn = src.shape[0]
if sn <= dn: # same as bound, since src fits in
self.sig[final_index][:sn] = np.broadcast_to(
src, (sn,) + dshape[1:])
elif sn > dn:
self.sig[final_index] = src[:dn]
# now extend by nn = sn-dn additional rows
if dn > 0:
nn = sn - dn # nr of needed additional rows
self.sig = np.r_[self.sig, np.zeros(
(nn,) + self.sig.shape[1:])]
if self.sig.ndim == 1:
self.sig[-nn:] = src[dn:]
else:
self.sig[-nn:, cidx] = src[dn:]
else: # this is when start is beyond length of dest...
nn = ridx.start + sn
self.sig = np.r_[
self.sig, np.zeros((nn - self.sig.shape[0],) + self.sig.shape[1:])]
if self.sig.ndim == 1:
self.sig[-sn:] = src
else:
self.sig[-sn:, cidx] = src
elif mode == 'overwrite':
# This mode is to replace a subset with an any given shape.
# Where the end point of the newly insert signal should be.
_LOGGER.info("setitem overwrite mode")
start_idx = ridx.start if isinstance(
ridx, slice) else 0 # Start index of the ridx,
stop_idx = ridx.stop if isinstance(
ridx, slice) else 0 # Stop index of the rdix
end = start_idx + src.shape[0]
# Create a new signal
# New row is: original samples + (new_signal_sample - the range to be replace)
sig = np.ndarray(shape=(
self.sig.shape[0] + src.shape[0] - (stop_idx - start_idx), self.channels))
if sig.ndim == 2 and sig.shape[1] == 1:
sig = np.squeeze(sig)
if isinstance(sig, numbers.Number):
sig = np.array(sig)
sig[:start_idx] = self.sig[:start_idx] # Copy the first part over
# The second part is the new signal
sig[start_idx:end] = src
# The final part is the remaining of self.sig
sig[end:] = self.sig[stop_idx:]
self.sig = sig # Update self.sig
return self
def resample(self, target_sr=44100, rate=1, kind='linear'):
"""Resample signal based on interpolation, can process multichannel signals.
Parameters
----------
target_sr : int
Target sampling rate (Default value = 44100)
rate : float
Rate to speed up or slow down the audio (Default value = 1)
kind : str
Type of interpolation (Default value = 'linear')
Returns
-------
_ : Asig
Asig with resampled signal.
"""
times = np.arange(self.samples) / self.sr
tsel = np.arange(np.floor(self.samples / self.sr * target_sr / rate)) * rate / target_sr
if self.channels == 1:
interp_fn = scipy.interpolate.interp1d(times, self.sig, kind=kind, assume_sorted=True,
bounds_error=False, fill_value=self.sig[-1])
return Asig(interp_fn(tsel), target_sr,
label=self.label + "_resampled", cn=self.cn)
else:
new_sig = np.ndarray(
shape=(int(self.samples / self.sr * target_sr / rate), self.channels))
for i in range(self.channels):
interp_fn = scipy.interpolate.interp1d(
times, self.sig[:, i], kind=kind, assume_sorted=True,
bounds_error=False, fill_value=self.sig[-1, i])
new_sig[:, i] = interp_fn(tsel)
return Asig(new_sig, target_sr, label=self.label + "_resampled", cn=self.cn)
def play(self, rate=1, **kwargs):
"""Play Asig audio via Aserver, using Aserver.default (if existing)
kwargs are propagated to Aserver:play(onset=0, out=0)
Parameters
----------
rate : float
Playback rate (Default value = 1)
**kwargs : str
'server' : Aserver
Set which server to play. e.g. s = Aserver(); s.boot(); asig.play(server=s)
Returns
-------
_ : Asig
return self
"""
if 'server' in kwargs.keys():
s = kwargs['server']
else:
s = Aserver.default
if not isinstance(s, Aserver):
warn("Asig.play: no default server running, nor server arg specified.")
return self
if rate == 1 and self.sr == s.sr:
asig = self
else:
asig = self.resample(s.sr, rate)
s.play(asig, **kwargs)
return self
def shift_channel(self, shift=0):
"""Shift signal to other channels. This is particular useful for assigning a mono signal to a specific channel.
* shift = 0: does nothing as the same signal is being routed to the same position
* shift > 0: shift channels of self.sig 'right', i.e. from [0,..channels-1] to channels [shift,shift+1,...]
* shift < 0: shift channels of self.sig 'left', i.e. the first shift channels will be discarded.
Parameters
----------
shift : int
shift channel amount (Default value = 0)
Returns
-------
_ : Asig
Rerouted asig
"""
if isinstance(shift, int):
# not optimized method here
new_sig = np.zeros((self.samples, shift + self.channels))
_LOGGER.debug("Shift by %d, new signal has %d channels",
shift, new_sig.shape[1])
if self.channels == 1:
new_sig[:, shift] = self.sig
elif shift > 0:
new_sig[:, shift:(shift + self.channels)] = self.sig
elif shift < 0:
new_sig[:] = self.sig[:, -shift:]
if self.cn is None:
new_cn = self.cn
else:
if shift > 0:
uname_list = ['unnamed' for i in range(shift)]
if isinstance(self.cn, list):
new_cn = uname_list + self.cn
else:
new_cn = uname_list.append(self.cn)
elif shift < 0:
new_cn = self.cn[-shift:]
return Asig(new_sig, self.sr, label=self.label + '_routed', cn=new_cn)
else:
raise AttributeError("Argument needs to be int")
def mono(self, blend=None):
"""Mix channels to mono signal. Perform sig = np.sum(self.sig_copy * blend, axis=1)
Parameters
----------
blend : list
list of gain for each channel as a multiplier.
Do nothing if signal is already mono, raise warning (Default value = None)
Returns
-------
_ : Asig
A mono Asig object
"""
if self.channels == 1:
warn("Signal is already mono")
return self
if blend is None:
blend = np.ones(self.channels) / self.channels
if len(blend) != self.channels:
raise AttributeError("len(blend) != self.channels")
else:
sig = np.sum(self.sig * blend, axis=1)
col_names = [
self.cn[np.argmax(blend)]] if self.cn is not None else None
return Asig(sig, self.sr, label=self.label + '_blended', cn=col_names)
def stereo(self, blend=None):
"""Blend all channels of the signal to stereo. Applicable for any single-/ or multi-channel Asig.
Parameters
----------
blend : list or None
Usage: For mono signal, blend=(g1, g2), the mono channel will be broadcated to left, right with g1, g2 gains.
For stereo signal, blend=(g1, g2), each channel is gain adjusted by g1, g2.
For multichannel: blend = [[list of gains for left channel], [list of gains for right channel]]
Default value = None, resulting in equal distribution to left and right channel
Example
-------
asig[:,['c1','c2','c3']].stereo[[1, 0.707, 0], [0, 0.707, 1]]
mixes channel 'c1' to left, 'c2' to center and 'c3' to right channel
of a new stereo asig. Note that for equal loudness left**2+right**2=1 should be used
Returns
-------
_ : Asig
A stereo Asig object
"""
if blend is None:
left = 1
right = 1
else:
left = blend[0]
right = blend[1]
if self.channels == 1:
left_sig = self.sig * left
right_sig = self.sig * right
elif self.channels == 2:
left_sig = self.sig[:, 0] * left
right_sig = self.sig[:, 1] * right
else:
if len(left) == self.channels and len(right) == self.channels:
left_sig = np.sum(self.sig * left, axis=1)
right_sig = np.sum(self.sig * right, axis=1)
else:
msg = """For signal channels > 2, argument blend should be a tuple of two lists,
each list contains the gain for each channel to be mixed.
"""
raise AttributeError(msg)
sig = np.stack((left_sig, right_sig), axis=1)
return Asig(sig, self.sr, label=self.label + '_to_stereo', cn=['l', 'r'])
def rewire(self, dic):
"""Rewire channels to flexibly allow weighted channel permutations.
Parameters
----------
dic : dict
key = tuple of (source channel, destination channel)
value = amplitude gain
Example
-------
{(0, 1): 0.2, (5, 0): 0.4}: rewire channel 0 to 1 with gain 0.2, and 5 to 1 with gain 2
leaving other channels unmodified
Returns
-------
_ : Asig
Asig with rewired channels..
"""
max_ch = max(dic, key=lambda x: x[1])[1] + 1
if max_ch > self.channels:
new_sig = np.zeros((self.samples, max_ch))
new_sig[:, :self.channels] = np.copy(self.sig)
else:
new_sig = np.copy(self.sig)
for key, val in dic.items():
new_sig[:, key[1]] = self.sig[:, key[0]] * val
return Asig(new_sig, self.sr, label=self.label + '_rewire', cn=self.cn)
def pan2(self, pan=0.):
"""Stereo panning of asig to a stereo output.
Panning is based on constant power panning, see pan below
Behavior depends on nr of channels self.channels
* multi-channel signals (self.channels>2) are cut back to stereo and treated as
* stereo signals (self.channels==2) are channelwise attenuated using cos(angle), sin(angle)
* mono signals (self.channels==1) result in stereo output asigs.
Parameters
----------
pan : float
panning between -1. (left) to 1. (right) (Default value = 0.)
Returns
-------
_ : Asig
Asig
"""
if isinstance(pan, float) or isinstance(pan, int):
# Stereo panning.
if pan <= 1. and pan >= -1.:
angle = linlin(pan, -1, 1, 0, np.pi / 2.)
gain = [np.cos(angle), np.sin(angle)]
if self.channels == 1:
# This is actually quite slow
newsig = np.repeat(self.sig, 2)
newsig_shape = newsig.reshape(-1, 2) * gain
new_cn = [str(self.cn), str(self.cn)]
return Asig(newsig_shape, self.sr,
label=self.label + "_pan2ed", channels=2, cn=new_cn)
else:
return Asig(self.sig[:, :2] * gain, self.sr, label=self.label + "_pan2ed", cn=self.cn)
else:
raise ValueError("Panning need to be in the range -1. to 1.")
else:
raise TypeError("pan needs to be a float number between -1. to 1.")
def remove_DC(self):
"""remove DC offset
Parameters
----------
none
Returns
-------
_ : Asig
channelwise DC-free Asig.
"""
sig = self.sig - np.mean(self.sig, 0)
return Asig(sig, sr=self.sr, label=self.label + "_DCfree", cn=self.cn)
def norm(self, norm=1, in_db=False, dcflag=False):
# ToDO add channel_wise argument . default True, currently it is the false.
"""Normalize signal
Parameters
----------
norm : float
normalize threshold (Default value = 1)
in_db : bool
Normally, norm takes amplitude, if in_db, norm's unit is in dB.
dcflag : bool
If true, remove DC offset (Default value = False)
Returns
-------
_ : Asig
normalized Asig.
"""
if in_db:
norm = dbamp(norm)
if dcflag:
sig = self.sig - np.mean(self.sig, 0)
else:
sig = self.sig
sig = norm * sig / np.max(np.abs(sig), 0)
return Asig(sig, self.sr, label=self.label + "_normalised", cn=self.cn)
def gain(self, amp=None, db=None):
"""Apply gain in amplitude or dB, only use one or the other arguments. Argument can be either a scalar
or a list (to apply individual gain to each channel). The method returns a new asig with gain applied.
Parameters
----------
amp : float or None
Amplitude (Default value = None)
db : float or int or None
Decibel (Default value = None)
Returns
-------
_ : Asig
Gain adjusted Asig.
"""
if (db is not None and amp is not None):
raise AttributeError("Both amp and db are set, use one only.")
elif db is not None: # overwrites amp
amp = dbamp(db)
elif amp is None: # default 1 if neither is given
amp = 1
return Asig(self.sig * amp, self.sr, label=self.label + "_scaled", cn=self.cn)
def rms(self, axis=0):
"""Return signal's RMS
Parameters
----------
axis : int
Axis to perform np.mean() on (Default value = 0)
Returns
-------
_ : float
RMS value
"""
return np.sqrt(np.mean(np.square(self.sig), axis))
def plot(self, fn=None, offset=0, scale=1, xlim=None, ylim=None, **kwargs):
"""Display signal graph
Parameters
----------
fn : func or None
Keyword or function (Default value = None)
offset : int or float
Offset each channel to create a stacked view (Default value = 0)
scale : float
Scale the y value (Default value = 1)
xlim : tuple or list
x axis range (Default value = None)
ylim : tuple or list
y axis range (Default value = None)
**kwargs :
keyword arguments for matplotlib.pyplot.plot()
Returns
-------
_ : Asig
self, you can use plt.show() to display the plot.
"""
if fn:
if fn == 'db':
def fn(x):
return np.sign(x) * ampdb((abs(x) * 2 ** 16 + 1))
elif not callable(fn):
raise AttributeError("Asig.plot: fn is neither keyword nor function")
plot_sig = fn(self.sig)
else:
plot_sig = self.sig
if self.channels == 1 or (offset == 0 and scale == 1):
self._['plot'] = plt.plot(
np.arange(0, self.samples) / self.sr, plot_sig, **kwargs)
else:
p = []
ts = np.linspace(0, self.samples / self.sr, self.samples)
for i, c in enumerate(self.sig.T):
p.append(plt.plot(ts, i * offset + c * scale, **kwargs))
plt.xlabel("time [s]")
if self.cn:
plt.text(0, (i + 0.1) * offset, self.cn[i])
if xlim is not None:
plt.xlim([xlim[0], xlim[1]])
if ylim is not None:
plt.ylim([ylim[0], ylim[1]])
return self
def get_duration(self):
"""Return the duration in second."""
return self.samples / self.sr
def get_times(self):
"""Get time stamps for left-edge of sample-and-hold-signal"""
return np.linspace(0, (self.samples - 1) / self.sr, self.samples)
def __eq__(self, other):
"""Check if two asig objects have the same signal. But does not care about sr and others"""
sig_eq = np.array_equal(self.sig, other.sig)
sr_eq = self.sr == other.sr
return sig_eq and sr_eq
def __repr__(self):
"""Report key attributes"""
return "Asig('{}'): {} x {} @ {}Hz = {:.3f}s cn={}".format(
self.label, self.channels, self.samples, self.sr, self.samples / self.sr,
self.cn)
def __mul__(self, other):
"""Magic method for multiplying. You can either multiply a scalar or an Asig object. If muliplying an Asig,
you don't always need to have same size arrays as audio signals may different in length. If mix_mode
is set to 'bound' the size is fixed to respect self. If not, the result will respect to whichever the
bigger array is."""
selfsig = self.sig
othersig = other.sig if isinstance(other, Asig) else other
if isinstance(othersig, numbers.Number):
return Asig(selfsig * othersig, self.sr, label=self.label + "_multiplied", cn=self.cn)
else:
if self.mix_mode == 'bound':
if selfsig.shape[0] > othersig.shape[0]:
selfsig = selfsig[:othersig.shape[0]]
elif selfsig.shape[0] < othersig.shape[0]:
othersig = othersig[:selfsig.shape[0]]
result = selfsig * othersig
self.mix_mode = None
elif self.mix_mode == 'extend':
if selfsig.shape[0] > othersig.shape[0]:
result = selfsig.copy()
result[:othersig.shape[0]] *= othersig
elif selfsig.shape[0] < othersig.shape[0]:
result = othersig.copy() # might not be deep enough.
result[:selfsig.shape[0]] *= selfsig
else:
result = selfsig * othersig
else:
result = selfsig * othersig
return Asig(result, self.sr, label=self.label + "_multiplied", cn=self.cn)
def __rmul__(self, other):
return Asig(self.sig * other, self.sr, label=self.label + "_multiplied", cn=self.cn)
def __truediv__(self, other):
"""Magic method for division. You can either divide a scalar or an Asig object.
Use division with caution, audio signal is common to reach 0 or near, avoid zero division or extremely large result.
If dividing an Asig, you don't always need to have same size arrays as audio signals
may different in length. If mix_mode is set to 'bound' the size is fixed to respect self.
If not, the result will respect to whichever the bigger array is."""
selfsig = self.sig
othersig = other.sig if isinstance(other, Asig) else other
if isinstance(othersig, numbers.Number):
return Asig(selfsig / othersig, self.sr, label=self.label + "_multiplied", cn=self.cn)
else:
if self.mix_mode == 'bound':
if selfsig.shape[0] > othersig.shape[0]:
selfsig = selfsig[:othersig.shape[0]]
elif selfsig.shape[0] < othersig.shape[0]:
othersig = othersig[:selfsig.shape[0]]
result = selfsig / othersig
self.mix_mode = None
elif self.mix_mode == 'extend':
if selfsig.shape[0] > othersig.shape[0]:
result = selfsig.copy()
result[:othersig.shape[0]] /= othersig
elif selfsig.shape[0] < othersig.shape[0]:
# a / b = 1 / (b/a)
result = othersig.copy() # might not be deep enough.
result[:selfsig.shape[0]] /= selfsig
result = 1. / result
else:
result = selfsig / othersig
else:
result = selfsig / othersig
return Asig(result, self.sr, label=self.label + "_divided", cn=self.cn)
def __rtruediv__(self, other):
return Asig(other / self.sig, self.sr, label=self.label + "_divided", cn=self.cn)
def __add__(self, other):
"""Magic method for adding. You can either add a scalar or an Asig object. If adding an Asig,
you don't always need to have same size arrays as audio signals may different in length. If mix_mode
is set to 'bound' the size is fixed to respect self. If not, the result will respect to whichever the
bigger array is."""
selfsig = self.sig
othersig = other.sig if isinstance(other, Asig) else other
if isinstance(othersig, numbers.Number): # When other is just a scalar
return Asig(selfsig + othersig, self.sr, label=self.label + "_added", cn=self.cn)
else:
if self.mix_mode == 'bound':
try:
if selfsig.shape[0] > othersig.shape[0]:
selfsig = selfsig[:othersig.shape[0]]
elif selfsig.shape[0] < othersig.shape[0]: