Skip to content

Instantly share code, notes, and snippets.

@PeterNSteinmetz
Created August 17, 2023 18:18
Show Gist options
  • Save PeterNSteinmetz/509079de83b1847d54462e8b9bd4a767 to your computer and use it in GitHub Desktop.
Save PeterNSteinmetz/509079de83b1847d54462e8b9bd4a767 to your computer and use it in GitHub Desktop.
Simulation of background activity and noise in human intracranial microwire recordings.
import numpy as np
import scipy.signal as signal
from NoiseSim.StdNoiseFilter import StdNoiseFilter
class StdNoiseGen:
"""
Standard noise generator.
Encapsulates filter length and leading zeros.
"""
def __init__(self, sampRate = 25000, gainFactor = 1.0, rngSeed = 12345):
"""
Build filter and get length.
:param sampRate: sampling rate
:param gainFactor: std in passband (300-3000 Hz) of output noise in volts
:param rngSeed: seed for random number generation
"""
self.filt = StdNoiseFilter(sampRate, gainFactor)
self.filtLen = self.filt.filtLength()
self.rng = np.random.default_rng(rngSeed)
def genNoise(self, length):
"""
Generate a standard noise sequence of given time duration.
Provide leading noise for input to minimize effect of filter startup.
:param length: length in seconds
:return: numpy.array 1-d with filtered noise
"""
outSamps = round(length * self.filt._sr)
numSamps = round(outSamps + self.filtLen)
w = self.rng.normal(size=numSamps)
output = signal.sosfilt(self.filt.sos, w)
return output[(numSamps-outSamps):]
def genNoiseForMultIntervals(self, intervals, multipliers):
"""
Generate noise given intervals of time and different multipliers.
:param intervals: np.array 1-d of time intervals to generate noise for
:param multipliers: np.array 1-d of multipliers on the gain to be applied for each interval
:return: np.array 1-d with filtered noise
"""
outSamps = round(np.sum(intervals) * self.filt._sr)
numSamps = round(outSamps + self.filtLen)
# run in interval at first multiplier
w0 = self.rng.normal(size=self.filtLen) * multipliers[0]
wsegs = [w0]
# for each interval
for i in range(0,intervals.shape[0]):
sw = self.rng.normal(size=round(intervals[i] * self.filt._sr)) * multipliers[i]
wsegs.append(sw)
w = np.concatenate(wsegs)
output = signal.sosfilt(self.filt.sos, w)
return output[(numSamps-outSamps):]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment