-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
1519 lines (1212 loc) · 50.5 KB
/
utils.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
# Utility function module for AI VJ
import time as _time
from time import sleep
import datetime
import os
from os.path import isfile
import ast
from shutil import copyfile, copy
import sys
from timeit import default_timer as timer
import ast
import glob
import pickle
import json
from pprint import pprint
import numpy as np
from numpy import array, random, arange, float32, float64, zeros
import pandas as pd
import matplotlib.pyplot as plt
import librosa
import librosa.display
from librosa.feature import melspectrogram
#import pyaudio
#from pyaudio import PyAudio, paContinue, paFloat32
import sounddevice as sd
from collections import Counter
from pythonosc import osc_message_builder
from pythonosc import udp_client
import theano
#from train_network import build_model
import keras
#from keras import backend as K
#from keras.layers import Convolution2D, MaxPooling2D, Flatten, AveragePooling2D, ZeroPadding2D
from keras import backend; backend.set_image_dim_ordering('th')
from keras.layers import Conv2D, MaxPooling2D, Flatten, AveragePooling2D, ZeroPadding2D
from keras.models import Sequential, Model
from keras.layers import Input, Dense, TimeDistributed, LSTM, Dropout, Activation
from keras.layers.normalization import BatchNormalization
from keras.layers.advanced_activations import ELU, LeakyReLU
from keras.callbacks import ModelCheckpoint
from keras import backend
from keras import metrics
from keras.utils import np_utils
from keras.optimizers import Adam
from keras.optimizers import SGD
from keras.callbacks import ModelCheckpoint
from keras import optimizers
from sklearn.metrics import classification_report, accuracy_score
from sklearn.preprocessing import normalize
from sklearn.metrics import matthews_corrcoef
from sklearn.metrics import hamming_loss, coverage_error, label_ranking_average_precision_score, label_ranking_loss
from numpy import array, random, arange, float32, float64, zeros
import matplotlib.pyplot as plt
import sounddevice as sd
#import OSC
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
sys.path.append(module_path)
################################
# constants
################################
fs = 16000 # Hz
threshold = 0.8 # absolute gain
delay = 40 # samples
signal_length = 30 # second
release_coeff = 0.5555 # release time factor
attack_coeff = 0.5 # attack time factor
dtype = float32 # default data type
block_length = 1024 # samples
best_threshold = [ 0.2, 0.1, 0.2, 0.1, 0.4, 0.1 , 0.1, 0.1, 0.1, 0.1 , 0.2 , 0.2, 0.1, 0.2, 0.1,
0.1 , 0.3, 0.2 , 0.2 , 0.2 , 0.3 , 0.2 , 0.1 , 0.1 , 0.2 , 0.1 , 0.1, 0.1 , 0.2, 0.6,
0.2, 0.2 , 0.1 , 0.2 , 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.3, 0.2, 0.2,
0.5, 0.2, 0.1 ,0.2, 0.1]
top_50 = ['rock', 'pop', 'alternative', 'indie', 'electronic', 'female vocalists',
'dance', '00s', 'alternative rock', 'jazz', 'beautiful', 'metal',
'chillout', 'male vocalists', 'classic rock', 'soul', 'indie rock',
'Mellow', 'electronica', '80s', 'folk', '90s', 'chill', 'instrumental',
'punk', 'oldies', 'blues', 'hard rock', 'ambient', 'acoustic', 'experimental',
'female vocalist', 'guitar', 'Hip-Hop', '70s', 'party', 'country', 'easy listening',
'sexy', 'catchy', 'funk', 'electro' ,'heavy metal', 'Progressive rock',
'60s', 'rnb', 'indie pop', 'sad', 'House', 'happy']
color_labels = ['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple', 'magenta', 'red']
color_labels_encoding = ['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple', 'magenta']
speed_range_scaled = [0, 34, 67, 101]
speed_labels = ['slow', 'medium', 'fast']
speed_unencode = [0.2, 0.5, 0.8]
color_unencode = [0.0, 0.08, 0.15, 0.35, 0.48, 0.67, 0.76, 0.84]
effect_unencode = [0.0, 0.3, 0.6, 0.9]
boundary_range_scaled = np.array([0, 20, 45, 75, 150, 200, 255, 285, 330, 361])
boundary_range = boundary_range_scaled/360.
patterns_full = ['AskewPlanes', 'Balance', 'Ball', 'BassPod', 'Blank', 'Bubbles', 'CrossSections', 'CubeEQ',
'CubeFlash', 'Noise', 'Palette', 'Pong', 'Rings', 'ShiftingPlane', 'SoundParticles', 'SpaceTime',
'Spheres', 'StripPlay', 'Swarm', 'Swim', 'TelevisionStatic', 'Traktor', 'ViolinWave']
patterns_reduced = ['AskewPlanes', 'Balance', 'CrossSections', 'CubeEQ',
'CubeFlash', 'Noise', 'Pong', 'Rings', 'ShiftingPlane', 'SoundParticles', 'SpaceTime',
'Spheres', 'StripPlay', 'Swarm', 'Swim', 'Traktor', 'ViolinWave']
effect_labels = ['low', 'medium', 'high']
effect_labels_full = [None, 'low', 'medium', 'high']
brightness_labels = ['off', 'half', 'full']
param_labels = ['Faster', 'Hue Variation', 'Sparkle', 'Crazy', 'Larger']
param_labels_full = [None, 'Faster', 'Hue Variation', 'Sparkle', 'Crazy', 'Larger']
################################
# general
################################
def explore_music_data(X_data, start_row, end_row, vertical_mean=False):
for i in range(start_row, end_row):
print('mean:' , X_data[i].mean())
print('max:' , X_data[i].max())
print('min:' , X_data[i].min())
print('std:', X_data[i].std())
print('var:', X_data[i].var())
if vertical_mean:
print('vert mean:', X_data[i].mean(axis=2))
def set_sounddevices(sd):
for index, device in enumerate(sd.query_devices()):
#print device['name']
#print index
if device['name'] == 'Soundflower (2ch)':
print('Soundflower 2ch found at index: ', index)
sd.default.device[0] = index
if device['name'] == 'Built-in Output':
print('Built-in output found at index: ', index)
sd.default.device[1] = index
print('\n \n \n')
print(sd.default.device)
print(sd.query_devices())
return sd
def encode_classes(class_name, class_names):
# makes a "one-hot" vector for each class - Multi-class implementation
vec = np.zeros(len(class_names))
for classes in class_name:
print(classes)
try:
idx = class_names.index(classes)
#vec = np.zeros(len(class_names))
vec[idx] = 1
except ValueError:
return None
return vec
def encode_class(class_name, class_names):
# makes a "one-hot" vector for each class name - Single class implementation
try:
idx = class_names.index(class_name)
vec = np.zeros(len(class_names))
vec[idx] = 1
return vec
except ValueError:
return None
def get_spec_from_mp3(audio_path):
#audio_path = '/Users/aaronopp/Downloads/440Hz_44100Hz_16bit_05sec.mp3'
#try:
aud, sr = librosa.load(audio_path, mono=True, sr=16000)
# print('samplerate:', sr)
melgram = librosa.power_to_db(librosa.feature.melspectrogram(aud, sr=sr, n_mels=96, n_fft=512, hop_length=256),ref=1.0)[np.newaxis,np.newaxis,:,:]
return melgram
def graph_MS(data, line):
if data.ndim == 4:
S = data[line].reshape(data[line].shape[1:])
if data.ndim == 3:
S = data[line].reshape(data[line].shape[0:])
else:
S = data
print(S.shape)
plt.figure(figsize=(10, 4))
librosa.display.specshow(librosa.power_to_db(S,
ref=np.max),
sr=16000, hop_length=256, y_axis='mel', fmax=8000,
x_axis='time')
plt.colorbar(format='%+2.0f dB')
plt.title('Mel spectrogram')
plt.tight_layout()
def graph_MS_non_notebook(data, line):
if data.ndim == 4:
S = data[line].reshape(data[line].shape[1:])
if data.ndim == 3:
S = data[line].reshape(data[line].shape[0:])
else:
S = data
print(S.shape)
plt.figure(figsize=(10, 4))
librosa.display.specshow(librosa.power_to_db(S,
ref=np.max),
sr=16000, hop_length=256, y_axis='mel', fmax=8000,
x_axis='time')
plt.colorbar(format='%+2.0f dB')
plt.title('Mel spectrogram')
plt.tight_layout()
plt.show()
def graph_MS_44k(data, line):
S = data[line].reshape(data[line].shape[1:])
print(S.shape)
plt.figure(figsize=(10, 4))
librosa.display.specshow(librosa.power_to_db(S,
ref=np.max),
sr=44100, hop_length=256, y_axis='mel', fmax=8000,
x_axis='time')
plt.colorbar(format='%+2.0f dB')
plt.title('Mel spectrogram')
plt.tight_layout()
def reshape_4_to_2(data, line):
S = data[line].reshape(data[line].shape[1:])
return S
def get_mel_spectrogram(aud):
melgram = librosa.power_to_db(librosa.feature.melspectrogram(aud, sr=16000, n_mels=96, n_fft=512, hop_length=256),ref=1.0)[np.newaxis,np.newaxis,:,:]
return melgram
def unencode_and_list(data, data_labels):
from collections import Counter
print('data length: ', len(data))
data_list = [None] * len(data)
for index, row in enumerate(data):
data_list[index] = (data_labels[row.argmax()])
cc = Counter(data_list)
print((list(cc.items())))
################################
# related to music tagging model
################################
# Convert a power spectrogram (amplitude squared) to decibel (dB) units
def get_music_tags(json_path):
tag_list = []
with open(json_path) as data_file:
data = json.load(data_file)
#print data["tags"]
for data in data["tags"]:
#print 'data type', type(data[1])
rating_int = int(data[1])
#rating_int = rating_string.toInt
#print 'rat int', rating_int
if rating_int > 50:
#print 'tags:', data[0]
#print 'rating:', data[1]
tag_list.append(data[0])
#print 'tag_list', tag_list
return tag_list
#print data[1]
#pprint(data)
#def get_music_tags():
def is_top_50(tags):
top_50_tags = [i for i in tags if i in top_50]
return top_50_tags
################################
# data pre-processing
################################
def get_max_label(data, labels):
print('max data pos: ' , data.argmax())
return labels[data.argmax()], data.argmax()#, data.max()
def num_to_color_label(num):
global color_labels
num = int(num*360)
print(num)
i = 0
for ranges in boundary_range_scaled:
if i != 0:
if num in range(old_range, ranges):
#print 'yes!!!!'
print(color_labels[i-1])
break
#print i, old_range
#print ranges
old_range = ranges
i += 1
return
def td_to_color_label(Y_logger):
global color_labels
for i in range(0, Y_logger.shape[0]):
num = int(num*360)
print(num)
i = 0
for ranges in boundary_range_scaled:
if i != 0:
if num in range(old_range, ranges):
#print 'yes!!!!'
print(color_labels[i-1])
break
#print i, old_range
#print ranges
old_range = ranges
i += 1
return
def csv_to_dataframe(data_file):
data = pd.read_csv(data_file, names = ["lx_route", "data", "raw_reading", "osc_reading", "timestamp"])
timestamps = data.timestamp.str.extract('(\d+)').fillna(0).astype(int)
print(data.shape)
data_2 = data.set_index(timestamps)
data_2 = data_2[~data_2.index.duplicated(keep='first')]
print(data_2.shape)
raw_data_size = data_2.shape[0]
raw_data_list = data_2.lx_route.str.split('lx/').tolist()
raw_data_list2 = data_2.lx_route.str.split('lx/', expand=True)
raw_data_list2.columns = ['pre_route', 'route']
training_data = raw_data_list2.drop('pre_route', 1)
training_data = training_data.join(data_2.data)
print(training_data.shape)
#training_data_red = trainind_data.str.replace('data:', '')
training_data_pivoted = training_data.pivot(columns = 'route', values = 'data')
# -------- WORKING TDP MAKER -----------------
td_p = training_data_pivoted.replace('data:', '', regex= True)
try:
td_p.drop([None], 1, inplace = True)
except:
print('no nan!')
for col in td_p:
#col = col.strip('"')
td_p[col] = td_p[col].str.split('[').str[-1]
#td_p[col] = td_p[col].str.split(']').str[-1]
td_p = td_p.replace(']', '', regex= True)
td_p = td_p.replace('"', '', regex= True)
#col = col.strip('"')
for index in td_p.index:
if index < 1000000000000:
print('dropping rows with indexes: ', index)
td_p.drop(index, inplace=True)
td_p.rename(columns=lambda x: x.strip('"'), inplace = True)
return td_p
def fill_none(dataframe):
placeholder = 0
j = 0
for col in dataframe:
i = 0
placeholder = 0
for row in dataframe[col]:
if row != None:
placeholder = row
else:
dataframe.iloc[i, dataframe.get_loc(col)] = placeholder
print(row , '=', placeholder)
i += 1
j += 1
def hue_to_color(num):
num = int(num*360)
#print num
j = 0
for ranges in boundary_range_scaled:
if j != 0:
if num in range(old_range, ranges):
print(color_labels[j-1])
current_color = color_labels[j-1]
#print i
break
#print i, old_range
#print ranges
old_range = ranges
j += 1
return current_color
def speed_to_label(speed):
#old_range = 0
j = 0
#current_speed = []
speed = int(speed*100)
print(speed)
for ranges in speed_range_scaled:
if j != 0:
if speed in range(old_range, ranges):
print(speed_labels[j-1])
return speed_labels[j-1]
break
j += 1
old_range = ranges
def effect_to_label(effect):
effect_labels = ['low', 'medium', 'high']
#old_range = 0
j = 0
#current_speed = []
effect = int(effect*100)
print(effect)
for ranges in speed_range_scaled:
if j != 0:
if effect in range(old_range, ranges):
print(effect_labels[j-1])
return effect_labels[j-1]
break
j += 1
old_range = ranges
def brightness_to_label(effect):
brightness_labels = ['off', 'half', 'full']
#old_range = 0
j = 0
#current_speed = []
effect = int(effect*100)
print(effect)
for ranges in speed_range_scaled:
if j != 0:
if effect in range(old_range, ranges):
print(brightness_labels[j-1])
return brightness_labels[j-1]
break
j += 1
old_range = ranges
#speed_range_scaled = [0, 34, 67, 101]
def get_unique_tags(data): # to get unique music tags in a list!
unique_tags = []
for i in range(len(data)):
tags_test = data[i]
print(tags_test)
if tags_test != 0:
# if multiple labels...
# for x in tags_test:
if tags_test not in unique_tags:
unique_tags.append(tags_test)
print('unique tags', unique_tags)
return unique_tags
def logger_to_training_data(data_file):
datan = pd.read_csv(data_file, sep="]", header=None, error_bad_lines=False)
datan_2 = pd.DataFrame(datan[0].str.rsplit(',',1).tolist(), columns = ['lx_route','data'])
datan_ts = pd.DataFrame(datan[1].str.rsplit(',',1).tolist(), columns = ['raw','timestamps'])
timestamps2 = datan_ts['timestamps'].str.extract('(\d+)').fillna(0).astype(int)
#datan_2.set_index(timestamps2)
for col in datan_2:
datan_2 = datan_2.replace('{"route":"', '', regex= True)
datan_2 = datan_2.replace('"data":', '', regex= True)
datan_2 = datan_2.replace('"', '', regex= True)
if col == 'lx_route':
datan_2[col] = datan_2[col].str.split(',').str[0]
else:
datan_2[col] = datan_2[col].str.split('[').str[-1]
datan_3 = datan_2.set_index(timestamps2)
datan_3 = datan_3[datan_3.lx_route != '/lx/channel/1/nextPattern']
datan_3 = datan_3[~datan_3.index.duplicated(keep='last')]
training_data_pivoted = datan_3.pivot(columns = 'lx_route', values = 'data')
td_p = training_data_pivoted
placeholder = 0
j = 0
for col in td_p:
i = 0
placeholder = 0
if 'activePattern' in col or 'hue' in col or 'speed' in col or 'enabled':
for row in td_p[col]:
#print row
if row != None:
placeholder = row
#print row
else:
#print placeholder /lx/output/enabled
#td_p.loc[col, row] = placeholder
#td_p.loc[i, col] = placeholder
td_p.iloc[i, td_p.columns.get_loc(col)] = placeholder
#print row , '=', placeholder
i += 1
j += 1
return td_p
def logger_to_param_data(data_file):
datan = pd.read_csv(data_file, sep="]", header=None, error_bad_lines=False)
datan_2 = pd.DataFrame(datan[0].str.rsplit(',',1).tolist(), columns = ['lx_route','data'])
datan_ts = pd.DataFrame(datan[1].str.rsplit(',',1).tolist(), columns = ['raw','timestamps'])
timestamps2 = datan_ts['timestamps'].str.extract('(\d+)').fillna(0).astype(int)
#datan_2.set_index(timestamps2)
for col in datan_2:
datan_2 = datan_2.replace('{"route":"', '', regex= True)
datan_2 = datan_2.replace('"data":', '', regex= True)
datan_2 = datan_2.replace('"', '', regex= True)
if col == 'lx_route':
datan_2[col] = datan_2[col].str.split(',').str[0]
else:
datan_2[col] = datan_2[col].str.split('[').str[-1]
datan_3 = datan_2.set_index(timestamps2)
datan_3 = datan_3[datan_3.lx_route != '/lx/channel/1/nextPattern']
datan_3 = datan_3[~datan_3.index.duplicated(keep='last')]
training_data_pivoted = datan_3.pivot(columns = 'lx_route', values = 'data')
td_p = training_data_pivoted
return td_p
def dataframe_to_labels(Y_logger_df):
######################################################################
# Raw values to labels
######################################################################
print('converting dataframe to labels')
print('dataframe length: ', len(Y_logger_df))
print('dataframe columns: ', Y_logger_df.columns)
color_labels = ['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple', 'magenta', 'red']
color_labels_encoding = ['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple', 'magenta']
speed_range_scaled = [0, 34, 67, 101]
speed_labels = ['slow', 'medium', 'fast']
######################################################################
# create individual lists and pattern label array
######################################################################
color_list = []
speed_list = []
pattern_list = []
if '/lx/palette/color/hue' in Y_logger_df.columns:
print('hue is in dataframe, making labels')
for i in Y_logger_df['/lx/palette/color/hue']:
#print type(i)
color_list.append(hue_to_color(float(i)))
else:
print('hue is not in dataframe, moving on')
if '/lx/engine/speed' in Y_logger_df.columns:
for i in Y_logger_df['/lx/engine/speed']:
speed_list.append(speed_to_label(float(i)))
else:
print('speed not in dataframe, moving on')
if '/lx/channel/1/activePattern' in Y_logger_df.columns:
for i in Y_logger_df['/lx/channel/1/activePattern']:
pattern_list.append(i)
else:
print('patterns not in dataframe, moving on')
pattern_labels = get_unique_tags(pattern_list)
Y_color = np.zeros((len(color_list), len(color_labels_encoding)))
Y_speed = np.zeros((len(speed_list), len(speed_labels)))
# ------ GLOBALLY encoded patterns ------
Y_pattern = np.zeros((len(pattern_list), len(patterns_full)))
# ------ OLD way of locally encoding patterns -------
#Y_pattern = np.zeros((len(pattern_list), len(pattern_labels)))
for index, label in enumerate(color_list):
#print type(i)
#print 'ind' , index
#print label
Y_color[index] = encode_class(label, color_labels_encoding)
for index, label in enumerate(speed_list):
#print type(i)
#print 'ind' , index
#print label
Y_speed[index] = encode_class(label, speed_labels)
for index, label in enumerate(pattern_list):
#print type(i)
#print 'ind' , index
#print label
Y_pattern[index] = encode_class(label, patterns_full)
return Y_color, Y_speed, Y_pattern
def match_training_dataset_old(td_p, time_test_scaled):
#time_test = time_test * 1000
Y_logger = np.zeros((21, td_p.shape[1]))
print('input data length', len(td_p))
Y_logger_df = pd.DataFrame(data=None, columns=td_p.columns)
j = 0
old_index = 0
old_value = td_p.index[0]
for timestamps in time_test_scaled:
for index, value in enumerate(list(td_p.index)):
#print timestamp_array[8]
if value > timestamps:
print(old_value, value)
print('index: ', index)
print(timestamps)
Y_logger_df = Y_logger_df.append(td_p.loc[old_value]) #ignore_index=True
#Y_logger[j] = td_p.loc[old_value].as_matrix()
j += 1
break
#print index
old_index = index
old_value = value
print(Y_logger_df)
return Y_logger_df
def match_training_dataset(td_p, time_test_scaled, X_test):
# function to match the dataframe with LX data and the audio data by timestamp
# notice that we have to scale the audio timestamps by multiplying it by 1000
# when the timestamp of the logger data passes the each audio timestamp, we append
# the reading before the audio timestamp to the new logger data...
# this is because that was the current LX settings when that audio timestamp occured
#time_test = time_test * 1000
X_test_trimmed = np.zeros((len(X_test), 1, 96, 938))
Y_logger = np.zeros((21, td_p.shape[1]))
print('input data length', len(td_p))
Y_logger_df = pd.DataFrame(data=None, columns=td_p.columns)
j = 0
old_index = 0
old_value = td_p.index[0]
for index_logger, timestamps in enumerate(time_test_scaled):
for index, value in enumerate(list(td_p.index)):
#print timestamp_array[8]
if value > timestamps:
print(old_value, value)
print('index: ', index)
print(timestamps)
Y_logger_df = Y_logger_df.append(td_p.loc[old_value]) #ignore_index=True
X_test_trimmed[j] = X_test[index_logger]
#Y_logger[j] = td_p.loc[old_value].as_matrix()
j += 1
break
#print index
old_index = index
old_value = value
print('j:' , j)
print('trimming new X data')
X_test_trimmed = X_test_trimmed[0:j]
print(Y_logger_df)
return Y_logger_df, X_test_trimmed
def drop_darkness(dataframe, X_test):
print('dropping all datapoints where light was not on')
print('matching up lengths of logger vs. audio data')
print('logger: ', len(dataframe), 'audio: ', X_test.shape)
#X_data_trimmed = X_data
dataframe_old = dataframe
dark_timestamps = dataframe.index[dataframe['/lx/output/enabled'] == '0'].tolist()
dark_indexes = np.zeros(len(dark_timestamps))
# Create a non-duplicated version of dark timestamps
dark_timestamps_nodup = []
for i in dark_timestamps:
if i not in dark_timestamps_nodup:
dark_timestamps_nodup.append(i)
# get row numbers where there were dark timestamps
j = 0
for row_number_ts, value in enumerate(dark_timestamps_nodup):
#print value
for row_number, df_index in enumerate(dataframe_matched.index):
if df_index == value:
dark_indexes[j] = row_number
print(row_number)
j += 1
# drop all dark timestamped rows from Dataframe logger data
for dark_index in dark_timestamps:
dataframe.drop(dark_index, inplace=True)
#dataframe.index.get_loc(dark_index)
# drop all dark indexes from music data (X)
X_test_trimmed = np.delete(X_test, dark_indexes, axis=0)
print('new X length:', len(X_test_trimmed))
return dataframe, dark_timestamps, dark_indexes, X_test_trimmed
def drop_runtime_toggle(dataframe, X_test):
print('dropping all datapoints where runtime record was toggled off')
print('dropping runtime predictions we dont want to feed back into the model')
print('as new training data')
print('logger: ', len(dataframe), 'audio: ', X_test.shape)
#X_data_trimmed = X_data
dataframe_old = dataframe
dark_timestamps = dataframe.index[dataframe['/lx/master/arm'] == '0'].tolist()
dark_indexes = np.zeros(len(dark_timestamps))
# Create a non-duplicated version of dark timestamps
dark_timestamps_nodup = []
for i in dark_timestamps:
if i not in dark_timestamps_nodup:
dark_timestamps_nodup.append(i)
# get row numbers where there were dark timestamps
j = 0
for row_number_ts, value in enumerate(dark_timestamps_nodup):
#print value
for row_number, df_index in enumerate(dataframe_matched.index):
if df_index == value:
dark_indexes[j] = row_number
print(row_number)
j += 1
# drop all dark timestamped rows from Dataframe logger data
for dark_index in dark_timestamps:
dataframe.drop(dark_index, inplace=True)
#dataframe.index.get_loc(dark_index)
# drop all dark indexes from music data (X)
X_test_trimmed = np.delete(X_test, dark_indexes, axis=0)
print('new X length:', len(X_test_trimmed))
return dataframe, dark_timestamps, dark_indexes, X_test_trimmed
def drop_darkness_post(dataframe, X_test_matched, dark_indexes, dark_timestamps):
# drop all dark timestamped rows from Dataframe logger data
for dark_index in dark_timestamps:
dataframe.drop(dark_index, inplace=True)
#dataframe.index.get_loc(dark_index)
# drop all dark indexes from music data (X)
X_test_trimmed = np.delete(X_test_matched, dark_indexes, axis=0)
print('new X length:', len(X_test_trimmed))
return dataframe, X_test_trimmed
def create_Y_param(dataframe):
global param_labels_full
Y_effects = [None] * len(dataframe)
placeholder = 0
j = 0
for col in dataframe:
i = 0
placeholder = 0
if 'Spd' in col or 'spd' in col or 'RATE' in col or 'Speed' in col or 'speed' in col:
print('col: ', col)
for row in dataframe[col]:
#print row, i
if row != None and row != '0':
#placeholder = row
print('row: ', row, 'col: ', i)
Y_effects[i] = 'Faster'
i += 1
if 'H.V.' in col or 'hShift' in col or 'HUE' in col:
print('col: ', col)
for row in dataframe[col]:
#print row, i
if row != None and row != '0':
#placeholder = row
print('row: ', row, 'col: ', i)
Y_effects[i] = 'Hue Variation'
i += 1
if 'Sprk' in col or 'Spark' in col: #or 'hue' in col or 'speed' in col or 'enabled':
print('col: ', col)
for row in dataframe[col]:
#print row, i
if row != None and row != '0':
#placeholder = row
print('row: ', row, 'col: ', i)
Y_effects[i] = 'Sparkle'
i += 1
if 'Crzy' in col or 'Wave' in col:
print('col: ', col)
for row in dataframe[col]:
#print row, i
if row != None and row != '0':
#placeholder = row
print('row: ', row, 'col: ', i)
Y_effects[i] = 'Crazy'
i += 1
if 'Dens' in col or 'thck' in col or 'DEPTH' in col or 'Size' in col or 'SIZE' in col:
print('col: ', col)
for row in dataframe[col]:
#print row, i
if row != None and row != '0':
#placeholder = row
print('row: ', row, 'col: ', i)
Y_effects[i] = 'Larger'
i += 1
Y_params_encoded = np.zeros((len(Y_effects), len(param_labels_full)))
for index, label in enumerate(Y_effects):
Y_params_encoded[index] = encode_class(label, param_labels_full)
return Y_effects, Y_params_encoded
def create_Y_effect_old(dataframe, effect_number):
global effect_labels_full
Y_effect = [None] * len(dataframe)
i= 0
for index, row in dataframe.iterrows():
print('row:', row['/lx/channel/1/effect/1/enabled'], end=' ')
if row['/lx/channel/1/effect/' + str(effect_number) + '/enabled'] == '1':
print(float(row['/lx/channel/1/effect/' + str(effect_number) + '/amount']))
print(i)
if row['/lx/channel/1/effect/' + str(effect_number) + '/amount'] == '0':
print('0 value although its on!')
break
Y_effect[i] = effect_to_label(float(row['/lx/channel/1/effect/' + str(effect_number) + '/amount']))
print('effect on at: ', row['/lx/channel/1/effect/' + str(effect_number) + '/amount'])
else:
print('blur off')
i += 1
#for index, label in enumerate(Y_blur):
#Y_pattern[index] = encode_class(label, patterns_full)
Y_effect_encoded = [None] * len(Y_effect)
for index, label in enumerate(Y_effect):
Y_effect_encoded[index] = encode_class(label, effect_labels_full)
return Y_effect, Y_effect_encoded
def create_Y_effect(dataframe, effect_number):
global effect_labels_full
Y_effect = [None] * len(dataframe)
i = 0
for index, row in dataframe.iterrows():
#print 'row:', row['/lx/channel/1/effect/1/enabled'],
if row['/lx/channel/1/effect/' + str(effect_number) + '/enabled'] == '1':
#print float(row['/lx/channel/1/effect/' + str(effect_number) + '/amount'])
#print i
if row['/lx/channel/1/effect/' + str(effect_number) + '/amount'] != '0':
#print '0value although its on! - at row: ', i
#continue
Y_effect[i] = effect_to_label(float(row['/lx/channel/1/effect/' + str(effect_number) + '/amount']))
else:
print('0 value although its on! - at row: ', i)
#print 'effect on at: ', row['/lx/channel/1/effect/' + str(effect_number) + '/amount']
else:
print('blur off')
i += 1
#for index, label in enumerate(Y_blur):
#Y_pattern[index] = encode_class(label, patterns_full)
Y_effect_encoded = np.zeros((len(Y_effect), len(effect_labels_full)))
for index, label in enumerate(Y_effect):
Y_effect_encoded[index] = encode_class(label, effect_labels_full)
return Y_effect, Y_effect_encoded
# function to pull Y_channel_2 and Y_pattern_2 from Dataframe
# IF WE want to create 2 separate models (ONE to tell if channel 2 is on and 1 to predict pattern)
# USE Y_channel_2 AS BOOLEAN
# channel 2 indexes to whittle down X_train
# Y_pattern 2 to train only pattern predicter
#
# THE ALTERNATE is to use just Y_pattern_2 and if it predicts a pattern, it turns on channel 2
# Y_pattern_2 is always running
def create_Y_channel_2(dataframe):
j = 0
Y_channel_2 = np.zeros(len(dataframe))
Y_pattern_2 = [None] * len(dataframe)
Y_channel_2_alt = []
channel_2_indexes = np.zeros(0)
for index, row in dataframe.iterrows():
#print 'row:', row['/lx/channel/2/enabled'],
if row['/lx/channel/2/enabled'] == '1':
if row['/lx/channel/2/activePattern'] != 0:
Y_pattern_2[j] = row['/lx/channel/2/activePattern']
channel_2_indexes = np.append(channel_2_indexes, j)
print(row['/lx/channel/2/activePattern'])
Y_channel_2_alt.append(row['/lx/channel/2/activePattern'])
#print 'pattern 2 on'
#print j
Y_channel_2[j] = 1
else:
Y_channel_2[j] = 0
j += 1
Y_pattern_2_encoded = np.zeros((len(Y_pattern_2), len(patterns_full)))
Y_channel_2_alt_encoded = np.zeros((len(Y_channel_2_alt), len(patterns_full)))
# encode full pattern
for index, label in enumerate(Y_pattern_2):
if label == None:
label = 'Blank'
if label == 'SolidColor':
label = 'Palette'
Y_pattern_2_encoded[index] = encode_class(label, patterns_full)
# encode only when pattern is on
for index, label in enumerate(Y_channel_2_alt):
if label == None:
label = 'Blank'
if label == 'SolidColor':
label = 'Palette'
Y_channel_2_alt_encoded[index] = encode_class(label, patterns_full)
return Y_channel_2, Y_pattern_2, Y_pattern_2_encoded, Y_channel_2_alt, Y_channel_2_alt_encoded, channel_2_indexes
#else:
def create_Y_brightness(dataframe):
j = 0
Y_brightness = [None] * len(dataframe) #np.zeros(len(dataframe))
for index, row in dataframe.iterrows():
Y_brightness[j] = brightness_to_label(float(row['/lx/output/brightness']))
j += 1
Y_brightness_encoded = np.zeros((len(Y_brightness), len(brightness_labels)))
for index, label in enumerate(Y_brightness):
Y_brightness_encoded[index] = encode_class(label, brightness_labels)
return Y_brightness, Y_brightness_encoded
def get_labels(data, top_50):