m-thesis-introduction/simulations/lib/sampling/sampling.py

56 lines
1.3 KiB
Python
Raw Normal View History

2022-03-11 17:49:59 +01:00
"""
Sampling related stuff
Such as a Sampler and Digitizer
"""
import numpy as np
def quantise(signal, resolution, bias=0):
"""
Quantise the signal with resolution
Parameters
##########
signal - arraylike
The signal to be quantised
resolution - float
Resolution for quantising the signal
bias - optional,float
Optional bias applied before quantising
"""
return np.round(signal / resolution - bias) * resolution
2022-03-24 17:48:34 +01:00
def resample(signal, signal_fs, sample_frequency = 1):
2022-03-11 17:49:59 +01:00
"""
Resample signal (sampled at signal_fs) to sample_frequency
Parameters
##########
signal - arraylike
The signal to be resampled
signal_fs - float
Sampling frequency of signal
sample_frequency - float
Wanted sampling frequency for the resampled signal
"""
scale = sample_frequency / signal_fs
return _resample(signal, scale)
def _resample(signal, scale):
"""
Quick resampling algorithm
From: https://github.com/nwhitehead/swmixer/blob/master/swmixer.py
"""
n = round( len(signal) * scale )
return np.interp(
np.linspace(0, 1, n, endpoint=False), # where to interpret
np.linspace(0, 1, len(signal), endpoint=False), # known positions
signal, # known data points
)