forked from smarsland/AviaNZ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DialogsTraining.py
3288 lines (2827 loc) · 147 KB
/
DialogsTraining.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
# This is part of the AviaNZ interface
# Holds most of the code for the various dialog boxes
# Version 3.0 14/09/20
# Authors: Stephen Marsland, Nirosha Priyadarshani, Julius Juodakis, Virginia Listanti
# AviaNZ bioacoustic analysis program
# Copyright (C) 2017--2020
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Dialogs used for filter training / testing.
# These are relatively complicated wizards which also do file I/O
import os
import time
import platform
import copy
from shutil import copyfile
import json
from PyQt5.QtGui import QIcon, QValidator, QAbstractItemView, QPixmap, QColor
from PyQt5.QtCore import QDir, Qt, QEvent, QSize, pyqtSignal
from PyQt5.QtWidgets import QLabel, QSlider, QPushButton, QListWidget, QListWidgetItem, QComboBox, QDialog, QWizard, QWizardPage, QLineEdit, QSizePolicy, QFormLayout, QVBoxLayout, QHBoxLayout, QCheckBox, QLayout, QApplication, QRadioButton, QGridLayout, QFileDialog, QScrollArea, QWidget
import matplotlib.markers as mks
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import pyqtgraph as pg
import numpy as np
import colourMaps
import SupportClasses, SupportClasses_GUI
import SignalProc
import WaveletSegment
import WaveletFunctions
import Segment
import Clustering
import Training
class BuildRecAdvWizard(QWizard):
# page 1 - select training data
class WPageData(QWizardPage):
def __init__(self, config, parent=None):
super(BuildRecAdvWizard.WPageData, self).__init__(parent)
self.setTitle('Training data')
self.setSubTitle('To start training, you need labelled calls from your species as training data (see the manual). Select the folder where this data is located. Then select the species.')
self.setMinimumSize(600, 150)
self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
self.adjustSize()
self.trainDirName = QLineEdit()
self.trainDirName.setReadOnly(True)
self.btnBrowse = QPushButton('Browse')
self.btnBrowse.clicked.connect(self.browseTrainData)
colourNone = QColor(config['ColourNone'][0], config['ColourNone'][1], config['ColourNone'][2], config['ColourNone'][3])
colourPossibleDark = QColor(config['ColourPossible'][0], config['ColourPossible'][1], config['ColourPossible'][2], 255)
colourNamed = QColor(config['ColourNamed'][0], config['ColourNamed'][1], config['ColourNamed'][2], config['ColourNamed'][3])
self.listFiles = SupportClasses_GUI.LightedFileList(colourNone, colourPossibleDark, colourNamed)
self.listFiles.setMinimumHeight(225)
self.listFiles.setSelectionMode(QAbstractItemView.NoSelection)
selectSpLabel = QLabel("Choose the species for which you want to build the recogniser")
self.species = QComboBox() # fill during browse
self.species.addItems(['Choose species...'])
space = QLabel()
space.setFixedHeight(20)
# SampleRate parameter
self.fs = QSlider(Qt.Horizontal)
self.fs.setTickPosition(QSlider.TicksBelow)
self.fs.setTickInterval(2000)
self.fs.setRange(0, 32000)
self.fs.setValue(0)
self.fs.valueChanged.connect(self.fsChange)
self.fstext = QLabel('')
form1 = QFormLayout()
form1.addRow('', self.fstext)
form1.addRow('Preferred sampling rate (Hz)', self.fs)
# training page layout
layout1 = QHBoxLayout()
layout1.addWidget(self.trainDirName)
layout1.addWidget(self.btnBrowse)
layout = QVBoxLayout()
layout.addWidget(space)
layout.addLayout(layout1)
layout.addWidget(self.listFiles)
layout.addWidget(space)
layout.addWidget(selectSpLabel)
layout.addWidget(self.species)
layout.addLayout(form1)
layout.setAlignment(Qt.AlignVCenter)
self.setLayout(layout)
def browseTrainData(self):
trainDir = QFileDialog.getExistingDirectory(self, 'Choose folder for training')
self.trainDirName.setText(trainDir)
self.fillFileList(trainDir)
def fsChange(self, value):
value = value // 4000 * 4000
if value < 4000:
value = 4000
self.fstext.setText(str(value))
self.fs.setValue(value)
def fillFileList(self, dirName):
""" Generates the list of files for a file listbox. """
if not os.path.isdir(dirName):
print("Warning: directory doesn't exist")
return
self.listFiles.fill(dirName, fileName=None, readFmt=True, addWavNum=True, recursive=True)
# while reading the file, we also collected a list of species present there
spList = list(self.listFiles.spList)
# and sample rate info
fs = list(self.listFiles.fsList)
if len(fs)==0:
print("Warning: no suitable files found")
return
# might need better limits on selectable sample rate here
self.fs.setValue(int(np.min(fs)))
self.fs.setRange(4000, int(np.max(fs)))
self.fs.setSingleStep(4000)
self.fs.setTickInterval(4000)
spList.insert(0, 'Choose species...')
self.species.clear()
self.species.addItems(spList)
if len(spList)==2:
self.species.setCurrentIndex(1)
# page 2 - precluster
class WPagePrecluster(QWizardPage):
def __init__(self, parent=None):
super(BuildRecAdvWizard.WPagePrecluster, self).__init__(parent)
self.setTitle('Confirm data input')
self.setSubTitle('When ready, press \"Cluster\" to start clustering. The process may take a long time.')
self.setMinimumSize(250, 150)
self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
self.adjustSize()
revtop = QLabel("The following parameters were set:")
self.params = QLabel("")
self.params.setStyleSheet("QLabel { color : #808080; }")
self.warnLabel = QLabel("")
self.warnLabel.setStyleSheet("QLabel { color : #800000; }")
layout2 = QVBoxLayout()
layout2.addWidget(revtop)
layout2.addWidget(self.params)
layout2.addWidget(self.warnLabel)
self.setLayout(layout2)
self.setButtonText(QWizard.NextButton, 'Cluster >')
def initializePage(self):
self.wizard().button(QWizard.NextButton).setDefault(False)
self.wizard().saveTestBtn.setVisible(False)
# parse some params
fs = int(self.field("fs"))//4000*4000
if fs not in [8000, 16000, 24000, 32000, 36000, 48000]:
self.warnLabel.setText("Warning: unusual sampling rate selected, make sure it is intended.")
else:
self.warnLabel.setText("")
self.params.setText("Species: %s\nTraining data: %s\nSampling rate: %d Hz\n" % (self.field("species"), self.field("trainDir"), fs))
# page 3 - calculate and adjust clusters
class WPageCluster(QWizardPage):
def __init__(self, config, parent=None):
super(BuildRecAdvWizard.WPageCluster, self).__init__(parent)
self.setTitle('Cluster similar looking calls')
self.setSubTitle('AviaNZ has tried to identify similar calls in your dataset. Please check the output, and move calls as appropriate.')
# start larger than minimumSize, but not bigger than the screen:
screenresol = QApplication.primaryScreen().availableSize()
self.manualSizeHint = QSize(min(800, 0.9*screenresol.width()), min(600, 0.9*screenresol.height()))
self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
self.adjustSize()
instr = QLabel("To move one call, just drag it with the mouse. To move more, click on them so they are marked with a tick and drag any of them. To merge two types, select all of one group by clicking the empty box next to the name, and then drag any of them. You might also want to name each type of call.")
instr.setWordWrap(True)
self.sampleRate = 0
self.segments = []
self.clusters = {}
self.clustercentres = {}
self.duration = 0
self.feature = 'we'
self.picbuttons = []
self.cboxes = []
self.tboxes = []
self.nclasses = 0
self.config = config
self.segsChanged = False
self.hasCTannotations = True
self.lblSpecies = QLabel()
self.lblSpecies.setStyleSheet("QLabel { color : #808080; }")
# Volume, brightness and contrast sliders.
# Config values are overwritten with fixed bright/contr/no inversion.
self.specControls = SupportClasses_GUI.BrightContrVol(80, 20, False)
self.specControls.colChanged.connect(self.setColourLevels)
self.specControls.volChanged.connect(self.volSliderMoved)
self.specControls.layout().setContentsMargins(20, 0, 20, 10)
self.btnCreateNewCluster = QPushButton('Create cluster')
self.btnCreateNewCluster.setFixedWidth(150)
self.btnCreateNewCluster.clicked.connect(self.createNewcluster)
self.btnDeleteSeg = QPushButton('Remove selected segment/s')
self.btnDeleteSeg.setFixedWidth(200)
self.btnDeleteSeg.clicked.connect(self.deleteSelectedSegs)
# Colour map
self.lut = colourMaps.getLookupTable(self.config['cmap'])
# page 3 layout
layout1 = QVBoxLayout()
layout1.addWidget(instr)
layout1.addWidget(self.lblSpecies)
hboxBtns2 = QHBoxLayout()
hboxBtns2.addWidget(self.btnCreateNewCluster)
hboxBtns2.addWidget(self.btnDeleteSeg)
hboxBtns2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
# top part
vboxTop = QVBoxLayout()
vboxTop.addWidget(self.specControls)
vboxTop.addLayout(hboxBtns2)
# set up the images
self.flowLayout = SupportClasses_GUI.Layout()
self.flowLayout.setMinimumSize(380, 247)
self.flowLayout.buttonDragged.connect(self.moveSelectedSegs)
self.flowLayout.layout.setSizeConstraint(QLayout.SetMinimumSize)
self.scrollArea = QScrollArea(self)
#self.scrollArea.setWidgetResizable(True)
self.scrollArea.setWidget(self.flowLayout)
self.scrollArea.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
# set overall layout of the dialog
self.vboxFull = QVBoxLayout()
self.vboxFull.addLayout(layout1)
self.vboxFull.addLayout(vboxTop)
self.vboxFull.addWidget(self.scrollArea)
self.setLayout(self.vboxFull)
def initializePage(self):
self.wizard().saveTestBtn.setVisible(False)
# parse field shared by all subfilters
fs = int(self.field("fs"))//4000*4000
self.wizard().speciesData = {"species": self.field("species"), "method": self.wizard().method, "SampleRate": fs, "Filters": []}
with pg.BusyCursor():
print("Processing. Please wait...")
# Check if the annotations come with call type labels, if so skip auto clustering
self.CTannotations()
if self.hasCTannotations:
# self.segments: [parent_audio_file, [segment], class_label]
self.segments, self.nclasses, self.duration = self.getClustersGT()
self.setSubTitle('AviaNZ found call type annotations in your dataset. You can still make corrections by moving calls as appropriate.')
else:
# return format:
# self.segments: [parent_audio_file, [segment], [syllables], [features], class_label]
# self.nclasses: number of class_labels
# duration: median length of segments
self.cluster = Clustering.Clustering([], [], 5)
self.segments, self.nclasses, self.duration = self.cluster.cluster(self.field("trainDir"), self.field("fs"), self.field("species"), feature=self.feature)
# segments format: [[file1, seg1, [syl1, syl2], [features1, features2], predict], ...]
# self.segments, fs, self.nclasses, self.duration = self.cluster.cluster_by_dist(self.field("trainDir"),
# self.field("species"),
# feature=self.feature,
# max_clusters=5,
# single=True)
self.setSubTitle('AviaNZ has tried to identify similar calls in your dataset. Please check the output, and move calls as appropriate.')
# Create and show the buttons
self.clearButtons()
self.addButtons()
self.updateButtons()
print("buttons added")
self.segsChanged = True
self.completeChanged.emit()
def isComplete(self):
# empty cluster names?
if len(self.clusters)==0:
return False
# duplicate cluster names aren't updated:
for ID in range(self.nclasses):
if self.clusters[ID] != self.tboxes[ID].text():
return False
# no segments at all?
if len(self.segments)==0:
return False
# if all good, then check if we need to redo the pages.
# segsChanged should be updated by any user changes!
if self.segsChanged:
self.segsChanged = False
self.wizard().redoTrainPages()
return True
def validatePage(self):
self.updateAnnotations()
return True
def cleanupPage(self):
self.clusters = {}
def CTannotations(self):
""" Check if all the segments from target species has call type annotations"""
self.hasCTannotations = True
listOfDataFiles = []
for root, dirs, files in os.walk(self.field("trainDir")):
for file in files:
if file[-5:].lower() == '.data':
listOfDataFiles.append(os.path.join(root, file))
for file in listOfDataFiles:
# Read the annotation
segments = Segment.SegmentList()
segments.parseJSON(file)
SpSegs = segments.getSpecies(self.field("species"))
for segix in SpSegs:
seg = segments[segix]
for label in seg[4]:
if label["species"] == self.field("species") and "calltype" not in label:
self.hasCTannotations = False
break
def getClustersGT(self):
""" Gets call type clusters from annotations
returns [parent_audio_file, [segment], [syllables], class_label], number of clusters, median duration
"""
ctTexts = []
CTsegments = []
duration = []
cl = Clustering.Clustering([], [], 5)
listOfDataFiles = []
listOfWavFiles = []
for root, dirs, files in os.walk(self.field("trainDir")):
for file in files:
if file[-5:].lower() == '.data':
listOfDataFiles.append(os.path.join(root, file))
elif file[-4:].lower() == '.wav':
listOfWavFiles.append(os.path.join(root, file))
for file in listOfDataFiles:
if file[:-5] in listOfWavFiles:
# Read the annotation
segments = Segment.SegmentList()
segments.parseJSON(file)
SpSegs = segments.getSpecies(self.field("species"))
for segix in SpSegs:
seg = segments[segix]
for label in seg[4]:
if label["species"] == self.field("species") and "calltype" in label:
if label["calltype"] not in ctTexts:
ctTexts.append(label["calltype"])
for i in range(len(ctTexts)):
self.clusters[i] = ctTexts[i]
for file in listOfDataFiles:
if file[:-5] in listOfWavFiles:
# Read the annotation
segments = Segment.SegmentList()
wavfile = os.path.join(self.field("trainDir"), file[:-5])
segments.parseJSON(os.path.join(self.field("trainDir"), file))
SpSegs = segments.getSpecies(self.field("species"))
for segix in SpSegs:
seg = segments[segix]
for label in seg[4]:
if label["species"] == self.field("species") and "calltype" in label:
# Find the syllables inside this segment
# TODO: Filter all the hardcoded parameters into a .txt in config (minlen=0.2, denoise=False)
syls = cl.findSyllablesSeg(file=wavfile, seg=seg, fs=self.field("fs"), denoise=False, minlen=0.2)
CTsegments.append([wavfile, seg, syls, list(self.clusters.keys())[list(self.clusters.values()).index(label["calltype"])]])
duration.append(seg[1]-seg[0])
return CTsegments, len(self.clusters), np.median(duration)
def backupDatafiles(self):
# Backup original data fiels before updating them
print("Backing up files ", self.field("trainDir"))
listOfDataFiles = QDir(self.field("trainDir")).entryList(['*.data'])
for file in listOfDataFiles:
source = self.field("trainDir") + '/' + file
destination = source[:-5] + ".backup"
if os.path.isfile(destination):
pass
else:
copyfile(source, destination)
def updateAnnotations(self):
""" Update annotation files. Assign call types suggested by clusters and remove any segment deleted in the
clustering. Keep a backup of the original .data."""
self.backupDatafiles()
print("Updating annotation files ", self.field("trainDir"))
listOfDataFiles = QDir(self.field("trainDir")).entryList(['*.data'])
for file in listOfDataFiles:
# Read the annotation
segments = Segment.SegmentList()
newsegments = Segment.SegmentList()
segments.parseJSON(os.path.join(self.field("trainDir"), file))
allSpSegs = np.arange(len(segments)).tolist()
newsegments.metadata = segments.metadata
for segix in allSpSegs:
seg = segments[segix]
if self.field("species") not in [fil["species"] for fil in seg[4]]:
newsegments.addSegment(seg) # leave non-target segments unchanged
else:
for seg2 in self.segments:
if seg2[1] == seg:
# find the index of target sp and update call type
seg[4][[fil["species"] for fil in seg[4]].index(self.field("species"))]["calltype"] = self.clusters[seg2[-1]]
newsegments.addSegment(seg)
newsegments.saveJSON(os.path.join(self.field("trainDir"), file))
def merge(self):
""" Listener for the merge button. Merge the rows (clusters) checked into one cluster.
"""
# Find which clusters/rows to merge
self.segsChanged = True
tomerge = []
i = 0
for cbox in self.cboxes:
if cbox.checkState() != 0:
tomerge.append(i)
i += 1
print('rows/clusters to merge are:', tomerge)
if len(tomerge) < 2:
return
# Generate new class labels
nclasses = self.nclasses - len(tomerge) + 1
max_label = nclasses - 1
labels = []
c = self.nclasses - 1
while c > -1:
if c in tomerge:
labels.append((c, 0))
else:
labels.append((c, max_label))
max_label -= 1
c -= 1
# print('[old, new] labels')
labels = dict(labels)
# print(labels)
keys = [i for i in range(self.nclasses) if i not in tomerge] # the old keys those didn't merge
# print('old keys left: ', keys)
# update clusters dictionary {ID: cluster_name}
clusters = {0: self.clusters[tomerge[0]]}
for i in keys:
clusters.update({labels[i]: self.clusters[i]})
print('before update: ', self.clusters)
self.clusters = clusters
print('after update: ', self.clusters)
self.nclasses = nclasses
# update the segments
for seg in self.segments:
seg[-1] = labels[seg[-1]]
# update the cluster combobox
#self.cmbUpdateSeg.clear()
#for x in self.clusters:
#self.cmbUpdateSeg.addItem(self.clusters[x])
# Clean and redraw
self.clearButtons()
self.updateButtons()
self.completeChanged.emit()
def moveSelectedSegs(self,dragPosy,source):
""" Listener for Apply button to move the selected segments to another cluster.
Change the cluster ID of those selected buttons and redraw all the clusters.
"""
# TODO: check: I think the dict is always in descending order down screen?
self.segsChanged = True
# The first line seemed neater, but the verticalSpacing() doesn't update when you rescale the window
#movetoID = dragPosy//(self.picbuttons[0].size().height()+self.flowLayout.layout.verticalSpacing())
movetoID = dragPosy//(self.flowLayout.layout.geometry().height()//self.nclasses)
# drags which start and end in the same cluster most likely were just long clicks:
for ix in range(len(self.picbuttons)):
if self.picbuttons[ix] == source:
if self.segments[ix][-1] == movetoID:
source.clicked.emit()
return
# Even if the button that was dragged isn't highlighted, make it so
source.mark = 'yellow'
for ix in range(len(self.picbuttons)):
if self.picbuttons[ix].mark == 'yellow':
self.segments[ix][-1] = movetoID
self.picbuttons[ix].mark = 'green'
# update self.clusters, delete clusters with no members
todelete = []
for ID, label in self.clusters.items():
empty = True
for seg in self.segments:
if seg[-1] == ID:
empty = False
break
if empty:
todelete.append(ID)
self.clearButtons()
# Generate new class labels
if len(todelete) > 0:
keys = [i for i in range(self.nclasses) if i not in todelete] # the old keys those didn't delete
# print('old keys left: ', keys)
nclasses = self.nclasses - len(todelete)
max_label = nclasses - 1
labels = []
c = self.nclasses - 1
while c > -1:
if c in keys:
labels.append((c, max_label))
max_label -= 1
c -= 1
# print('[old, new] labels')
labels = dict(labels)
print(labels)
# update clusters dictionary {ID: cluster_name}
clusters = {}
for i in keys:
clusters.update({labels[i]: self.clusters[i]})
print('before move: ', self.clusters)
self.clusters = clusters
print('after move: ', self.clusters)
# update the segments
for seg in self.segments:
seg[-1] = labels[seg[-1]]
self.nclasses = nclasses
# redraw the buttons
self.updateButtons()
self.updateClusterNames()
self.completeChanged.emit()
def createNewcluster(self):
""" Listener for Create cluster button to move the selected segments to a new cluster.
Change the cluster ID of those selected buttons and redraw all the clusters.
"""
self.segsChanged = True
# There should be at least one segment selected to proceed
proceed = False
for ix in range(len(self.picbuttons)):
if self.picbuttons[ix].mark == 'yellow':
proceed = True
break
if proceed:
# User to enter new cluster name
#newLabel, ok = QInputDialog.getText(self, 'Cluster name', 'Enter unique Cluster Name\t\t\t')
#if not ok:
#self.completeChanged.emit()
#return
names = [self.tboxes[ID].text() for ID in range(self.nclasses)]
nextNumber = 0
newLabel = 'Cluster_'+str(nextNumber)
names.append(newLabel)
while len(names) != len(set(names)):
del(names[-1])
nextNumber += 1
newLabel = 'Cluster_'+str(nextNumber)
names.append(newLabel)
# create new cluster ID, label
newID = len(self.clusters)
self.clusters[newID] = newLabel
self.nclasses += 1
print('after adding new cluster: ', self.clusters)
for ix in range(len(self.picbuttons)):
if self.picbuttons[ix].mark == 'yellow':
self.segments[ix][-1] = newID
self.picbuttons[ix].mark = 'green'
# Delete clusters with no members left and update self.clusters before adding the new cluster
todelete = []
for ID, label in self.clusters.items():
empty = True
for seg in self.segments:
if seg[-1] == ID:
empty = False
break
if empty:
todelete.append(ID)
# Generate new class labels
if len(todelete) > 0:
keys = [i for i in range(self.nclasses) if i not in todelete] # the old keys those didn't delete
# print('old keys left: ', keys)
nclasses = self.nclasses - len(todelete)
max_label = nclasses - 1
labels = []
c = self.nclasses - 1
while c > -1:
if c in keys:
labels.append((c, max_label))
max_label -= 1
c -= 1
# print('[old, new] labels')
labels = dict(labels)
print(labels)
# update clusters dictionary {ID: cluster_name}
clusters = {}
for i in keys:
clusters.update({labels[i]: self.clusters[i]})
print('before: ', self.clusters)
self.clusters = clusters
self.nclasses = nclasses
print('after: ', self.clusters)
# update the segments
for seg in self.segments:
seg[-1] = labels[seg[-1]]
# redraw the buttons
self.clearButtons()
self.updateButtons()
#self.cmbUpdateSeg.addItem(newLabel)
self.completeChanged.emit()
else:
msg = SupportClasses_GUI.MessagePopup("t", "Select", "Select calls to make the new cluster")
msg.exec_()
self.completeChanged.emit()
return
def deleteSelectedSegs(self):
""" Listener for Delete button to delete the selected segments completely.
"""
inds = []
for ix in range(len(self.picbuttons)):
if self.picbuttons[ix].mark == 'yellow':
inds.append(ix)
if len(inds)==0:
print("No segments selected")
return
self.segsChanged = True
for ix in reversed(inds):
del self.segments[ix]
del self.picbuttons[ix]
# update self.clusters, delete clusters with no members
todelete = []
for ID, label in self.clusters.items():
empty = True
for seg in self.segments:
if seg[-1] == ID:
empty = False
break
if empty:
todelete.append(ID)
self.clearButtons()
# Generate new class labels
if len(todelete) > 0:
keys = [i for i in range(self.nclasses) if i not in todelete] # the old keys those didn't delete
# print('old keys left: ', keys)
nclasses = self.nclasses - len(todelete)
max_label = nclasses - 1
labels = []
c = self.nclasses - 1
while c > -1:
if c in keys:
labels.append((c, max_label))
max_label -= 1
c -= 1
labels = dict(labels)
# print(labels)
# update clusters dictionary {ID: cluster_name}
clusters = {}
for i in keys:
clusters.update({labels[i]: self.clusters[i]})
print('before delete: ', self.clusters)
self.clusters = clusters
print('after delete: ', self.clusters)
# update the segments
for seg in self.segments:
seg[-1] = labels[seg[-1]]
self.nclasses = nclasses
# redraw the buttons
self.updateButtons()
self.completeChanged.emit()
def updateClusterNames(self):
# Check duplicate names
self.segsChanged = True
names = [self.tboxes[ID].text() for ID in range(self.nclasses)]
if len(names) != len(set(names)):
msg = SupportClasses_GUI.MessagePopup("w", "Name error", "Duplicate cluster names! \nTry again")
msg.exec_()
self.completeChanged.emit()
return
if "(Other)" in names:
msg = SupportClasses_GUI.MessagePopup("w", "Name error", "Name \"(Other)\" is reserved! \nTry again")
msg.exec_()
self.completeChanged.emit()
return
for ID in range(self.nclasses):
self.clusters[ID] = self.tboxes[ID].text()
self.completeChanged.emit()
print('updated clusters: ', self.clusters)
def addButtons(self):
""" Only makes the PicButtons and self.clusters dict
"""
self.picbuttons = []
if not self.hasCTannotations:
self.clusters = []
for i in range(self.nclasses):
self.clusters.append((i, 'Cluster_' + str(i)))
self.clusters = dict(self.clusters) # Dictionary of {ID: cluster_name}
# largest spec will be this wide
maxspecsize = max([seg[1][1]-seg[1][0] for seg in self.segments]) * self.field("fs") // 256
# Create the buttons for each segment
self.minsg = 1
self.maxsg = 1
for seg in self.segments:
sp = SignalProc.SignalProc(512, 256)
sp.readWav(seg[0], seg[1][1]-seg[1][0], seg[1][0], silent=True)
# set increment to depend on Fs to have a constant scale of 256/tgt seconds/px of spec
incr = 256 * sp.sampleRate // self.field("fs")
_ = sp.spectrogram(window='Hann', sgType='Standard',incr=incr, mean_normalise=True, onesided=True, need_even=False)
sg = sp.normalisedSpec("Log")
# buffer the image to largest spec size, so that the resulting buttons would have equal scale
if sg.shape[0]<maxspecsize:
padlen = int(maxspecsize - sg.shape[0])//2
sg = np.pad(sg, ((padlen, padlen), (0,0)), 'constant', constant_values=np.quantile(sg, 0.1))
self.minsg = min(self.minsg, np.min(sg))
self.maxsg = max(self.maxsg, np.max(sg))
newButton = SupportClasses_GUI.PicButton(1, np.fliplr(sg), sp.data, sp.audioFormat, seg[1][1]-seg[1][0], 0, seg[1][1], self.lut, cluster=True)
self.picbuttons.append(newButton)
# (updateButtons will place them in layouts and show them)
def selectAll(self):
""" Tick all buttons in the row and vise versa"""
for ID in range(len(self.cboxes)):
if self.cboxes[ID].isChecked():
for ix in range(len(self.segments)):
if self.segments[ix][-1] == ID:
self.picbuttons[ix].mark = 'yellow'
self.picbuttons[ix].buttonClicked = True
self.picbuttons[ix].setChecked(True)
self.picbuttons[ix].repaint()
else:
for ix in range(len(self.segments)):
if self.segments[ix][-1] == ID:
self.picbuttons[ix].mark = 'green'
self.picbuttons[ix].buttonClicked = False
self.picbuttons[ix].setChecked(False)
self.picbuttons[ix].repaint()
def updateButtons(self):
""" Draw the existing buttons, and create check- and text-boxes.
Called when merging clusters or initializing the page. """
self.cboxes = [] # List of check boxes
self.tboxes = [] # Corresponding list of text boxes
for r in range(self.nclasses):
c = 0
# print('**', self.clusters[r])
tbox = QLineEdit(self.clusters[r])
tbox.setMinimumWidth(80)
tbox.setMaximumHeight(150)
tbox.setStyleSheet("border: none;")
tbox.setAlignment(Qt.AlignCenter)
tbox.textChanged.connect(self.updateClusterNames)
self.tboxes.append(tbox)
self.flowLayout.addWidget(self.tboxes[-1], r, c)
c += 1
cbox = QCheckBox("")
cbox.clicked.connect(self.selectAll)
self.cboxes.append(cbox)
self.flowLayout.addWidget(self.cboxes[-1], r, c)
c += 1
# Find the segments under this class and show them
for segix in range(len(self.segments)):
if self.segments[segix][-1] == r:
self.flowLayout.addWidget(self.picbuttons[segix], r, c)
c += 1
self.picbuttons[segix].show()
self.flowLayout.adjustSize()
self.flowLayout.update()
# Apply colour and volume levels
self.specControls.emitAll()
def clearButtons(self):
""" Remove existing buttons, call when merging clusters
"""
for ch in self.cboxes:
ch.hide()
for tbx in self.tboxes:
tbx.hide()
for btnum in reversed(range(self.flowLayout.layout.count())):
item = self.flowLayout.layout.itemAt(btnum)
if item is not None:
self.flowLayout.layout.removeItem(item)
r, c = self.flowLayout.items[item.widget()]
del self.flowLayout.items[item.widget()]
del self.flowLayout.rows[r][c]
item.widget().hide()
self.flowLayout.update()
def setColourLevels(self, brightness, contrast):
""" Listener for the brightness and contrast sliders being changed. Also called when spectrograms are loaded, etc.
Translates the brightness and contrast values into appropriate image levels.
"""
brightness = 100-brightness
colRange = colourMaps.getColourRange(self.minsg, self.maxsg, brightness, contrast, False)
for btn in self.picbuttons:
btn.stopPlayback()
btn.setImage(colRange)
btn.update()
def volSliderMoved(self, value):
# try/pass to avoid race situations when smth is not initialized
try:
for btn in self.picbuttons:
btn.media_obj.applyVolSlider(value)
except Exception:
pass
# page 4 - set params for training
class WPageParams(QWizardPage):
def __init__(self, method, cluster, segments, picbtn, parent=None):
super(BuildRecAdvWizard.WPageParams, self).__init__(parent)
self.setTitle("Training parameters: %s" % cluster)
self.setSubTitle("These fields were completed using the training data. Adjust if required.\nWhen ready, "
"press \"Train\". The process may take a long time.")
#self.setMinimumSize(350, 430)
self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)
self.adjustSize()
self.method = method
self.lblSpecies = QLabel("")
self.lblSpecies.setStyleSheet("QLabel { color : #808080; }")
self.numSegs = QLabel("")
self.numSegs.setStyleSheet("QLabel { color : #808080; }")
self.segments = segments
lblCluster = QLabel(cluster)
lblCluster.setStyleSheet("QLabel { color : #808080; }")
# small image of the cluster and other info
calldescr = QFormLayout()
calldescr.addRow('Species:', self.lblSpecies)
calldescr.addRow('Call type:', lblCluster)
calldescr.addRow('Number of segments:', self.numSegs)
imgCluster = QLabel()
imgCluster.setFixedHeight(100)
picimg = QPixmap.fromImage(picbtn.im1)
imgCluster.setPixmap(picimg.scaledToHeight(100))
# TimeRange parameters
form1_step4 = QFormLayout()
if method=="wv":
self.minlen = QLineEdit(self)
form1_step4.addRow('Min call length (sec)', self.minlen)
self.maxlen = QLineEdit(self)
form1_step4.addRow('Max call length (sec)', self.maxlen)
self.avgslen = QLineEdit(self)
form1_step4.addRow('Avg syllable length (sec)', self.avgslen)
self.maxgap = QLineEdit(self)
form1_step4.addRow('Max gap between syllables (sec)', self.maxgap)
elif method=="chp":
self.chpwin = QLineEdit(self)
form1_step4.addRow('Window size (sec)', self.chpwin)
self.minlen = QLineEdit(self)
form1_step4.addRow('Min call length (sec)', self.minlen)
self.maxlen = QLineEdit(self)
form1_step4.addRow('Max call length (sec)', self.maxlen)
else:
print("ERROR: unrecognized method", method)
return
# FreqRange parameters
self.fLow = QSlider(Qt.Horizontal)
self.fLow.setTickPosition(QSlider.TicksBelow)
self.fLow.setTickInterval(2000)
self.fLow.setRange(0, 32000)
self.fLow.setSingleStep(100)
self.fLow.valueChanged.connect(self.fLowChange)
self.fLowtext = QLabel('')
form1_step4.addRow('', self.fLowtext)
form1_step4.addRow('Lower frq. limit (Hz)', self.fLow)
self.fHigh = QSlider(Qt.Horizontal)
self.fHigh.setTickPosition(QSlider.TicksBelow)
self.fHigh.setTickInterval(2000)
self.fHigh.setRange(0, 32000)
self.fHigh.setSingleStep(100)
self.fHigh.valueChanged.connect(self.fHighChange)
self.fHightext = QLabel('')
form1_step4.addRow('', self.fHightext)
form1_step4.addRow('Upper frq. limit (Hz)', self.fHigh)
### Step4 layout
hboxTop = QHBoxLayout()
hboxTop.addLayout(calldescr)
hboxTop.addSpacing(30)
hboxTop.addWidget(imgCluster)
layout_step4 = QVBoxLayout()
layout_step4.setSpacing(10)
layout_step4.addWidget(QLabel("<b>Current call type</b>"))
layout_step4.addLayout(hboxTop)
layout_step4.addWidget(QLabel("<b>Call parameters</b>"))
layout_step4.addLayout(form1_step4)
self.setLayout(layout_step4)
self.setButtonText(QWizard.NextButton, 'Train >')
def fLowChange(self, value):
value = value//10*10
if value < 0:
value = 0
self.fLow.setValue(value)
self.fLowtext.setText(str(value))
def fHighChange(self, value):
value = value//10*10
if value < 100:
value = 100
self.fHigh.setValue(value)
self.fHightext.setText(str(value))
def initializePage(self):
self.wizard().saveTestBtn.setVisible(False)
# populates values based on training files
fs = int(self.field("fs")) // 4000 * 4000
# self.segments is already selected to be this cluster only
pageSegs = Segment.SegmentList()
for longseg in self.segments:
# long seg has format: [file [segment] clusternum]
pageSegs.addSegment(longseg[1])
len_min, len_max, f_low, f_high = pageSegs.getSummaries()
self.maxlen.setText(str(round(np.max(len_max),2)))