Measuring surprisal in sound sequences.
The 2 matches
- [1] § General discussion ↔ analysis/SSM.R, lines 1–106 · score 0.54 · auditory spectrograms, syllable, tune, STFT, segmentation, SSM
- [2] § General discussion ↔ analysis/surprisal.R, lines 421–504 · score 0.50 · amplitude envelope, auditory spectrograms, tune, windows, surprisal
Paper
Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
R · 692 lines · 24 KB · no license · 1 match
- #' Self-similarity matrix
- #'
- #' Calculates the self-similarity matrix and novelty vector of a sound. The
- #' self-similarity matrix is produced by cross-correlating different segments of
- #' the input sound. Novelty is calculated by convolving the self-similarity
- #' matrix with a tapered checkerboard kernel. The positive lobes of the kernel
- #' represent coherence (self-similarity within the regions on either side of the
- #' center point) and the negative lobes anti-coherence (cross-similarity
- #' between these two regions). Since novelty is the dot product of the
- #' checkerboard kernel with the SSM, it is high when the two regions are
- #' self-similar (internally consistent) but different from each other.
- #'
- #' @seealso \code{\link{spectrogram}} \code{\link{modulationSpectrum}}
- #' \code{\link{segment}}
- #'
- #' @references \itemize{
- #' \item Foote, J. (1999, October). Visualizing music and
- #' audio using self-similarity. In Proceedings of the seventh ACM
- #' international conference on Multimedia (Part 1) (pp. 77-80). ACM.
- #' \item
- #' Foote, J. (2000). Automatic audio segmentation using a measure of audio
- #' novelty. In Multimedia and Expo, 2000. ICME 2000. 2000 IEEE International
- #' Conference on (Vol. 1, pp. 452-455). IEEE.
- #' }
- #' @inheritParams spectrogram
- #' @inheritParams analyze
- #' @param sparse if TRUE, the entire SSM is not calculated, but only the central
- #' region needed to extract the novelty contour (speeds up the processing)
- #' @param input the spectral representation used to calculate the SSM: "audSpec"
- #' = auditory spectrogram returned by \code{\link{audSpectrogram}}, "mfcc" =
- #' Mel-Frequency Cepstral coefficients, "melspec" = Mel-transformed STFT
- #' spectrogram, "spec" = STFT power spectrogram (all three returned by
- #' \code{\link[tuneR]{melfcc}}). Any custom spectrogram-like matrix of
- #' features (time in columns labeled in s, features in rows) is also accepted
- #' (see examples)
- #' @param takeLog if TRUE, the input is log-transformed prior to calculating
- #' self-similarity
- #' @param MFCC which mel-frequency cepstral coefficients to use; defaults to
- #' \code{2:13}
- #' @param melfcc_pars a list of parameters passed to \code{\link[tuneR]{melfcc}}
- #' @param audSpec_pars a list of parameters passed to
- #' \code{\link{audSpectrogram}} (if input = 'audSpec')
- #' @param norm if TRUE, the spectrum of each STFT frame is normalized
- #' @param simil method for comparing frames: "cosine" = cosine similarity, "cor"
- #' = Pearson's correlation
- #' @param kernelLen length of checkerboard kernel for calculating novelty, ms
- #' (larger values favor global, slow vs. local, fast novelty)
- #' @param kernelSD SD of checkerboard kernel for calculating novelty
- #' @param padWith how to treat edges when calculating novelty: NA = treat sound
- #' before and after the recording as unknown, 0 = treat it as silence
- #' @param ssmWin window for averaging SSM, frames (has a smoothing effect and
- #' speeds up the processing)
- #' @param output what to return (drop "ssm" to save memory when analyzing a lot
- #' of files)
- #' @param plot if TRUE, plots the SSM
- #' @param heights relative sizes of the SSM and spectrogram/novelty plot
- #' @param main plot title
- #' @param specPars graphical parameters passed to \code{filled.contour.mod} and
- #' affecting the \code{\link{spectrogram}}
- #' @param ssmPars graphical parameters passed to \code{filled.contour.mod} and
- #' affecting the plot of SSM
- #' @param noveltyPars graphical parameters passed to
- #' \code{\link[graphics]{lines}} and affecting the novelty contour
- #' @return Returns a list of two components: $ssm contains the self-similarity
- #' matrix, and $novelty contains the novelty vector.
- #' @export
- #' @examples
- #' sound = c(soundgen(),
- #' soundgen(nSyl = 4, sylLen = 50, pauseLen = 70,
- #' formants = NA, pitch = c(500, 330)))
- #' # playme(sound)
- #' # detailed, local features (captures each syllable)
- #' s1 = ssm(sound, samplingRate = 16000, kernelLen = 100,
- #' sparse = TRUE) # much faster with 'sparse'
- #' # more global features (captures the transition b/w the two sounds)
- #' s2 = ssm(sound, samplingRate = 16000, kernelLen = 400, sparse = TRUE)
- #'
- #' s2$summary
- #' s2$novelty # novelty contour
- #' \dontrun{
- #' ssm(sound, samplingRate = 16000,
- #' input = 'mfcc', simil = 'cor', norm = TRUE,
- #' ssmWin = 10, # speed up the processing
- #' kernelLen = 300, # global features
- #' specPars = list(colorTheme = 'seewave'),
- #' ssmPars = list(col = rainbow(100)),
- #' noveltyPars = list(type = 'l', lty = 3, lwd = 2))
- #'
- #' # Custom input: produce a nice spectrogram first, then feed it into ssm()
- #' sp = spectrogram(sound, 16000, windowLength = c(5, 40), contrast = .3,
- #' output = 'processed') # return the modified spectrogram
- #' colnames(sp) = as.numeric(colnames(sp)) / 1000 # convert ms to s
- #' ssm(sound, 16000, kernelLen = 400, input = sp)
- #'
- #' # Custom input: use acoustic features returned by analyze()
- #' an = analyze(sound, 16000, windowLength = 20, novelty = NULL)
- #' input_an = t(an$detailed[, 4:ncol(an$detailed)]) # or select pitch, HNR, ...
- #' input_an = t(apply(input_an, 1, scale)) # z-transform all variables
- #' input_an[is.na(input_an)] = 0 # get rid of NAs
- #' colnames(input_an) = an$detailed$time / 1000 # time stamps in s
- #' rownames(input_an) = 1:nrow(input_an)
- #' image(t(input_an)) # not a spectrogram, just a feature matrix
- #' ssm(sound, 16000, kernelLen = 500, input = input_an, takeLog = FALSE,
- #' specPars = list(ylab = 'Feature'))
- #' }
- ssm = function(
- x,
- samplingRate = NULL,
- from = NULL,
- to = NULL,
- sparse = FALSE,
- input = c('melspec', 'mfcc', 'spec', 'audSpec')[1],
- melfcc_pars = list(windowLength = 125, step = 25, nbands = 50),
- MFCC = 2:13,
- audSpec_pars = list(nFilters = 16, step = 10),
- takeLog = FALSE,
- norm = FALSE,
- simil = c('cosine', 'cor')[1],
- kernelLen = 1000,
- kernelSD = .5,
- padWith = 0,
- ssmWin = NULL,
- summaryFun = c('mean', 'sd'),
- output = c('ssm', 'novelty', 'summary'),
- reportEvery = NULL,
- cores = 1,
- plot = TRUE,
- savePlots = NULL,
- main = NULL,
- heights = c(2, 1),
- width = 900,
- height = 500,
- units = 'px',
- res = NA,
- specPars = list(
- colorTheme = c('bw', 'seewave', 'heat.colors', '...')[2],
- xlab = 'Time, s'
- ),
- ssmPars = list(
- colorTheme = c('bw', 'seewave', 'heat.colors', '...')[2],
- xlab = 'Time, s',
- ylab = 'Time, s'
- ),
- noveltyPars = list(
- type = 'b',
- pch = 16,
- col = 'black',
- lwd = 3
- )) {
- ## Prepare a list of arguments to pass to .ssm()
- myPars = as.list(environment())
- # exclude unnecessary args
- myPars = myPars[!names(myPars) %in% c(
- 'x', 'samplingRate', 'from', 'to', 'savePlots', 'reportEvery', 'cores',
- 'summaryFun', 'specPars', 'ssmPars', 'noveltyPars', 'ssmWin',
- 'melfcc_pars', 'audSpec_pars')]
- myPars$specPars = specPars
- myPars$ssmPars = ssmPars
- myPars$noveltyPars = noveltyPars
- myPars$melfcc_pars = melfcc_pars
- myPars$audSpec_pars = audSpec_pars
- myPars$win = ssmWin
- # analyze
- pa = processAudio(
- x,
- samplingRate = samplingRate,
- from = from,
- to = to,
- funToCall = '.ssm',
- myPars = myPars,
- reportEvery = reportEvery,
- cores = cores,
- savePlots = savePlots
- )
- # htmlPlots
- if (!is.null(pa$input$savePlots) && pa$input$n > 1) {
- try(htmlPlots(pa$input, savePlots = savePlots, changesAudio = FALSE,
- suffix = "ssm", width = paste0(width, units)))
- }
- # prepare output
- if (!is.null(summaryFun) && any(!is.na(summaryFun))) {
- temp = vector('list', pa$input$n)
- for (i in 1:pa$input$n) {
- if (!pa$input$failed[i]) {
- temp[[i]] = summarizeAnalyze(
- data.frame(novelty = pa$result[[i]]$novelty),
- summaryFun = summaryFun,
- var_noSummary = NULL)
- }
- }
- idx_failed = which(pa$input$failed)
- if (length(idx_failed) > 0) {
- idx_ok = which(!pa$input$failed)
- if (length(idx_ok) > 0) {
- filler = temp[[idx_ok[1]]] [1, ]
- filler[1, ] = NA
- } else {
- stop('Failed to analyze any input')
- }
- for (i in idx_failed) temp[[i]] = filler
- }
- mysum_all = cbind(data.frame(file = pa$input$filenames_base),
- do.call('rbind', temp))
- } else {
- mysum_all = NULL
- }
- if (pa$input$n == 1) {
- # unlist
- ssm = pa$result[[1]]$ssm
- novelty = pa$result[[1]]$novelty
- } else {
- ssm = lapply(pa$result, function(x) x[['ssm']])
- novelty = lapply(pa$result, function(x) x[['novelty']])
- }
- out = list(ssm = ssm, novelty = novelty, summary = mysum_all)
- invisible(out[which(names(out) %in% output)])
- }
- #' SSM per sound
- #'
- #' Internal soundgen function.
- #' @inheritParams ssm
- #' @param audio a list returned by \code{readAudio}
- #' @keywords internal
- .ssm = function(
- audio,
- sparse = FALSE,
- input = c('melspec', 'mfcc', 'spec', 'audSpec')[1],
- melfcc_pars = list(windowLength = 125, step = 25, nbands = 50),
- MFCC = 2:13,
- audSpec_pars = list(nFilters = 16, step = 10),
- takeLog = FALSE,
- norm = FALSE,
- simil = c('cosine', 'cor')[1],
- kernelLen = 100,
- kernelSD = .5,
- padWith = 0,
- win = 1,
- output = c('ssm', 'novelty', 'summary'),
- plot = TRUE,
- main = NULL,
- heights = c(2, 1),
- width = 900,
- height = 500,
- units = 'px',
- res = NA,
- specPars = list(
- colorTheme = c('bw', 'seewave', 'heat.colors', '...')[2],
- xlab = 'Time, s',
- ylab = 'kHz'
- ),
- ssmPars = list(
- colorTheme = c('bw', 'seewave', 'heat.colors', '...')[2],
- xlab = 'Time, s',
- ylab = 'Time, s'
- ),
- noveltyPars = list(
- type = 'b',
- pch = 16,
- col = 'black',
- lwd = 3
- )) {
- nyquist = audio$samplingRate / 2
- if (is.matrix(input)) {
- # custom input to SSM - use as is
- target_spec = as.matrix(input)
- step = diff(as.numeric(colnames(target_spec))[1:2])
- frame_points = round(audio$samplingRate * step)
- input = 'custom'
- } else {
- ## compute mel-filtered spectrum and MFCCs
- if (input == 'audSpec') {
- # call audSpectrogram()
- if (is.null(audSpec_pars$nFilters)) audSpec_pars$nFilters = 32
- if (is.null(audSpec_pars$step)) audSpec_pars$step = 20
- frame_points = round(audio$samplingRate * audSpec_pars$step / 1000)
- target_spec = do.call(.audSpectrogram, c(audSpec_pars, list(
- audio = audio,
- plot = FALSE
- )))$audSpec # cols = time, rows = freq
- colnames(target_spec) = as.numeric(colnames(target_spec)) / 1000 # ms to s
- } else if (input %in% c('mfcc', 'spec', 'melspec')) {
- # call tuneR::melfcc()
- if (is.null(melfcc_pars$windowLength)) melfcc_pars$windowLength = 25
- if (is.null(melfcc_pars$step)) melfcc_pars$step = 5
- frame_points = round(audio$samplingRate * melfcc_pars$step / 1000)
- if (!is.numeric(melfcc_pars$windowLength) | melfcc_pars$windowLength <= 0 |
- melfcc_pars$windowLength > (audio$duration / 2 * 1000)) {
- melfcc_pars$windowLength = min(50, round(audio$duration / 2 * 1000))
- warning(paste0(
- '"windowLength" must be between 0 and half the sound duration (in ms);
- resetting to ', melfcc_pars$windowLength, ' ms')
- )
- }
- if (is.null(melfcc_pars$step))
- melfcc_pars$step = melfcc_pars$windowLength / 4
- if (is.null(melfcc_pars$nbands)) {
- melfcc_pars$nbands = round(100 * melfcc_pars$windowLength / 20)
- }
- windowLength_points = floor(melfcc_pars$windowLength / 1000 *
- audio$samplingRate / 2) * 2
- if (is.null(melfcc_pars$maxfreq)) {
- melfcc_pars$maxfreq = floor(audio$samplingRate / 2) # Nyquist
- }
- sound = tuneR::Wave(left = audio$sound, samp.rate = audio$samplingRate, bit = 16)
- mel = do.call(tuneR::melfcc, c(
- melfcc_pars[which(!names(melfcc_pars) %in% c('windowLength', 'step'))],
- list(
- samples = sound,
- wintime = melfcc_pars$windowLength / 1000,
- hoptime = melfcc_pars$step / 1000,
- spec_out = TRUE,
- numcep = max(MFCC)
- )))
- if (input == 'mfcc') {
- # the first cepstrum presumably makes no sense with amplitude normalization
- # (?), and it overestimates the similarity of different frames
- target_spec = t(mel$cepstra)[MFCC, ]
- target_spec[is.na(target_spec)] = 0 # MFCC are NaN for silent frames
- colnames(target_spec) = seq(audio$timeShift, audio$duration,
- length.out = ncol(target_spec))
- rownames(target_spec) = 1:nrow(target_spec)
- } else if (input == 'melspec') {
- target_spec = t(mel$aspectrum) # cols = time, rows = freq
- colnames(target_spec) = seq(audio$timeShift, audio$duration,
- length.out = ncol(target_spec))
- rownames(target_spec) = otherToHz(
- seq(0, HzToOther(nyquist, "mel"),
- length.out = nrow(target_spec)), "mel") / 1000
- } else if (input == 'spec') {
- target_spec = t(mel$pspectrum) # cols = time, rows = freq
- colnames(target_spec) = seq(audio$timeShift, audio$duration,
- length.out = ncol(target_spec))
- rownames(target_spec) = seq(0, nyquist,
- length.out = nrow(target_spec)) / 1000
- }
- }
- }
- if (takeLog) {
- target_spec = target_spec - min(target_spec, na.rm = TRUE)
- target_spec = log(target_spec + min(target_spec[target_spec > 0], na.rm = TRUE))
- }
- # image(t(target_spec))
- ## compute self-similarity matrix
- # kernel size in frames, guaranteed to be even
- kernelSize = max(4, round(kernelLen * audio$samplingRate / 1000 /
- frame_points / 2) * 2)
- s = selfsim(
- m = target_spec,
- norm = norm,
- simil = simil,
- win = win,
- sparse = sparse,
- kernelSize = kernelSize
- )
- # s = zeroOne(s^2) # hist(s)
- # image(s)
- ## compute novelty
- novelty = getNovelty(ssm = s, kernelSize = kernelSize,
- kernelSD = kernelSD, padWith = padWith)
- ## PLOTTING
- if (is.character(audio$savePlots)) {
- plot = TRUE
- png(filename = paste0(audio$savePlots, audio$filename_noExt, "_ssm.png"),
- width = width, height = height, units = units, res = res)
- }
- if (plot) {
- if (is.null(main)) {
- if (audio$filename_base == 'sound') {
- main = ''
- } else {
- main = audio$filename_base
- }
- }
- op = par(c('mar', 'xaxt', 'yaxt', 'mfrow')) # save user's original pars
- layout(matrix(c(2, 1), nrow = 2, byrow = TRUE), heights = heights)
- par(mar = c(5.1, 4.1, 0, 2.1),
- xaxt = 's',
- yaxt = 's')
- # spectrogram
- if (input == 'audSpec') {
- # spec = zeroOne(t(log(target_spec + 1e-4)))
- spec = t(target_spec)
- specPars1 = list(
- colorTheme = 'seewave',
- xlab = 'Time, s',
- ylab = 'kHz'
- )
- specPars1[names(specPars)] = specPars
- specPars1$color.palette = switchColorTheme(specPars1$colorTheme)
- specPars1[['colorTheme']] = NULL
- do.call(filled.contour.mod, c(list(
- x = as.numeric(rownames(spec)),
- y = as.numeric(colnames(spec)),
- z = spec,
- yScale = if (is.null(audSpec_pars$yScale)) 'bark' else audSpec_pars$yScale
- ), specPars1))
- specPars1$xlim = range(as.numeric(rownames(spec)))
- specPars1$ylim = range(as.numeric(colnames(spec)))
- } else {
- # # log-transform and normalize spectrogram
- # if (input == 'melspec') {
- # spec = log(zeroOne(mel$aspectrum) + 1e-4) # dynamic range ~ 80 dB or 1e-4
- # } else {
- # spec = log(zeroOne(mel$pspectrum) + 1e-4)
- # }
- # spec = zeroOne(spec)
- spec = t(target_spec)
- specPars1 = list(
- colorTheme = 'seewave',
- xlab = 'Time, s',
- ylab = if (input %in% c('custom', 'mfcc')) input else 'kHz'
- )
- specPars1[names(specPars)] = specPars
- specPars1$color.palette = switchColorTheme(specPars1$colorTheme)
- specPars1[['colorTheme']] = NULL
- do.call(filled.contour.mod, c(list(
- x = as.numeric(rownames(spec)),
- y = as.numeric(colnames(spec)),
- z = spec,
- yScale = if (input == 'melspec') 'mel' else 'linear'
- ), specPars1
- ))
- }
- specPars1$xlim = c(audio$timeShift, audio$duration)
- specPars1$ylim = range(as.numeric(rownames(target_spec)))
- if (input == 'melspec')
- specPars1$ylim = HzToOther(specPars1$ylim * 1000, 'mel')
- # novelty
- noveltyPars1 = list(
- type = 'b',
- pch = 16,
- col = 'black',
- lwd = 3
- )
- noveltyPars1[names(noveltyPars)] = noveltyPars
- do.call(lines, c(list(
- x = seq(specPars1$xlim[1], specPars1$xlim[2], length.out = length(novelty)),
- y = zeroOne(novelty) * specPars1$ylim[2] * .95
- ), noveltyPars1
- ))
- axis(side = 1, labels = TRUE)
- par(mar = c(0, 4.1, 2.1, 2.1),
- xaxt = 'n',
- yaxt = 's')
- xlab = ''
- # SSM
- ssmPars1 = list(
- levels = seq(0, 1, length = 30),
- colorTheme = 'seewave',
- xlab = 'Time, s',
- ylab = 'Time, s',
- main = main
- )
- ssmPars1[names(ssmPars)] = ssmPars
- ssmPars1$color.palette = switchColorTheme(ssmPars1$colorTheme)
- ssmPars1[['colorTheme']] = NULL
- timestamps_ssm = seq(0, audio$duration, length.out = nrow(s))
- do.call(filled.contour.mod, c(list(
- x = timestamps_ssm,
- y = timestamps_ssm,
- z = s,
- y_Hz = FALSE
- ), ssmPars1
- ))
- # restore original pars
- par('mar' = op$mar, 'xaxt' = op$xaxt, 'yaxt' = op$yaxt, 'mfrow' = op$mfrow)
- if (is.character(audio$savePlots)) dev.off()
- }
- out = list(ssm = s, novelty = novelty)
- invisible(out[which(names(out) %in% output)])
- }
- #' Compute self-similarity
- #'
- #' Internal soundgen function.
- #'
- #' Called by \code{\link{ssm}}.
- #' @param m input matrix such as a spectrogram
- #' @inheritParams ssm
- #' @param win the length of window for averaging self-similarity, frames
- #' @return Returns a square self-similarity matrix.
- #' @keywords internal
- #' @examples
- #' m = matrix(rnorm(40), nrow = 5)
- #' soundgen:::selfsim(m, sparse = TRUE, kernelSize = 2)
- selfsim = function(m,
- norm = FALSE,
- simil = c('cosine', 'cor')[1],
- win = 1,
- sparse = FALSE,
- kernelSize = NULL) {
- nc = ncol(m)
- if (win > floor(nc / 2)) {
- win = floor(nc / 2)
- warning(paste('"win" must be smaller than half the number of frames',
- 'resetting to', floor(nc / 2)))
- }
- if (win %% 2 == 0) {
- win = max(ceiling(win / 2) * 2 - 1, 1)
- } # win must be odd
- # normalize input by column, if needed
- if (norm) {
- m = apply(m, 2, zeroOne, na.rm = TRUE)
- m[is.na(m)] = 0
- }
- # calculate windows for averaging self-similarity
- winIdx = unique(round(seq(1, nc - win + 1, length.out = ceiling(nc / win))))
- numWins = length(winIdx)
- # calculate the lower triangle of self-similarity matrix
- out = matrix(NA, nrow = numWins, ncol = numWins)
- rownames(out) = colnames(out) = winIdx
- if (!sparse) j_idx = seq_len(numWins)
- for (i in seq_along(winIdx)) {
- if (sparse) {
- j_idx = max(1, i - kernelSize) : max(1, (i - 1))
- } else {
- j_idx = 1:max(1, (i - 1))
- }
- for (j in j_idx) {
- mi = as.vector(m[, winIdx[i]:(winIdx[i] + win - 1)])
- mj = as.vector(m[, winIdx[j]:(winIdx[j] + win - 1)])
- if (any(mi != 0) && any(mj != 0)) {
- if (simil == 'cosine') {
- # http://stackoverflow.com/questions/6597005/cosine-similarity-between-two-vectors-in-language-r
- out[i, j] = crossprod(mi, mj) / sqrt(crossprod(mi) * crossprod(mj))
- } else if (simil == 'cor') {
- out[i, j] = cor(mi, mj)
- }
- } else {
- # if at least one is a vector of zeros, set result to 0 (otherwise NA)
- out[i, j] = 0
- }
- }
- }
- # fill up the upper triangle as well
- diag(out) = 1
- out1 = t(out)
- out1[lower.tri(out1)] = out[lower.tri(out)]
- # isSymmetric(out1)
- # image(out1)
- zeroOne(t(out1), na.rm = TRUE)
- }
- #' Checkerboard kernel
- #'
- #' Internal soundgen function.
- #'
- #' Prepares a square matrix \code{size x size} specifying a gaussian kernel for
- #' measuring novelty of self-similarity matrices. Called by
- #' \code{\link{getNovelty}}
- #' @param size kernel size (points), preferably an even number
- #' @param kernel_mean,kernelSD mean and SD of the gaussian kernel
- #' @param plot if TRUE, shows a perspective plot of the kernel
- #' @param checker if TRUE, inverts two quadrants
- #' @return Returns a square matrix with \code{size} rows and columns.
- #' @keywords internal
- #' @examples
- #' kernel = soundgen:::getCheckerboardKernel(size = 64, kernelSD = 0.1, plot = TRUE)
- #' dim(kernel)
- #' kernel = soundgen:::getCheckerboardKernel(size = 19, kernelSD = .5,
- #' checker = FALSE, plot = TRUE)
- #' kernel = soundgen:::getCheckerboardKernel(size = c(9, 45), kernelSD = .5,
- #' checker = FALSE, plot = TRUE)
- #' kernel = soundgen:::getCheckerboardKernel(size = c(9, 45), kernelSD = .5,
- #' checker = TRUE, plot = TRUE)
- getCheckerboardKernel = function(size,
- kernel_mean = 0,
- kernelSD = 0.5,
- plot = FALSE,
- checker = TRUE) {
- if (length(size) == 1) {
- x = y = seq(-1, 1, length.out = size)
- size = c(size, size)
- } else if (length(size) == 2) {
- x = seq(-1, 1, length.out = size[1])
- y = seq(-1, 1, length.out = size[2])
- } else {
- stop('size must be of length 1 or 2')
- }
- kernelSD = kernelSD # just to get rid of the "unused arg" warning in CMD check :-)
- if (max(size) < 50) {
- # faster than mvtnorm::dmvnorm for small kernels
- kernel = matrix(NA, ncol = size[2], nrow = size[1])
- for (i in seq_len(nrow(kernel))) {
- for (j in seq_len(ncol(kernel))) {
- kernel[i, j] = dnorm(x[i], mean = kernel_mean, sd = kernelSD) *
- dnorm(y[j], mean = kernel_mean, sd = kernelSD)
- }
- }
- } else {
- # this is faster for large kernels
- sigma = diag(2) * kernelSD
- kernel_long = expand.grid(x1 = x, x2 = y)
- kernel_long$dd = mvtnorm::dmvnorm(x = kernel_long,
- mean = c(kernel_mean, kernel_mean),
- sigma = sigma)
- kernel = matrix(kernel_long$dd, nrow = size[1])
- # kernel[1:5, 1:5]
- }
- if (checker) {
- fl_row = floor(size[1] / 2)
- fl_col = floor(size[2] / 2)
- cl_row = ceiling(size[1] / 2)
- cl_col = ceiling(size[2] / 2)
- # quadrant 0 to 3 o'clock
- kernel[seq_len(fl_row), (cl_col + 1):size[2]] = -kernel[seq_len(fl_row), (cl_col + 1):size[2]]
- # quadrant 6 to 9 o'clock
- kernel[(cl_row + 1):size[1], seq_len(cl_col)] = -kernel[(cl_row + 1):size[1], seq_len(cl_col)]
- }
- kernel = kernel / max(kernel)
- if (plot) {
- persp(
- kernel,
- theta = -20,
- phi = 25,
- # zlim = c(-1, 4),
- ticktype = 'detailed'
- )
- }
- kernel
- }
- #' SSM novelty
- #'
- #' Internal soundgen function.
- #'
- #' Calculates novelty in a self-similarity matrix. Called by \code{\link{ssm}}.
- #' @param ssm self-similarity matrix, as produced by \code{\link{selfsim}}
- #' @param kernelSize the size of gausisan kernel (points)
- #' @param kernelSD the SD of gaussian kernel
- #' @param normalize if TRUE, normalizes so that max = 1
- #' @return Returns a numeric vector of length \code{nrow(ssm)}
- #' @keywords internal
- getNovelty = function(ssm,
- kernelSize,
- kernelSD,
- padWith = 0,
- normalize = TRUE) {
- kernel = getCheckerboardKernel(size = kernelSize, kernelSD = kernelSD)
- ## pad matrix with size / 2 zeros, so that we can correlate it with the
- # kernel starting from the very edge
- ssm_padded = matrix(padWith,
- nrow = nrow(ssm) + kernelSize,
- ncol = nrow(ssm) + kernelSize)
- halfK = kernelSize / 2
- # indices in the padded matrix where we'll paste the original ssm
- idx = c(halfK + 1, nrow(ssm_padded) - halfK)
- # paste original. Now we have a padded ssm
- ssm_padded[idx[1]:idx[2], idx[1]:idx[2]] = ssm
- ## get novelty
- novelty = rep(0, nrow(ssm))
- # for each point on the main diagonal, novelty = correlation between the
- # checkerboard kernel and the ssm. See Badawy, "Audio novelty-based
- # segmentation of music concerts"
- for (i in idx[1]:idx[2]) {
- n = (i - halfK):(i + halfK - 1)
- # suppress warnings, b/c otherwise cor complains of sd = 0 for silent segments
- mat_i = ssm_padded[n, n]
- diag(mat_i) = NA
- novelty[i - halfK] = suppressWarnings(
- cor(as.vector(mat_i), as.vector(kernel), use = 'pairwise.complete.obs')
- )
- }
- novelty[is.na(novelty)] = 0
- novelty
- }
SSM.R, no license · at the source
Overview
Abstract
Sensory input that violates prior expectations attracts attention, making unpredictability an important perceptual property to measure. In the auditory modality, knowing what sounds will be perceived as surprising, and therefore salient, is relevant both for studying vocal communication and for applied purposes such as managing noise pollution. Focusing on sequences of animal vocalizations and environmental sounds as ecologically important acoustic stimuli, I describe and benchmark several algorithms for measuring their perceived unpredictability. Information-theoretical approaches include Shannon surprisal and Bayesian surprise, both implemented here to detect deviant stimuli based on distributional acoustic properties. The second group of algorithms is based on detecting spectro-temporal recurrence assessed with autocorrelation functions (ACF surprisal) and self-similarity matrices (SSM novelty). The third approach uses neural networks. Based on the ratings of the predictability of 300 synthetic acoustic sequences by 195 human listeners, Shannon surprisal and SSM novelty capture the perceived unpredictability that is due to spectral variability, whereas ACF surprisal taps into the perceptual impact of irregular rhythm. Most algorithms converge on the time scale of about 1 s as the most perceptually relevant for spectral variability, which is consistent with the hypothesis that the perception of unpredictability stems from a relatively limited amount of auditory input held in short-term memory. Together, the presented open-source algorithms offer powerful and flexible tools for measuring acoustic surprisal and studying auditory attention, while the corpus of predictability ratings offers a resource for future benchmarking. All code and data are freely available from the R package soundgen and supplementary materials at https://
Supplementary Information: The online version contains supplementary material available at 10.3758/
Reproduced under the paper's license (CC BY), from the paper cited above.
Repositories
Its files are read in the Code ↔ Paper reader above, with 2 matches between paragraphs and lines of code.
OSF bgzvc
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
- 27 September 2026: the link answers (HTTP 200)
16 files
- analysis/
SSM.R , R, 692 lines, 1 match - analysis/
ac_pred_ratings.Rmd , R, 332 lines - analysis/
acoustic_analysis.R , R, 96 lines - analysis/
acoustic_analysis_audioi , R, 28 linesc.R - analysis/
demogr.Rmd , R, 66 lines - analysis/
fig_S6_window-dependence , R, 66 lines.R - analysis/
fig_acf_ex.R , R, 80 lines - analysis/
fig_info_ex.R , R, 62 lines - analysis/
fig_novelty_ex.R , R, 39 lines - analysis/
fig_spectrograms.R , R, 20 lines - analysis/
optim_info.Rmd , R, 637 lines - analysis/
optim_novelty.Rmd , R, 575 lines - analysis/
optim_surprisal.Rmd , R, 765 lines - analysis/
rating_per_sound.Rmd , R, 197 lines - analysis/
surprisal.R , R, 994 lines, 1 match - analysis/
zz_prep.R , R, 105 lines
OSF kp9mg
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
- 27 September 2026: the link answers (HTTP 200)
16 files
- Exp2/
analysis/ , R, 103 linessurp2_acoustic_analysis. R - Exp2/
analysis/ , R, 83 linessurp2_demogr.Rmd - Exp2/
analysis/ , R, 429 linessurp2_effect_of_manip_on _ratings.Rmd - Exp2/
analysis/ , R, 50 linessurp2_names.R - Exp2/
analysis/ , R, 109 lineszz_surp2_prep.R - Exp2/
analysis/ , R, 105 lineszz_surp2_prep_annoy.R - Exp2/
analysis/ , R, 123 lineszz_surp2_prep_predict.R - Exp2/
surp2_synthesis.R , R, 555 lines - Exp3/
surp3_synthesis.R , R, 535 lines - Exp4/
analysis/ , R, 560 linessurp4_accuracy.Rmd - Exp4/
analysis/ , R, 515 linessurp4_accuracy_full.Rmd - Exp4/
analysis/ , R, 62 linessurp4_demogr.Rmd - Exp4/
analysis/ , R, 53 linessurp4_names.R - Exp4/
analysis/ , R, 106 lineszz_surp4_prep.R - SSM.R, R, 692 lines
- surprisal.R, R, 994 lines
Code availability
All data and materials are available at https://
Reproduced under the paper's license (CC BY), from the paper cited above.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 32 scripts, each with its path and the digest of its content;
- 2 matches between paragraphs of the paper and lines of the code (method lexical-v1);
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
No dataset and no data link were found in the paper.
Data Availability Statement
All data and materials are available at https://
All data and materials are available at https://
Reproduced under the paper's license (CC BY), from the paper cited above.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 2, 28 September 2026
- Publisher: n/a → Springer Science+Business Media
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 1 author, 5 keywords, 9 MeSH terms, 1 funder, 44 references.
Cite
This paper
Anikin, A. (2026). Measuring surprisal in sound sequences. Behavior research methods, 58(10), 278. https://
BibTeX
@article{anikin2026measu
author = {Anikin, Andrey},
title = {{Measuring surprisal in sound sequences}},
journal = {Behavior research methods},
year = {2026},
month = aug,
volume = {58},
number = {10},
pages = {278},
publisher = {Springer Science+Business Media},
issn = {1554-351X},
doi = {10.3758/
url = {https://
pmid = {42637973},
pmcid = {PMC13503466}
}
RIS
TY - JOUR
AU - Anikin, Andrey
TI - Measuring surprisal in sound sequences
T2 - Behavior research methods
J2 - Behav Res Methods
PY - 2026
DA - 2026/
VL - 58
IS - 10
SP - 278
SN - 1554-351X
PB - Springer Science+Business Media
DO - 10.3758/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.3758/
"type": "article-journal",
"title": "Measuring surprisal in sound sequences",
"container-title": "Behavior research methods",
"author": [
{
"family": "Anikin",
"given": "Andrey"
}
],
"container-title-short":
"volume": "58",
"issue": "10",
"page": "278",
"DOI": "10.3758/
"PMID": "42637973",
"PMCID": "PMC13503466",
"ISSN": "1554-351X",
"publisher": "Springer Science+Business Media",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
8,
24
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1038/s42003-026-10957-8 [code]
- Brain defence by the extracellular matrix protein Cochlin.Journal: Communications biologyIn common: randomForest, brms, reshape2, 3 other tools
- [2] doi:10.1093/bioinformatics/btag592 [code]
- Network-based stratification of allele-specific expression reveals patient subgroups in Huntington's disease.Journal: Bioinformatics (Oxford, England)In common: randomForest, reshape2, patchwork, 2 other tools
- [3] doi:10.3390/ijms27156925 [code]
- XGBoost-SHAP Interpretable Modeling Identifies and Validates an Eight-Gene Biomarker for Hepatic Encephalopathy Risk Prediction in Cirrhosis.Journal: International journal of molecular sciencesIn common: randomForest, reshape2, patchwork, 2 other tools
- [4] doi:10.1162/imag.a.1347 [code]
- Neural and behavioural correlates of theory of mind reasoning in five-year-old children born preterm.Journal: Imaging neuroscience (Cambridge, Mass.)In common: brms, reshape2, patchwork, 2 other tools
- [5] doi:10.1162/opmi.a.372 [code]
- Broadening the Agent Preference Hypothesis Through Experiencers: Eye-Tracking and EEG Evidence of Proto-Agents and Proto-Patients.Journal: Open mind : discoveries in cognitive scienceIn common: brms, reshape2, patchwork, 2 other tools
- [6] doi:10.1093/braincomms/fcag217 [code]
- Investigation of stress hormones across multiday seizure cycles.Journal: Brain communicationsIn common: brms, reshape2, patchwork, 2 other tools
- [7] doi:10.1038/s41593-026-02387-w [code]
- Developing mouse inhibitory neuron single-cell transcriptomes reveal distinct modes of cell-type diversification.Journal: Nature neuroscienceIn common: randomForest, reshape2, patchwork, 2 other tools
- [8] doi:10.1016/j.celrep.2026.117505 [code]
- Impaired spatial coding and neuronal hyperactivity in the medial entorhinal cortex of aged APP knock-in mice.Journal: Cell reportsIn common: brms, reshape2, patchwork, 2 other tools
- [9] doi:10.1162/imag.a.1258 [code]
- Non-specific increase in alpha power during a neurofeedback session targeting its downregulation.Journal: Imaging neuroscience (Cambridge, Mass.)In common: brms, reshape2, patchwork, 2 other tools
- [10] doi:10.1038/s44271-026-00431-w [code]
- Alpha power increases spontaneously during a neurofeedback session.Journal: Communications psychologyIn common: brms, reshape2, patchwork, 2 other tools
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 2 repositories of the authors' code, each at its verified commit and with its license, 32 scripts, and 2 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:8086f839b2d8bcd0…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[.
Discussion, reproductions, activity
Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.
Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
