Skip to content

segment: amplitude variance from Alam Zia Roberts 2024 #168

Open

Description

@NickleDave

Algorithm used in this paper:
https://www.nature.com/articles/s41586-024-07207-4

They report in results:

DAN first calculates the variance of the raw audio files, applying a Gaussian filter to smooth fluctuations, and uses thresholding to reliably identify periods of silence and sound. Automated segmentation, based on the first derivative of the amplitude variance, then provides highly accurate identification of individual sounds (Extended Data Fig. 1; the average duration of DAN-segmented syllables and introductory notes is within less than 1.0 ms of hand-labelled data).

< 1.0 ms of hand-labelled data sounds great! Where is this hand-labeled data I can verify with

Further description in methods:

Amplitude variance was calculated on recorded raw SAP audio files. We then applied a Gaussian filter to the resulting amplitude variance. To identify onsets and offsets of sound and silence, we directed the identification of local maxima and local minima in the lower range of the variance. Once the range was defined, we calculated the first derivative of the amplitude variance to identify periods of transition from silence to sound and sound to silence. These onset and offset times were used to segment the audio file into audio segments.

We should include as a reference algorithm for zebra finch.

Code, from here:
https://dataverse.tdl.org/dataset.xhtml?persistentId=doi:10.18738/T8/WBQM4I

for i in tqdm(range(Start, End)):
            
            Times= []
            foldername= self.FolderBrowse_lineEdit.text() + '/'

            dayname= str(i)
            folderday= os.path.join(foldername, dayname)
            waves= '*wav'
            folderday1= os.path.join(folderday, waves)
            filenames = sorted(glob.glob(folderday1))
            audiofile = filenames
            path = (folderday)
            output_folder= Path(foldername+dayname)
            output_dir = os.path.join(output_folder, 'Segments/')
            output_csv = os.path.join(foldername,dayname,'SegmentTimes.csv')

            with open(output_csv, 'w') as file:
                writer = csv.writer(file)
                writer.writerow(header)
            if not os.path.isdir(output_dir):
                os.makedirs(output_dir)
            for f in tqdm(audiofile):
                
                sr, x = scipy.io.wavfile.read(f)
        
                times = np.arange(len(x))/float(sr)
                
                fx= x/float(1)
        
                chunks = np.array_split(fx, (len(x)/10))
        
                variance=[]
        
                for i in chunks:
                    var= np.var(i)
                    variance.append(var)
        
        
                gaussianvariance=gaussian_filter(variance, sigma=10)
                thresholdmin= float(self.LowerThreshold.text())

                threshold= thresholdmin+7000
                
                gaussianvariance[gaussianvariance > threshold] = threshold
                gaussianvariance[gaussianvariance < thresholdmin] = thresholdmin
        
                
                chunks2 = librosa.util.frame(gaussianvariance, frame_length=10, hop_length=20,axis=0)
                
                mean=[]
                for i in chunks2:
                    m= np.mean(i)
                    mean.append(m)
        
                
                diff= np.diff(mean)
                peaks, _ = find_peaks(diff,distance=10, height=((np.percentile(diff, 97))))
                if len(peaks) > 0:
            
                    peaks= peaks - 1
        
                    
                    diff2= np.diff(mean)
                    diff2[diff2 > 0] = 0
                    
                    mins, _ =find_peaks(diff2*-1,distance=10, height=((np.percentile(diff2, 97))))
                    mins=np.append(mins,(peaks[-1]+1))
            
            
            
                    mins1= np.array([mins[mins > i].min() for i in peaks])
                    mins1= mins1 + 1
            
            
            
                    
                    peaks= peaks * 20
                    mins1= mins1 * 20
                    
           
                    
                    gaussianvariance=np.repeat(gaussianvariance, 10)
                    variance=np.repeat(variance, 10)
            
                    maybe=[]
                    for i in range(len(peaks)):
                        maybe.append(peaks[i]*10)
                        maybe.append(mins1[i]*10)
                        
            
                    
                    lengthinseconds=len(x)/44100
                    lengthofeachelement= lengthinseconds/len(x)
                    yvalues=np.arange(0, len(gaussianvariance),1)
                    timesm= np.arange(0, lengthinseconds,lengthofeachelement )
                    timesofvariance= yvalues
                    listofframe=[]
                    for i in range(len(timesofvariance)):
                        A=timesofvariance[i]     
                        B=timesm[A]    
                        listofframe.append(B)
            
                    sound_times=[]
                    #first = 0
                    #sound_times.append(first)
                    for i in range(len(maybe)):
                        A=maybe[i]            
                        B=listofframe[A]    
                        sound_times.append(B)
                    
                    onset_offset= pd.DataFrame(sound_times)
                    onset_offset.columns= ['Onset']    
                    onset_values = pd.DataFrame(onset_offset['Onset'].iloc[0::2].values)                           
                    offset_values= pd.DataFrame(onset_offset['Onset'].iloc[1::2].values)
                    onset_offset_times = pd.concat([onset_values,offset_values], axis =1)
                    onset_offset_times.columns= ['Onset', 'Offset']
                    onset_offset_times = onset_offset_times.dropna()
                       
                    seg_lims = onset_offset_times.values.tolist()
                    seglimits = np.asarray(seg_lims)
                    fdc= (len(seglimits[:]))
                    segmentlimits=pd.DataFrame(np.array(seglimits), columns=['Start', 'Stop'])
                    newseglimitsStart=[]
                    newseglimitsStop=[]
                    for index, row in segmentlimits.iterrows():
                        Duration=row.Stop-row.Start
                        if Duration > 0.04:
                            newseglimitsStart.append(row.Start)
                            newseglimitsStop.append(row.Stop)
                    seglimits=np.vstack((newseglimitsStart,newseglimitsStop)).T
                    if fdc > 0 :
                        sl= pd.DataFrame(np.array(seglimits), columns=['Start', 'Stop'])
                        times= [None] * 5
                        for index, row in sl.iterrows():
                            #SegmentStart = (row.Start *1000)-20
                            #SegmentStop = (row.Stop * 1000)+25
                            SegmentStart = (row.Start * 1000)
                            if SegmentStart < 0:
                                SegmentStart= np.float64(0)
                            SegmentStop = (row.Stop * 1000)
                            SegmentStart2 = row.Start
                            SegmentStop2 = row.Stop
                            SegmentStart1 = SegmentStart
                            SegmentStart1 = SegmentStart1.clip(min=0) 
                            SegmentStart1 = SegmentStart1
                            SegmentStart1 = SegmentStart1/10
                            SegmentedSong = AudioSegment.from_file(f)
                            SegmentedSong = SegmentedSong[SegmentStart:SegmentStop]
                            i= index
                            SegmentSongName = (output_dir + f[len(path):-4] + "_{}.wav".format(i))
                            SegmentedSong.export(SegmentSongName, format="wav")
                            sr, x = scipy.io.wavfile.read(SegmentSongName)
                            Duration= SegmentStop2-SegmentStart2
            
                            SegmentStart1 = SegmentStart1.clip(min=0)  
                            times[0] = f
                            times[1] = SegmentSongName
                            times[2] = SegmentStart2
                            times[3] = SegmentStop2
                            times[4] = Duration
                 
                            with open(output_csv, 'a', newline='') as v:
                                writer = csv.writer(v)
                                writer.writerows([times])
                            Times.append(times)

Activity

  1. added
    Segmentation
    on Jun 2, 2024
  2. self-assigned this
    on Jun 2, 2024
  3. added this to vocalpy-0.11.0 and removed this from vocalpy-0.10.0on Dec 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Segmentation

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions