add signal processing code and new GUI

Remove copyrighted docs and maciej program
parent e8a3e159
# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="Federico Asara"
__date__ ="$Jul 11, 2011 2:39:38 PM$"
__doc__= """This module offers the Signal class, which simple store the output
signal of an ADC with some other useful informations. """
from Utilities import *
from numpy import *
import Sinefit
class Signal(object):
"""A class that represent a time-domain sampled signal.
"""
def __init__(self, nbits = 0, rate = 1, data = []):
"""initialize a signal object
nbits: bit width of the sample values
rate: sampling rate of sample production
data: an array of samples (usually nbits-long words, stored in
a numpy array)
"""
self.nbits = nbits
self.rate = rate
self.fulldata = data = array(data, dtype=float)
self.fullnsamples = len(data)
self.data = self.fulldata
self.nsamples = len(data)
# remove DC component
if self.fullnsamples > 0:
self.fulldata -= (max(self.fulldata) +min(self.fulldata))/2.
self.fulldft = abs(fft.fft(self.fulldata))
# useful names
N = len(data)
fdft = self.fulldft
first = 1. + argmax(fdft[1:N/2])
second = first + (argmax(fdft[first-1:first+2:2])*2) -1
ratio = (fdft[second] / fdft[first])
self.first = first
self.beta = N/pi * arctan(sin(pi/N)/(cos(pi/N)+1./ratio))
self.w0index = first+ self.beta
freqSample = 2 * pi * self.rate
w0 = freqSample * float(self.w0index)/self.nsamples
print "Frequency initial guess ->", w0
self.w0, self.A, self.B, self.C = Sinefit.sinefit4(data, 1.0/rate, w0, 1e-7)
print "Frequency fit ->", self.w0
# limit data
self.w0index = self.w0 /freqSample * self.nsamples
self.limit = floor(0.5 + N*int(self.w0index)/self.w0index)
self.data = data[:self.limit]
self.nsamples = len(self.data)
print "limit is:", self.limit
self.precalculateAll()
def items(self):
"""Create a list of tuples that describes the signal.
The structure of a tuple is"""
output = []
output.append(('Number of bits', '%d b', self.nbits))
output.append(('Sampling rate', '%.2f Hz', self.rate))
output.append(('Number of samples', "%d samples", self.nsamples))
output.append(('Peak at', "%f", self.w0index))
output.append(('Input frequency', "%.6f Hz", self.w0/2/pi))
output.append(('Beta', "%f", self.beta))
return output
def precalculateAll(self):
return
......@@ -31,16 +31,47 @@ def sinefit3(samples, sample_t, w0):
D0 = D0T.T
x0 = (D0T * D0).I * D0T * matrix(samples).T
return array(x0).reshape((3,))
def sinefit4matrix(samples, sample_t, w0, tol=1e-7):
"""fit a sampled wave to a sine of unknown frequency
def sinefit4(data, Ts, w0):
This routine implements the algorithm of IEEE 1241, sect. 4.1.4.3.,
fitting a sine wave the the samples given, which are assumed equally
spaced in time by a sample period sample_t.
a0 cos(w0 t + theta) + b0 sin(w0 t + theta) + c0
An initial frequency estimate w0 is required to start, and an
optional relative error in frequency is admitted (1e-4 by default)
The return value is the quadruple (w0, a0, b0, c0)
"""
a0, b0, c0 = sinefit3(samples, sample_t, w0)
deltaw0 = 0
while True:
w0 += deltaw0
n = samples.size
t = arange(n) * sample_t
w0t = w0 * t
D0T = matrix(vstack([cos(w0t), sin(w0t), ones(n),
-a0*t*sin(w0t) + b0*t*cos(w0t)]))
D0 = D0T.T
x0 = (D0T * D0).I * D0T * matrix(samples).T
x0 = array(x0).reshape((4,))
a0, b0, c0, deltaw0 = x0
if abs(deltaw0/w0) < tol:
return (w0+deltaw0, a0, b0, c0)
def sinefit4scipy(data, Ts, w0, *args, **kwargs):
# Target function
# fitfunc = lambda p, x: p[0]*cos(p[3]*x) +p[1]*sin(p[3]*x) +p[2]
# Distance to the target function
errfunc = lambda p, x, y: p[0]*cos(p[3]*x) +p[1]*sin(p[3]*x) +p[2] - y
errfunc = lambda p, x, y: y - (p[0]*cos(p[3]*x) +p[1]*sin(p[3]*x) +p[2])
# Initial guess for the parameters
A, B, C = sinefit3(data, Ts, w0)
A, B, C = sinefit3(data, Ts, w0)
p0 = [A, B, C, w0];
# Time serie
......@@ -49,7 +80,7 @@ def sinefit4(data, Ts, w0):
p1, success = optimize.leastsq(errfunc, p0[:], args=(Tx, data))
return p1
return p1[:4]
def makesine(samples, periods, bits, amplitude=1, noise=0):
t = arange(samples)/float(samples)
......@@ -60,6 +91,8 @@ def makesine(samples, periods, bits, amplitude=1, noise=0):
place(sine, sine <= -2**bits, -2**bits)
return sine
sinefit4 = sinefit4matrix
if __name__ == "__main__":
sine = makesine(20000, 20, 12, 443, 10)
print sine
......
from Signal import *
class TwoToneSignal(Signal):
"""A class that represent a time-domain sampled signal with two sinusoids
with similiar frequenciess.
"""
def __init__(self, nbits = 0, rate = 1, data = []):
"""initialize a signal object
nbits: bit width of the sample values
rate: sampling rate of sample production
data: an array of samples (usually nbits-long words, stored in
a numpy array)
"""
super(TwoToneSignal, self).__init__(nbits, rate, data)
def items(self):
output = super(TwoToneSignal, self).items()
output.append(('The cake is a lie', "%s ", True))
return output
def precalculateAll(self):
"""Evaluates all the parameters of the signal, and also call the
precalculate method for each window function we know."""
return
from ConfigParser import RawConfigParser
from numpy import max, abs, sum, sqrt, log10
from time import time
# timeit decoratr
def timeit(method):
def timed(*args, **kw):
ts = time()
result = method(*args, **kw)
te = time()
print '%r (%r, %r) %2.3f sec' % (method.__name__, args, kw, te-ts)
return result
return timed
# db converter
def dB(x): return 20*log10(x)
def norm(v):
m = max(abs(v))
w = v/m
return m * sqrt(sum(w*w))
# empty generator
def fake(x, y):
return (i for i in [])
@timeit
def readFile(path):
config = RawConfigParser()
config.read(path)
nbits = config.getint('SIGNAL', 'nbits')
rate = config.getint('SIGNAL', 'rate')
dataString = config.get('SIGNAL', 'data').split('\n')
data = map(int, dataString)
return nbits, rate, data
......@@ -50,4 +50,4 @@ windows = {
if __name__ == "__main__":
for name in windows:
print "Using window", name
print windows[name][15]
\ No newline at end of file
print windows[name][15]
from numpy import *
class WindowedSignal:
data = array([])
th = array([])
nsamples = 0
dft = array([])
udft = array([])
ldft = array([])
ludft = array([])
ratio = 0
maxPeak = 0
w0 = 0
w0index = 0
rate = 0
def adjust(self, data, fs):
while data >= fs:
data -= fs
if data >= fs/2.:
data = fs -data;
return data
def harmonicPeaksGenerator(self, start, end):
indexes = (self.adjust(x * self.w0index, self.nsamples -1) for x in xrange(start , end))
return ((i, self.ratio*i, self.dft[i]) for i in indexes)
def logHarmonicPeaksGenerator(self, start, end):
indexes = (self.adjust(x * self.w0index, self.nsamples -1) for x in xrange(start , end))
return ((i, self.ratio*i, self.ldft[i]) for i in indexes)
THD = 0
noiseFloor = 0
signalPower = 0
noisePower = 0
SNR = 0
SINAD = 0
ENOB = 0
maxPeak = 0
secondPeak = 0
SFDR = 0
def items(self):
output = []
output.append(('Input frequency', '%.5f Hz', self.w0/(2*pi)))
output.append(('Peak', '%d', self.w0index))
output.append(('THD', '%.2f dB', self.THD))
output.append(('Noise floor', "%g dB", self.noiseFloor))
output.append(('Signal power', "%.f ", self.signalPower))
output.append(('Noise power', "%.f ", self.noisePower))
output.append(('SNR', "%.2f dB", self.SNR))
output.append(('SINAD', "%.2f dB", self.SINAD))
output.append(('ENOB', "%.2f b", self.ENOB))
output.append(('SFDR', "%.2f dBc", self.SFDR))
return output
def report(self):
for i in self.items():
print "%s: %s" % (i[0], i[1] % i[2])
__author__="federico"
__date__ ="$Jul 11, 2011 2:39:08 PM$"
import matplotlib
matplotlib.use('Qt4Agg')
# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="Federico Asara"
__date__ ="$Jul 11, 2011 2:39:38 PM$"
__doc__= """This module offers the Signal class, which calculate a variety of
parameters of an ADC output signal. """
# We use its array for data representation, also we use its FFT implementation
from numpy import *
# For frequency detection and unit-testin
import Sinefit
# We need all the window functions
import WindowFunction
def dB(x): return 20*log10(x)
class WindowedSignal:
"""Container object that will hold information about a DFT of a signal
multiplied by some window function"""
pass
class Signal(object):
"""A class that represent a time-domain sampled signal, and also holds many
WindowedSignal that represent the signal in frequency domain.
"""
# maximum tolerable resolution for a histogram
MAXRES = 512
# indicates the selected window
selectedWindow = "No window"
def __getitem__(self, what):
"""Get a windowed signal item for a particular window function"""
if what is None:
what = self.selectedWindow
# just to be sure
if what not in WindowFunction.windows.keys():
what = self.WindowFunction.windows.keys()[0]
return self.windowed[what]
def __init__(self, nbits, rate, data):
"""initialize a signal object
nbits: bit width of the sample values
rate: sampling rate of sample production
data: an array of samples (usually nbits-long words, stored in
a numpy array)
"""
self.nbits = nbits
self.rate = rate
self.data = array(data) # just to be sure
self.nsamples = len(data)
self.precalculateAll()
def precalculateAll(self):
"""Evaluates all the parameters of the signal, and also call the
precalculate method for each window function we know."""
# First of all evaluate the histograms
self.idealHistogram = self._ideal_histogram()
self.realHistogram = self._histogram()
# Then evaluate DNL and INL
self.DNL, self.maxDNL = self._DNL()
self.INL, self.maxINL = self._INL()
# ..theoretical SNR and process gain
self.thSNR = 6.02 * self.nbits + 1.76
self.processGain = 10.0 * log10(self.nbits / 2.0)
# This dictionary will hold all the WindowedSignal objects
self.windowed = {}
for i in WindowFunction.windows.keys():
print
print "Precalculating fft data for", i
print
self.windowed[i] = self.precalculate(i)
def precalculate(self, windowName):
"""Evaluates all the parameters for a particular window function.
windowName: a string containing the name of the window function
Returns a WindowFunction object, or None if windowName is not valid."""
# windows are ok right now
# wrong values: THD
# wrong formatting output: THD
if windowName not in WindowFunction.windows.keys():
return None # and maybe launch an exception
output = WindowedSignal()
window = WindowFunction.windows[windowName]
output.data = self.data * window[self.nsamples]
output.dft = abs(fft.rfft(output.data))
output.ldft = 10*log10(output.dft)
# sinusoid frequency detection
w0, w0index = Sinefit.sineguess(output.ldft, self.rate, self.nsamples)
freqSample = 2*pi*self.rate
ratio = w0 / w0index
output.w0 = Sinefit.sinefit4(self.data, freqSample, w0)
# let's go through harmonic peaks. we will produce a generator
# this way
def adjust(data, fs):
while data >= fs:
data -= fs
if data >= fs/2.:
data = fs -data;
return data
def getGenerator(start, end):
indexes = (adjust(x * w0index, self.nsamples -1) for x in xrange(start , end))
return ((i, ratio*i, output.dft[i]) for i in indexes)
def getLogGenerator(start, end):
indexes = (adjust(x * w0index, self.nsamples -1) for x in xrange(start , end))
return ((i, ratio*i, 10*log10(output.dft[i])) for i in indexes)
output.harmonicPeaksGenerator = getGenerator
output.logHarmonicPeaksGenerator = getLogGenerator
# THD seems easy..
tenHarmonics = list(getGenerator(2, 10))
thindex = vstack(map(lambda x: x[0], tenHarmonics))
thvalues = vstack(map(lambda x: x[2], tenHarmonics))
tenHarmonicsValues = array(map(lambda x: x[2], tenHarmonics))
rssHarmonics = sqrt(sum(tenHarmonicsValues**2))
output.THD = dB(output.dft[w0index]/rssHarmonics)
# we need the avg of HDs
avgHarmonics = mean(tenHarmonicsValues)
# we also need the noise floor: the average of all components below
# avgHarmonics
filteredNoise = where(output.dft < avgHarmonics, output.dft, 0)
output.noiseFloor = dB(mean(filteredNoise))
output.signalPower = sum(abs(output.dft)**2)/self.nsamples
#sum(where(output.dft < output.noiseFloor, output.dft, 0)**2)/(self.nsamples**2 )
avg = mean(self.data)
maxval = max(self.data)
minval = min(self.data)
amplitude = 1
periods = w0index
thSin = avg + Sinefit.makesine(self.nsamples, periods, self.nbits, amplitude)
noise = self.data - thSin
output.noisePower = sum(abs(fft.rfft(noise))**2)/self.nsamples
# now we can evaluate SNR = max component - noise floor - process gain
# output.SNR = output.dft[w0index] -output.noiseFloor -self.processGain
output.SNR = dB(output.signalPower/output.noisePower)
# now it's time for SINAD
clean = array(output.dft)
clean[0] = 0
clean[w0index] = 0
output.SINAD = dB(output.dft[w0index]/sqrt(sum(clean**2)))
# ENOB
fsr = 2**(self.nbits -1)
ra = (max(output.data) - min(output.data))/2.0
factor = dB(fsr/ra)
output.ENOB = (output.SINAD - 1.76 + factor) / 6.02
# SFDR - should I use dB(x) instead of 10log10 ?
output.maxPeak = 10*log10(output.dft[w0index])
secondPeak = max(thvalues)
output.secondPeak = 10*log10(secondPeak)
output.SFDR = 10*log10(output.dft[w0index] - secondPeak) #10*log10
print "Sampling frequency = %.6f rad/s" % freqSample
print "Input frequency detected = %.6f rad/s" % output.w0
print "THD = %g dB" % output.THD
print "Noise floor = %.6f dB" % output.noiseFloor
print "Signal power = %.f W" % output.signalPower
print "Noise power = %.f W" % output.noisePower
print "SNR = %.6f dB" % output.SNR
print "SINAD = %.6f dB" % output.SINAD
print "ENOB = %.f b" % output.ENOB
print "SFDR = %.6f dBc" % output.SFDR
return output
def histogram_resolution(self):
bins = 2**self.nbits
return 512 if bins > self.MAXRES else bins
def _histogram(self):
"""Compute histogram of a sampled signal
The number of bins in the histogram is implicitly given by the number
of bits of the samples: 2**signal.nbits bins.
returns: an array of 2**signal.nbits numbers (frequencies)
"""
bins = 2**self.nbits
hist, discard = histogram(self.data, bins)
return hist[1:-1]
def _ideal_histogram(self):
"""Produce an ideal vector of frequencies (histogram) for the
nsamples samples of a perfect nbits ADC. Mostly for auxiliary and
display purposes
returns: an array of 2**signal.nbits numbers (frequencies)
"""
Mt = self.nsamples
A = sin(pi/2 * Mt / (Mt + self.data[0] + self.data[-1]))
range = 2**self.nbits
midrange = range/2
n = arange(1, range-1)
p = arcsin(A/midrange * (n - midrange))
q = arcsin(A/midrange * (n - 1 - midrange))
p = (p - q) / pi
return Mt * p
def _DNL(self):
dnl = (self.realHistogram/self.idealHistogram) -1
return dnl, max(abs(dnl))
def _INL(self):
inl = cumsum(self.DNL)
return inl, max(abs(inl))
# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="federico"
__date__ ="$Jul 11, 2011 2:40:18 PM$"
from numpy import *
from scipy import optimize
def sineguess(dft, rate, nsamples):
w0index = argmax(dft)
w0 = w0index * (2 * pi * rate) / nsamples
return w0, w0index
def sinefit3(samples, sample_t, w0):
"""fit a sampled wave to a sine of kwnown frequency
This routine implements the algoritm of IEEE 1241, sect. 4.1.4.1.,
fitting a sine of given frequency w0 to the samples given, which are
assumed equally spaced by a sample period of sample_t
a0 cos(w0 t + theta) + b0 sin(w0 t + theta) + c0
The return value is the triple (a0, b0, c0)
"""
n = samples.size
t = w0 * arange(n) * sample_t
D0T = matrix(vstack([cos(t), sin(t), ones(n)]))
D0 = D0T.T
x0 = (D0T * D0).I * D0T * matrix(samples).T
return array(x0).reshape((3,))
def sinefit4(data, Ts, w0):
# Target function
fitfunc = lambda p, x: p[0]*cos(p[3]*x) +p[1]*sin(p[3]*x) +p[2]
# Distance to the target function
errfunc = lambda p, x, y: fitfunc(p, x) - y
# Initial guess for the parameters
A, B, C = sinefit3(data, Ts, w0)
p0 = [A, B, C, w0];
# Time serie
n = data.size
Tx = arange(n) * Ts
p1, success = optimize.leastsq(errfunc, p0[:], args=(Tx, data))
return p1[3]
def makesine(samples, periods, bits, amplitude=1, noise=0):
t = arange(samples)/float(samples)
sine = amplitude * sin(2*pi*periods*t)
sine += noise * ((t % 0.02) / 0.02 - 0.01)
sine = (sine * 2**bits + 0.5).astype(int)
place(sine, sine >= 2**bits, 2**bits)
place(sine, sine <= -2**bits, -2**bits)
return sine
if __name__ == "__main__":
sine = makesine(20000, 20, 12, 443, 10)
print sine
dft = 10*log10(abs(fft.rfft(sine)))
w0, w0index = sineguess(dft, 133, 20000)
out = sinefit4(sine, 2*pi*(133**-1), w0)
print w0, w0index, out
__author__="federico"
__date__ ="$Jul 11, 2011 2:39:08 PM$"
\ No newline at end of file
from numpy import*
from math import sin, pi, atan
import matplotlib.pyplot as p
def sine_samples(n):
"""Produce a vector of samples of sine in [0..2 pi]"""
samples = []
for i in range(n):
samples.append(sin(2*pi*i/n))
return samples
x=input("give number of samples :")
vec=sine_samples(x)
for element in vec:
print element
b=fft.fft(vec)
print("now i'll show you the FFT of it")
print(b)
c=atan(b[0].imag/b[0].real)
d=atan(b[x-1].imag/b[x-1].real)
print("modulus of the first harmonic:")
print(abs(b[0]))
print("argument of the first harmonic:")
print(c)
print("modulus of the last harmonic:")
print(abs(b[x-1]))
print("argument of the last harmonic:")
print(d)
#if you put x=9 it gives you d=1.57079632679 but my calculator gives d=1.431169...so,where is the mistake?
a=[]
print "give a number"
x=input("x: ")
while x>=0:
a.append(x)
print "give a number"
x=input("x: ")
print a[:]
#f_name=input()
#print(f_name)
question = "What is the name of the file?"
print (question)
answer = raw_input()
print ("ok,so the name of the file is " + answer + "let me show it")
f=open(answer)
for line in f:
print line
import math
for i in range (101):
x = 2 * math.pi * i / 100
print math.sin(x)
import math
samples = input('Number of divisions: ')
i = 0
while i <= samples:
# do sample i
x = 2 * math.pi * i / samples
print math.sin(x)
i = i + 1
from math import sin, pi
from sys import argv
def sine_samples(n):
"""Produce a vector of samples of sine in [0..2 pi]"""
samples = []
for i in range(n+1):
samples.append(sin(2*pi*i/n))
return samples
def print_vector(v):
for element in v:
print element
if __name__ == '__main__': # the usual idiom for a main program
# samples = input("give a number: ")
# samples = int(argv[1])
if len(argv)==1:
samples = input("give a number: ")
else:
samples = int(argv[1])
vec = sine_samples(samples)
print_vector(vec)
from numpy import*
from math import sin, pi
import matplotlib.pyplot as p
def sine_samples(n):
"""Produce a vector of samples of sine in [0..2 pi]"""
samples = []
for i in range(n):
samples.append(sin(2*pi*i/n))
return samples
x=input("give number of samples :")
vec=sine_samples(x)
for element in vec:
print element
print("and now the FFT of it:")
print fft.fft(vec)
a = range(x)
b=fft.fft(vec)
p.plot(a, vec, a, abs(b))
p.show()
a=input(
from numpy import*
from math import sin, pi
import matplotlib.pyplot as p
def sine_samples(n):
"""Produce a vector of samples of sine in [0..2 pi]"""
samples = []
for i in range(n):
samples.append(sin(2*pi*i/n))
return samples
x=input("give number of samples :")
vec=sine_samples(x)
for element in vec:
print element
print("and now the FFT of it:")
print fft.fft(vec)
from numpy import*
from math import sin, pi
def argument(n,sampl_rate,fr,ph):
#produce a vector of the arguments of the sinewave#
arg=[]
for i in range(n):
arg.append(2*pi*fr*i/sampl_rate+ph*2*pi)
return arg
def make_sinewave (n,v,amp):
#produces the values if the sinewave#
b=[]
for i in range (n):
b.append(amp*sin(v[i]))
return b
a=input("please give amplitude:")
f=input("please give the sinewave's frequency:")
p=input("please give phase(rad):")
sr=input("please give sampling rate:")
s=input("please give number of samples:")
vector=argument(s,sr,f,p)
print("these are the arguments of the sinewave")
print vector[:]
print ("these are the values of the sinewave")
sine=make_sinewave(s,vector,a)
print sine[:]
from numpy import*
from math import *
import matplotlib.pyplot as pl
def adc_transfer(fsr, bits,inl):
#MAKING THE TRANSFER FUNCTION
a=float(math.pow(2,bits))
lsb=float(fsr/a)
print("the LSB is"),lsb
digital=[]
analog=[]
plot_analog=[]
plot_digital=[]
straight_line=[]
for i in range (a):
b=lsb*i
analog.append(b)
#THE INL ERROR HAS AN INFLUANCE ON THE Y-AXES(thus,on "digital"and "plot_digital")
digital.append(i+inl)
dnl=input ("WHAT IS THE DNL ERROR AT THIS STEP? : ")
d=(dnl*lsb)
for w in range(a):
#THE DNL ERROR HAS AN INFLUANCE ON THE Y-AXES(thus,on "analog" and "plot_analog")
plot_analog.append((w/a+i)*lsb+d)
plot_digital.append(digital[w])
if (w==a/2):
straight_line.append((w/a+i)*lsb)
print ("THE ANALOG VALUES ARE: "),analog [:]
print ("THE DIGITAL VALUES ARE: "),digital[:]
print ("plot_analog: "),plot_analog[:]
print ("plot_digital: "),plot_digital[:]
print ("THE STRAIGHT LINE VECTOR IS: "),straight_line[:]
#PLOTTING THE TRANSFER FUNCTION
# pl.plot(plot_analog, plot_digital)
# pl.show()
#PLOTTING THE STRAIGHT LINE OF THE TRANSFER FUNCTION
# pl.plot(straight_line,digital)
# pl.show()
pl.plot(plot_analog,plot_digital)
pl.show()
return analog,digital
full_scale_range=input("GIVE ME THE FULL SCALE RANGE: ")
num_of_bits=input("GIVE ME THE NUMBER OF BITS: ")
inl_error=float(input("PLEASE GIVE ME THE INL ERROR: "))
adc_transfer(full_scale_range,num_of_bits,inl_error)
from numpy import*
x=input("give number of samples: ")
b=array(random.random(x)*)
print b[:]
from numpy import*
from math import sin, pi
import matplotlib.pyplot as pl
def argument(n,sampl_rate,fr,ph):
#produce a vector of the arguments of the sinewave#
arg=[]
for i in range(n):
arg.append(2*pi*fr*i/sampl_rate+ph*2*pi)
return arg
def make_sinewave (n,v,amp):
#produces the values if the sinewave#
b=[]
for i in range (n):
b.append(amp*sin(v[i]))
return b
a=input("please give amplitude:")
f=input("please give the sinewave's frequency:")
p=input("please give phase(rad):")
sr=input("please give sampling rate:")
s=input("please give number of samples:")
vector=argument(s,sr,f,p)
print("these are the arguments of the sinewave")
print vector[:]
print ("these are the values of the sinewave")
sine=make_sinewave(s,vector,a)
sine=array(sine)
print sine[:]
b=array(random.random(s)-1)
print ("this is the noise")
print b[:]
c=array(b+sine)
print("the sum of the sinewave and the noise is:")
print c[:]
#SNR calculation#
sine_rss=0
noise_rss=0
for i in range (s):
sine_rss=sine_rss+sine[i]*sine[i]
noise_rss=noise_rss+b[i]*b[i]
SNR=sine_rss/noise_rss
print ("the SNR is" ) ,10*log10(SNR)
#creation of the plot#
g=range(s)
pl.plot(g, c)
pl.show()
import matplotlib.pyplot as pl
def plot_routine(arr,n):
#plots the contents of arr#
#creation of the plot#
g=range(n)
pl.plot(g, arr)
pl.show()
a=[]
s=input("give me the size of the array: ")
answer="y"
i=0
while (answer=="y") and (i in range (s)):
b=input("give me element: ")
a.append(b)
print("would you like to continue?")
answer=raw_input()
i=i+1
plot_routine(a,s)
from numpy import*
from math import *
import matplotlib.pyplot as pl
#def Denary2Binary(n):
# #convert denary integer n to binary string bStr
# bStr = ''
# if n < 0: raise ValueError, "must be a positive integer"
# if n == 0: return '0'
# while n > 0:
# bStr = str(n % 2) + bStr
# n = n >> 1
# return bStr
def adc_transfer(v, fsr, bits):
#MAKING THE TRANSFER FUNCTION
a=2.0**bits
lsb=float(fsr/a)
print("the LSB is"),lsb
digital=[]
analog=[]
for i in range (a):
b=lsb*i
analog.append(b)
digital.append(i)
print ("THE ANALOG VALUES ARE: "),analog [:]
print ("THE DIGITAL VALUES ARE: "),digital[:]
#PLOTTING THE TRANSFER FUNCTION
#pl.plot(analog, digital)
#pl.show()
#AND NOW THE CORRESPONDANCE!!!
i=0
if (v>=analog[0]) and (v<=analog[int(math.pow(2,bits)-1)]):
while i<=a:
if (v>=analog[i]) and (v<analog[i+1]):
return digital[i]
i=i+1
elif (v>analog[int(math.pow(2,bits)-1)]) :
return digital[int(math.pow(2,bits)-1)]
else:
return digital[0]
voltage_value=float(input("GIVE ME THE VOLTAGE VALUE: "))
full_scale_range=input("GIVE ME THE FULL SCALE RANGE: ")
num_of_bits=input("GIVE ME THE NUMBER OF BITS: ")
digital_value=adc_transfer(voltage_value,full_scale_range,num_of_bits)
print ("THE DIGITAL VALUE CORRESPONDING TO THE ANALOG IS :"),digital_value
from numpy import*
from math import *
import matplotlib.pyplot as pl
def adc_transfer(fsr, bits):
#MAKING THE TRANSFER FUNCTION
a=float(math.pow(2,bits))
lsb=float(fsr/a)
print("the LSB is"),lsb
digital=[]
analog=[]
plot_analog=[]
plot_digital=[]
for i in range (a):
b=lsb*i
analog.append(b)
digital.append(i)
for j in range(a):
plot_digital.append(digital[i])
for w in range(a):
plot_analog.append((w/a+i)*lsb)
print ("THE ANALOG VALUES ARE: "),analog [:]
print ("THE DIGITAL VALUES ARE: "),digital[:]
print ("plot_analog: "),plot_analog[:]
print ("plot_digital: "),plot_digital[:]
#PLOTTING THE TRANSFER FUNCTION
pl.plot(plot_analog, plot_digital)
pl.show()
return analog,digital
full_scale_range=input("GIVE ME THE FULL SCALE RANGE: ")
num_of_bits=input("GIVE ME THE NUMBER OF BITS: ")
adc_transfer(full_scale_range,num_of_bits)
from numpy import*
from math import *
import matplotlib.pyplot as pl
def adc_transfer(fsr, bits,inl):
#MAKING THE TRANSFER FUNCTION
a=float(math.pow(2,bits))
lsb=float(fsr/a)
print("the LSB is"),lsb
digital=[]
analog=[]
plot_analog=[]
plot_digital=[]
straight_line=[]
for i in range (a):
b=lsb*i
analog.append(b)
#THE INL ERROR HAS AN INFLUANCE ON THE Y-AXES(thus,on "digital"and "plot_digital")
digital.append(i+inl)
dnl=input ("WHAT IS THE DNL ERROR AT THIS STEP? : ")
d=(dnl*lsb)
for w in range(a):
#THE DNL ERROR HAS AN INFLUANCE ON THE Y-AXES(thus,on "analog" and "plot_analog")
plot_analog.append((w/a+i)*lsb+d)
plot_digital.append(digital[i])
if (w==a/2):
straight_line.append((w/a+i)*lsb)
print ("THE ANALOG VALUES ARE: "),analog [:]
print ("THE DIGITAL VALUES ARE: "),digital[:]
print ("plot_analog: "),plot_analog[:]
print ("plot_digital: "),plot_digital[:]
print ("THE STRAIGHT LINE VECTOR IS: "),straight_line[:]
#PLOTTING THE TRANSFER FUNCTION
# pl.plot(plot_analog, plot_digital)
# pl.show()
#PLOTTING THE STRAIGHT LINE OF THE TRANSFER FUNCTION
# pl.plot(straight_line,digital)
# pl.show()
pl.plot(plot_analog,plot_digital)
pl.show()
return analog,digital
full_scale_range=input("GIVE ME THE FULL SCALE RANGE: ")
num_of_bits=input("GIVE ME THE NUMBER OF BITS: ")
inl_error=float(input("PLEASE GIVE ME THE INL ERROR: "))
adc_transfer(full_scale_range,num_of_bits,inl_error)
from numpy import*
from numpy import bartlett
import matplotlib.pyplot as plt
n=input("the number of samples is :")
d=bartlett(n)
print d[:]
#plt.plot(d)
#plt.show()
e=abs(fft.fft(d))
e=array(e)
maximum=max(e)
f=e/maximum
g=log10(f)
h=20*g
i=fft.fftshift(h)
plt.plot(i)
plt.show()
from math import *
from numpy import *
from matplotlib import pyplot as plt
name=raw_input("give me the name of the file :")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
b=fft.fft(a)
c=abs(b)
#n=b.size
#c=abs(b)
#h=[]
#i=[]
#h,i=histogram(c,n)
#plt.hist(c,n)
#plt.show()
from numpy import*
from numpy import bartlett
import matplotlib.pyplot as plt
n=input("the number of samples is :")
d=bartlett(n)
print d[:]
plt.plot(d)
plt.show()
e=fft.fft(d)
f=abs(e)
n=f.size
print n
from math import *
from numpy import *
from matplotlib import pyplot as plt
##################### OPEN THE FILE ###################################
name=raw_input("GIVE ME THE NAME OF THE FILE:")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
#################### MAKING THE FFT ###################################
a=a-mean(a)
a=array(a)
asize=a.size
x=log2(asize)
print ("SIZE OF a IS: "),asize
print ("THE SIZE OF a EQUALS TO: 2 TO THE "),x
b=abs(fft.fft(a))
maxb=max(b)
d=b/maxb
e=log10(d)
f=20*e
h=fft.fftshift(f)
m=h.size
################ I 'LL MAKE A COUPLE:VECTOR h AND VECTOR freq #################################
freq=[]
for i in range (m):
freq.append(-50000000+i*100000000/m)
######## I'LL MAKE ANOTHER COUPLE:Vector hhalfh AND VECTOR freq_shift ##########################
hhalf=[]
freq_shift=[]
for i in range(m/2,m):
freq_shift.append(freq[i])
hhalf.append(h[i])
hhalf=array(hhalf)
freq_shift=array(freq_shift)
ser=hhalf.size
sep=freq_shift.size
print ("SIZE OF hhalf IS:"),ser
########## FINDING THE POSITION OF THE MAXMUM OF hhalf=>EXPECTING THE INPUT FREQUENCY #########
for i in range (ser):
maximum=hhalf[i]
for j in range (ser):
if hhalf[j]>maximum:
maximum=hhalf[j]
sinefreq=freq_shift[j]
print("the frequency of the sinewave is "),sinefreq
print("maximum of hhalf is "),maximum
#************************************* HARMONICS *********************************************#
# 2 important vectors: 1) position :has the position of the harmonics , 2) distortion :has the values of hhalf at the position of the harmonics (those two have the same size)
position=[]
distortion=[]
if x%2==0 :
################## 64 ##########################(x=12)
for i in range(int(2**(x/2))):
vector=[]
######################### 32 ###################
for j in range(int(2**((x/2)-1))):
vector.append(hhalf[j+i*(2**((x/2)-1))])
vector=array(vector)
maxh=max(vector)
for j in range(int(2**((x/2)-1))):
if vector[j]>=maxh:
maxh=vector[j]
position.append(freq_shift[j+i*(2**((x/2)-1))])
distortion.append(vector[j])
else :
########################## 128 #################(x=13)
for i in range(int((2**((x+1)/2)))):
vector=[]
############################ 32 ################
for j in range(int(2**(((x-1)/2)-1))):
vector.append(hhalf[j+i*(2**(((x-1)/2)-1))])
vector=array(vector)
maxh=max(vector)
for j in range(int(2**(((x-1)/2)-1))):
if vector[j]>=maxh:
maxh=vector[j]
position.append(freq_shift[j+i*(2**(((x-1)/2)-1))])
distortion.append(vector[j])
###### i will calculate the mean value of distortion and save the values in a vector called: realdistortion and the position of them(frequencies) in a vector called: realposition
distortion=array(distortion)
position=array(position)
mean=mean(distortion)
realdistortion=[]
realposition=[]
if x%2==0 :
for i in range(int(2**(x/2))):
if distortion[i]>=mean:
realdistortion.append(distortion[i])
realposition.append(position[i])
else:
for i in range(int((2**((x+1)/2)))):
if distortion[i]>=mean:
realdistortion.append(distortion[i])
realposition.append(position[i])
print("THE DISTORTION VECTOR :"),realdistortion[:]
print("THE POSITION OF THE HARMONICS :"),realposition[:]
plt.plot(freq_shift,hhalf)
plt.title("The FFT of the signal")
plt.xlabel("frequency")
plt.ylabel("dB")
plt.show()
from math import *
from numpy import *
from matplotlib import pyplot as plt
##################### OPEN THE FILE ###################################
name=raw_input("GIVE ME THE NAME OF THE FILE:")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
#################### MAKING THE FFT ###################################
a=a-mean(a)
a=array(a)
asize=a.size
x=log2(asize)
print ("SIZE OF a IS: "),asize
print ("THE SIZE OF a EQUALS TO: 2 TO THE "),x
b=abs(fft.fft(a))
maxb=max(b)
d=b/maxb
e=log10(d)
f=20*e
h=fft.fftshift(f)
m=h.size
################ I 'LL MAKE A COUPLE:VECTOR h AND VECTOR freq #################################
freq=[]
for i in range (m):
freq.append(-50000000+i*100000000/m)
######## I'LL MAKE ANOTHER COUPLE:Vector hhalfh AND VECTOR freq_shift ##########################
hhalf=[]
freq_shift=[]
for i in range(m/2,m):
freq_shift.append(freq[i])
hhalf.append(h[i])
hhalf=array(hhalf)
freq_shift=array(freq_shift)
ser=hhalf.size
print ("SIZE OF hhalf IS:"),ser
########## FINDING THE POSITION OF THE MAXMUM OF hhalf=>EXPECTING THE INPUT FREQUENCY #########
for i in range (ser):
maximum=hhalf[i]
for j in range (ser):
if hhalf[j]>maximum:
maximum=hhalf[j]
sinefreq=freq_shift[j]
print("the frequency of the sinewave is "),sinefreq
print("maximum of hhalf is "),maximum
#************************************************************************HARMONICS**********************************************************************************
#############WINDOW FUNCTION################
nbart=asize/2
d=hamming(nbart)
print d[:]
#e=abs(fft.fft(d))
#e=array(e)
#maximum=max(e)
#f=e/maximum
#g=log10(f)
#h=20*g
#i=fft.fftshift(h)
#plt.plot(i)
#plt.show()
gerog=a[0:(asize/2)]
print ("size of gerog is:"),gerog.size
gerog=array(gerog)
d=array(d)
mult=d*gerog
mult=array(mult)
mult1=abs(fft.fft(mult))
maxmult1=max(mult1)
mult2=mult1/maxmult1
mult3=log10(mult2)
mult4=20*mult3
mult5=fft.fftshift(mult4)
multsize=mult5.size
freq_shift1=[]
for i in range (gerog.size):
freq_shift1.append(-50000000+i*100000000/nbart)
freq_shift1=array(freq_shift1)
plt.plot(freq_shift1,mult5)
plt.title("The FFT of the signal")
plt.xlabel("frequency")
plt.ylabel("dB")
plt.show()
from math import *
from numpy import *
from matplotlib import pyplot as plt
##################### OPEN THE FILE ###################################
name=raw_input("GIVE ME THE NAME OF THE FILE:")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
#################### MAKING THE FFT ###################################
a=a-mean(a)
a=array(a)
asize=a.size
x=log2(asize)
print ("SIZE OF a IS: "),asize
print ("THE SIZE OF a EQUALS TO: 2 TO THE "),x
b=abs(fft.fft(a))
maxb=max(b)
d=b/maxb
e=log10(d)
f=20*e
h=fft.fftshift(f)
m=h.size
################ I 'LL MAKE A COUPLE:VECTOR h AND VECTOR freq #################################
freq=[]
for i in range (m):
freq.append(-50000000+i*100000000/m)
######## I'LL MAKE ANOTHER COUPLE:Vector hhalfh AND VECTOR freq_shift ##########################
hhalf=[]
freq_shift=[]
for i in range(m/2,m):
freq_shift.append(freq[i])
hhalf.append(h[i])
hhalf=array(hhalf)
freq_shift=array(freq_shift)
ser=hhalf.size
print ("SIZE OF hhalf IS:"),ser
print ("freq_shift is :"),freq_shift
########## FINDING THE POSITION OF THE MAXMUM OF hhalf=>EXPECTING THE INPUT FREQUENCY #########
for i in range (ser):
maximum=hhalf[i]
for j in range (ser):
if hhalf[j]>maximum:
maximum=hhalf[j]
sinefreq=freq_shift[j]
print("the frequency of the sinewave is "),sinefreq
print("maximum of hhalf is "),maximum
#*****************************************************************************HARMONICS**************************************************************
position=[]
distortion=[]
for i in range (ser):
#I TRY TO FIND THE POSITION OF THE HARMONICS BY SEARCHING IN freq_shift VEVTOR FOR FREQUENCIES CLOSE TO THE:f=n*sinefreq #
if (freq_shift[i]%sinefreq==0) :#if you find a harmonic
if x%2==0 :
magnitude=[]
helpfreq=[]
for j in range (int(-2**(((x-2)/2)-1)),int(2**(((x-2)/2)-1))):
magnitude.append(hhalf[i+j])
helpfreq.append(freq_shift[i+j])
magnitude=array(magnitude)
helpfreq=array(helpfreq)
maxmag=max(magnitude)
sizemag=magnitude.size
for w in range(sizemag):
if magnitude[w]>=maxmag:
maxmag=magnitude[w]
position.append(helpfreq[w])
distortion.append(magnitude[w])
else:
magnitude=[]
helpfreq=[]
for j in range(int(-2**(((x-3)/2)-1)),int(2**(((x-3)/2)-1))): #(if doubled sampling frequency is used)
magnitude.append(hhalf[i+j])
helpfreq.append(freq_shift[i+j])
magnitude=array(magnitude)
helpfreq=array(helpfreq)
maxmag=max(magnitude)
sizemag=magnitude.size
for w in range(sizemag):
if magnitude[w]>=maxmag:
maxmag=magnitude[w]
position.append(helpfreq[w])
distortion.append(magnitude[w])
print ("The position vector is:"),position[:]
print ("The distortion vector is:"),distortion[:]
distortion=array(distortion)
distsize=distortion.size
position=array(position)
meandistortion=mean(distortion)
print("the mean value of distort is :"),meandistortion
##################
realdistortion=[]
realposition=[]
for i in range(distsize):
if distortion[i]>=meandistortion:
realdistortion.append(distortion[i])
realposition.append(position[i])
print("the REAL position of distortion is: "),realposition[:]
print("the REAL distortion is: "),realdistortion[:]
########
plt.plot(freq_shift,hhalf)
plt.title("The FFT of the signal")
plt.xlabel("frequency")
plt.ylabel("dB")
plt.show()
from math import *
from numpy import *
from matplotlib import pyplot as plt
##################### OPEN THE FILE ###################################
name=raw_input("GIVE ME THE NAME OF THE FILE:")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
#################### MAKING THE FFT ###################################
a=a-mean(a)
a=array(a)
asize=a.size
x=log2(asize)
print ("SIZE OF a IS: "),asize
print ("THE SIZE OF a EQUALS TO: 2 TO THE "),x
b=abs(fft.fft(a))
maxb=max(b)
d=b/maxb
e=log10(d)
f=20*e
h=fft.fftshift(f)
m=h.size
################ I 'LL MAKE A COUPLE:VECTOR h AND VECTOR freq #################################
freq=[]
for i in range (m):
freq.append(-50000000+i*100000000/m)
######## I'LL MAKE ANOTHER COUPLE:Vector hhalfh AND VECTOR freq_shift ##########################
hhalf=[]
freq_shift=[]
for i in range(m/2,m):
freq_shift.append(freq[i])
hhalf.append(h[i])
hhalf=array(hhalf)
freq_shift=array(freq_shift)
ser=hhalf.size
sep=freq_shift.size
print ("SIZE OF hhalf IS:"),ser
########## FINDING THE POSITION OF THE MAXMUM OF hhalf=>EXPECTING THE INPUT FREQUENCY #########
for i in range (ser):
maximum=hhalf[i]
for j in range (ser):
if hhalf[j]>maximum:
maximum=hhalf[j]
sinefreq=freq_shift[j]
print("the frequency of the sinewave is "),sinefreq
print("maximum of hhalf is "),maximum
#************************************* HARMONICS *********************************************#
position=[]
distortion=[]
if x%2==0 :
################## 64 ##########################(x=12)
for i in range(int(2**(x/2))):
vector=[]
######################### 32 ###################
for j in range(int(2**((x/2)-1))):
vector.append(hhalf[j+i*(2**((x/2)-1))])
vector=array(vector)
maxh=max(vector)
for j in range(int(2**((x/2)-1))):
if vector[j]>=maxh:
maxh=vector[j]
position.append(freq_shift[j+i*(2**((x/2)-1))])
distortion.append(vector[j])
else :
########################## 128 #################(x=13)
for i in range(int((2**((x+1)/2)))):
vector=[]
############################ 32 ################
for j in range(int(2**(((x-1)/2)-1))):
vector.append(hhalf[j+i*(2**(((x-1)/2)-1))])
vector=array(vector)
maxh=max(vector)
for j in range(int(2**(((x-1)/2)-1))):
if vector[j]>=maxh:
maxh=vector[j]
position.append(freq_shift[j+i*(2**(((x-1)/2)-1))])
distortion.append(vector[j])
print("THE POSITION OF THE HARMONICS ARE :"),position[:]
plt.plot(freq_shift,hhalf)
plt.title("The FFT of the signal")
plt.xlabel("frequency")
plt.ylabel("dB")
plt.show()
from math import *
from numpy import *
from matplotlib import pyplot as plt
##################### OPEN THE FILE ###################################
name=raw_input("GIVE ME THE NAME OF THE FILE:")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
#################### MAKING THE FFT ###################################
a=a-mean(a)
a=array(a)
asize=a.size
x=log2(asize)
print ("SIZE OF a IS: "),asize
print ("THE SIZE OF a EQUALS TO: 2 TO THE "),x
b=abs(fft.fft(a))
maxb=max(b)
d=b/maxb
e=log10(d)
f=20*e
h=fft.fftshift(f)
m=h.size
################ I 'LL MAKE A COUPLE:VECTOR h AND VECTOR freq #################################
freq=[]
for i in range (m):
freq.append(-50000000+i*100000000/m)
######## I'LL MAKE ANOTHER COUPLE:Vector hhalfh AND VECTOR freq_shift ##########################
hhalf=[]
freq_shift=[]
for i in range(m/2,m):
freq_shift.append(freq[i])
hhalf.append(h[i])
hhalf=array(hhalf)
freq_shift=array(freq_shift)
ser=hhalf.size
print ("SIZE OF hhalf IS:"),ser
print ("freq_shift is :"),freq_shift
########## FINDING THE POSITION OF THE MAXMUM OF hhalf=>EXPECTING THE INPUT FREQUENCY #########
for i in range (ser):
maximum=hhalf[i]
for j in range (ser):
if hhalf[j]>maximum:
maximum=hhalf[j]
sinefreq=freq_shift[j]
print("the frequency of the sinewave is "),sinefreq
print("maximum of hhalf is "),maximum
#*****************************************************************************HARMONICS**************************************************************
position=[]
distortion=[]
for i in range (ser):
#I TRY TO FIND THE POSITION OF THE HARMONICS BY SEARCHING IN freq_shift VEVTOR FOR FREQUENCIES CLOSE TO THE:f=n*sinefreq #
if (freq_shift[i]%sinefreq==0) :#if you find a harmonic
if x%2==0 :
magnitude=[]
helpfreq=[]
for j in range (int(-2**(((x-2)/2)-1)),int(2**(((x-2)/2)-1))):
magnitude.append(hhalf[i+j])
helpfreq.append(freq_shift[i+j])
magnitude=array(magnitude)
helpfreq=array(helpfreq)
maxmag=max(magnitude)
sizemag=magnitude.size
for w in range(sizemag):
if magnitude[w]>=maxmag:
maxmag=magnitude[w]
position.append(helpfreq[w])
distortion.append(magnitude[w])
else:
magnitude=[]
helpfreq=[]
for j in range(int(-2**(((x-3)/2)-1)),int(2**(((x-3)/2)-1))): #(if doubled sampling frequency is used)
magnitude.append(hhalf[i+j])
helpfreq.append(freq_shift[i+j])
magnitude=array(magnitude)
helpfreq=array(helpfreq)
maxmag=max(magnitude)
sizemag=magnitude.size
for w in range(sizemag):
if magnitude[w]>=maxmag:
maxmag=magnitude[w]
position.append(helpfreq[w])
distortion.append(magnitude[w])
print ("The position vector is:"),position[:]
print ("The distortion vector is:"),distortion[:]
distortion=array(distortion)
distsize=distortion.size
position=array(position)
meandistortion=mean(distortion)
print("the mean value of distort is :"),meandistortion
##################
realdistortion=[]
realposition=[]
noise1=[]
for i in range(distsize):
if distortion[i]>=meandistortion:
realdistortion.append(distortion[i])
realposition.append(position[i])
for i in range (ser):
if hhalf[i]<meandistortion:
noise1.append(hhalf[i])
print("the REAL position of distortion is: "),realposition[:]
print("the REAL distortion is: "),realdistortion[:]
noise1=array(noise1)
noisesize=noise1.size
noise2=[]
for i in range(noisesize):
if noise1[i]>-140.0:
noise2.append(noise1[i])
print ("THE NOISE FLOOR IS :"),mean(noise2)
snr=maximum-mean(noise2)
print ("SNR IS (quick and dirty) :" ),snr
########
plt.plot(freq_shift,hhalf)
plt.title("The FFT of the signal")
plt.xlabel("frequency")
plt.ylabel("dB")
plt.show()
from math import *
from numpy import *
from matplotlib import pyplot as plt
##################### OPEN THE FILE ###################################
name=raw_input("GIVE ME THE NAME OF THE FILE:")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
#################### MAKING THE FFT ###################################
a=a-mean(a)
a=array(a)
asize=a.size
x=log2(asize)
print ("SIZE OF a IS: "),asize
print ("THE SIZE OF a EQUALS TO: 2 TO THE "),x
b=abs(fft.fft(a))
maxb=max(b)
d=b/maxb
e=log10(d)
f=20*e
h=fft.fftshift(f)
m=h.size
################ I 'LL MAKE A COUPLE:VECTOR h AND VECTOR freq #################################
freq=[]
for i in range (m):
freq.append(-50000000+i*100000000/m)
######## I'LL MAKE ANOTHER COUPLE:Vector hhalfh AND VECTOR freq_shift ##########################
hhalf=[]
freq_shift=[]
for i in range(m/2,m):
freq_shift.append(freq[i])
hhalf.append(h[i])
hhalf=array(hhalf)
freq_shift=array(freq_shift)
ser=hhalf.size
print ("SIZE OF hhalf IS:"),ser
print ("freq_shift is :"),freq_shift
########## FINDING THE POSITION OF THE MAXMUM OF hhalf=>EXPECTING THE INPUT FREQUENCY #########
for i in range (ser):
maximum=hhalf[i]
for j in range (ser):
if hhalf[j]>maximum:
maximum=hhalf[j]
sinefreq=freq_shift[j]
print("the frequency of the sinewave is "),sinefreq
print("maximum of hhalf is "),maximum
#############WINDOW FUNCTION################
nbart=asize/2
d=hamming(nbart)
print d[:]
#e=abs(fft.fft(d))
#e=array(e)
#maximum=max(e)
#f=e/maximum
#g=log10(f)
#h=20*g
#i=fft.fftshift(h)
#plt.plot(i)
#plt.show()
gerog=a[0:(asize/2)]
print ("size of gerog is:"),gerog.size
gerog=array(gerog)
d=array(d)
mult=d*gerog
mult=array(mult)
mult1=abs(fft.fft(mult))
maxmult1=max(mult1)
mult2=mult1/maxmult1
mult3=log10(mult2)
mult4=20*mult3
mult5=fft.fftshift(mult4)
multsize=mult5.size
freq_shift1=[]
for i in range (gerog.size):
freq_shift1.append(-50000000+i*100000000/nbart)
for i in range (gerog.size):
if freq_shift1[i]==0:
flag=i
fourievector=mult5[flag:multsize]
freqvector=freq_shift1[flag:multsize] #the distance between two elements of freqvector is 2fs/M and not fs/M. -(THE SAME HAPPENS FOR freq_shift1[])
################################################ CALCULATION OF THE DISTORTION WHEN THERE IS ALSO PROCESS GAIN SO THE HARMONICS ARE A LITTLE SPREAD ############################################################################
#################################################### THE ARRAYS THAT ARE GOING TO BE USED ARE: fourievector and freqvector #####################################################################################################
position=[]
distortion=[]
for i in range (fourievector.size):
#I TRY TO FIND THE POSITION OF THE HARMONICS BY SEARCHING IN freq_shift VECTOR FOR FREQUENCIES CLOSE TO THE:f=n*sinefreq #
if (freqvector[i]%sinefreq==0) :#if you find a harmonic
if x%2==0 :
magnitude=[]
helpfreq=[]
if i>=2**(((x-2)/2)-1) and i<=fourievector.size-2**(((x-2)/2)-1)-1:
for j in range (int(-2**(((x-2)/2)-1)),int(2**(((x-2)/2)-1))):
magnitude.append(fourievector[i+j])
helpfreq.append(freqvector[i+j])
elif i<2**(((x-2)/2)-1):
for j in range (0,int(i+2**(((x-2)/2)-1))):
magnitude.append(fourievector[j])
helpfreq.append(freqvector[j])
else:
for j in range (int(i-2**(((x-2)/2)-1)),fourievector.size):
magnitude.append(fourievector[j])
helpfreq.append(freqvector[j])
magnitude=array(magnitude)
helpfreq=array(helpfreq)
maxmag=max(magnitude)
sizemag=magnitude.size
for w in range(sizemag):
if magnitude[w]>=maxmag:
maxmag=magnitude[w]
position.append(helpfreq[w])
distortion.append(magnitude[w])
else:
magnitude=[]
helpfreq=[]
for j in range(int(-2**(((x-3)/2)-1)),int(2**(((x-3)/2)-1))):
magnitude.append(fourievector[i+j])
helpfreq.append(freqvector[i+j])
magnitude=array(magnitude)
helpfreq=array(helpfreq)
maxmag=max(magnitude)
sizemag=magnitude.size
for w in range(sizemag):
if magnitude[w]>=maxmag:
maxmag=magnitude[w]
position.append(helpfreq[w])
distortion.append(magnitude[w])
############################################# I ASSUMED THAT WHEN THERE IS A SIGNAL LEACAGE,ONLY THE HIGHEST PEAK IS A HARMONIC AND THE REST OF THE PEAKS ARE NOTHING,NOT EVEN NOISE ###################
distortion=array(distortion)
distsize=distortion.size
position=array(position)
meandistortion=mean(distortion)
realdistortion=[]
realposition=[]
for i in range(distsize):
if distortion[i]>=meandistortion:
realdistortion.append(distortion[i])
realposition.append(position[i])
print("the REAL position of distortion is: "),realposition[:]
print("the REAL distortion is: "),realdistortion[:]
freqvector=array(freqvector)
fourievector=array(fourievector)
plt.plot(freqvector,fourievector)
plt.title("The FFT of the signal")
plt.xlabel("frequency")
plt.ylabel("dB")
plt.show()
from math import *
from numpy import *
from matplotlib import pyplot as plt
##################### OPEN THE FILE ###########################################################
num_of_bits=input("GIVE ME THE NUMBER OF BITS :")
real_amplit=input("GIVE ME THE INPUT AMPLITUDE :") #(I NEED both real_amplit AND full_scale_amplitud
full_scale_amplitude=input("GIVE ME THE FULLSCALE AMPLITUDE :") # IN ORDER TO MEASURE ENOB )
name=raw_input("GIVE ME THE NAME OF THE FILE:")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
#################### MAKING THE FFT ###########################################################
a=a-mean(a)
a=array(a)
asize=a.size
x=log2(asize)
print ("NUMBER OF SAMPLES ARE(-SIZE OF a IS) : "),asize
print ("THE SIZE OF a EQUALS TO: 2 TO THE "),x
b=abs(fft.fft(a))
maxb=max(b)
d=b/maxb
e=log10(d)
f=20*e
h=fft.fftshift(f)
m=h.size
################ I 'LL MAKE A COUPLE:VECTOR h AND VECTOR freq #################################
freq=[]
for i in range (m):
freq.append(-50000000+i*100000000/m)
######## I'LL MAKE ANOTHER COUPLE:Vector hhalfh AND VECTOR freq_shift #########################
hhalf=[]
freq_shift=[]
for i in range(m/2,m):
freq_shift.append(freq[i])
hhalf.append(h[i])
hhalf=array(hhalf)
freq_shift=array(freq_shift)
ser=hhalf.size
print ("SIZE OF hhalf IS:"),ser
########## SEARCH FOR THE POSITION OF THE MAXMUM OF hhalf=>EXPECTING THE INPUT FREQUENCY #########
for i in range (ser):
maximum=hhalf[i]
for j in range (ser):
if hhalf[j]>maximum:
maximum=hhalf[j]
sinefreq=freq_shift[j]
print("the frequency of the sinewave is "),sinefreq
print("maximum of hhalf is "),maximum
#############WINDOW FUNCTION################
nbart=asize/2
d=hamming(nbart)
print d[:]
#e=abs(fft.fft(d))
#e=array(e)
#maximum=max(e)
#f=e/maximum
#g=log10(f)
#h=20*g
#i=fft.fftshift(h)
#plt.plot(i)
#plt.show()
gerog=a[0:(asize/2)]
gerog=array(gerog)
d=array(d)
mult=d*gerog
mult=array(mult)
mult1=abs(fft.fft(mult))
maxmult1=max(mult1)
mult2=mult1/maxmult1
mult3=log10(mult2)
mult4=20*mult3
mult5=fft.fftshift(mult4)
multsize=mult5.size
freq_shift1=[]
for i in range (gerog.size):
freq_shift1.append(-50000000+i*100000000/nbart)
for i in range (gerog.size):
if freq_shift1[i]==0:
flag=i
fourievector=mult5[flag:multsize]
freqvector=freq_shift1[flag:multsize] #the distance between two elements of freqvector is 2fs/M and not fs/M. -(THE SAME HAPPENS FOR freq_shift1[])
###
#helpvect=mult2[flag:multsize]
################################################ CALCULATION OF THE DISTORTION WHEN THERE IS ALSO PROCESS GAIN SO THE HARMONICS ARE A LITTLE SPREAD ############################################################################
############################################################# THE ARRAYS THAT ARE GOING TO BE USED ARE: fourievector and freqvector ############################################################################################
position=[]
distortion=[]
for i in range (fourievector.size):
#I TRY TO FIND THE POSITION OF THE HARMONICS BY SEARCHING IN freq_shift VECTOR FOR FREQUENCIES CLOSE TO THE:f=n*sinefreq #
if (freqvector[i]%sinefreq==0) :#if you find a harmonic
if x%2==0 :
magnitude=[]
helpfreq=[]
if i>=2**(((x-2)/2)-1) and i<=fourievector.size-2**(((x-2)/2)-1)-1:
for j in range (int(-2**(((x-2)/2)-1)),int(2**(((x-2)/2)-1))):
magnitude.append(fourievector[i+j])
helpfreq.append(freqvector[i+j])
elif i<2**(((x-2)/2)-1):
for j in range (0,int(i+2**(((x-2)/2)-1))):
magnitude.append(fourievector[j])
helpfreq.append(freqvector[j])
else:
for j in range (int(i-2**(((x-2)/2)-1)),fourievector.size):
magnitude.append(fourievector[j])
helpfreq.append(freqvector[j])
magnitude=array(magnitude)
helpfreq=array(helpfreq)
maxmag=max(magnitude)
sizemag=magnitude.size
for w in range(sizemag):
if magnitude[w]>=maxmag:
maxmag=magnitude[w]
position.append(helpfreq[w])
distortion.append(magnitude[w])
else:
magnitude=[]
helpfreq=[]
for j in range(int(-2**(((x-3)/2)-1)),int(2**(((x-3)/2)-1))):
magnitude.append(fourievector[i+j])
helpfreq.append(freqvector[i+j])
magnitude=array(magnitude)
helpfreq=array(helpfreq)
maxmag=max(magnitude)
sizemag=magnitude.size
for w in range(sizemag):
if magnitude[w]>=maxmag:
maxmag=magnitude[w]
position.append(helpfreq[w])
distortion.append(magnitude[w])
############################################# I ASSUMED THAT WHEN THERE IS A SIGNAL LEACAGE,ONLY THE HIGHEST PEAK IS A HARMONIC AND THE REST OF THE PEAKS ARE NOTHING,NOT EVEN NOISE ###################
distortion=array(distortion)
distsize=distortion.size
position=array(position)
meandistortion=mean(distortion)
realdistortion=[]
realposition=[]
noise1=[]
for i in range(distsize):
if (distortion[i]>=meandistortion) and (position[i]>sinefreq):
realdistortion.append(distortion[i])
realposition.append(position[i])
#*********************************************************** C A L C U L A T I O N O F N O I S E ==> SNR *********************************************************************************************
for i in range (ser):
if hhalf[i]<meandistortion:
noise1.append(hhalf[i])
noise1=array(noise1)
noisesize=noise1.size
noise2=[]
for i in range(noisesize):
if noise1[i]>-140.0:
noise2.append(noise1[i])
print ("THE NOISE FLOOR IS :"),mean(noise2)
snr=maximum-mean(noise2)-10*log10(asize/2) # there is also the process gain:10*log10(asize/2) #
snr_theoret=6.02*num_of_bits+1.76
print("******************************* SNR ********************************************")
print ("SNR IS (quick and dirty) :" ),snr
print ("SNRtheoretical IS :"),snr_theoret
#*********************************************************************************************************************************************************************************************************
#**************************************************************** C A L C U L A T I O N O F D I S T O R T I O N ==> THD ******************************************************************************
print("******************************* THD*********************************************")
print("the REAL position of distortion is: "),realposition[:]
print("the REAL distortion is: "),realdistortion[:]
realposition=array(realposition)
realdistortion=array(realdistortion)
thd1=[]
for i in range (realdistortion.size):
thd1.append(realdistortion[i]/20.0)
thd1=array(thd1)
thd2=thd1*2
thd2=array(thd2)
thd3=10**(thd2)
thd4=0
for i in range (realdistortion.size-1):
if thd3[i]!=1 :
thd4=thd4+thd3[i]
thd=10*log10(thd4)
print ("THD IS :"),thd
#********************************************************************************************************************************************************************************************************
#*********************************************************************************************** C A L C U L A T I O N O F SINAD *************************************************************************
print("**************************** SINAD ***********************************************")
sinad1=-(snr)/10.0
sinad2=10**(sinad1)
sinad3=-abs(thd)/10.0
sinad4=10**(sinad3)
sinad5=sinad2+sinad4
sinad=-10*log10(sinad5)
print("SINAD IS :"),sinad
#************************************************************************************************************************************************************************************************************
#****************************************************************************************** C A L C U L A T I O N O F ENOB ********************************************************************************
print("**************************** ENOB ************************************************")
factor=20*log10(full_scale_amplitude/real_amplit)
enob=(sinad-1.76+factor)/6.02
print ("ENOB IS :"),enob
#*************************************************************************************************************************************************************************************************************
#******************************************************************************************** PLOTTING *******************************************************************************************************
freqvector=array(freqvector)
fourievector=array(fourievector)
plt.plot(freqvector,fourievector)
plt.title("The FFT of the signal")
plt.xlabel("frequency")
plt.ylabel("dB")
plt.show()
from math import *
from matplotlib import pyplot as plt
from numpy import *
##########MAKING THE HISTOGRAM##################
def histo(bits, samples):
c=[]
d=[]
c,d=histogram(samples,2**bits)
plt.hist(samples,2**bits)
# plt.show()
return c
b=input("give number of bits :")
name=raw_input("give me the name of the file :")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
#########CALCULATE THE NUMBER OF SAMPLES###########
a=array(a)
mt=a.size
print ("number of samples is"),mt
###################################################
e=[]
e=histo(b,a)
print ("the number of occurencies per bin are "),e[:]
h_first=e[0]
last=int(2**b-1)
h_last=e[last]
#########CALCULATING THE ESTIMATED AMPLITUDE########
fsr=input("give me fsr: ")
g=(math.pi/2)
help1=float(mt+h_first+h_last)
help=(mt/help1)
w=(g*(help))
k=float(math.sin(w))
amp=float(fsr/k)
####################################################
##########CALCULATING THE p(n)######################
p=[]
print("the amplitude is "),amp
for i in range(2**b):
twobits = 2**b
twobits1 = 2**(b-1)
pirecip = 1/math.pi
p.append(pirecip * (math.asin(fsr*(i -twobits1)/(amp*twobits))
-math.asin(fsr*(i-1-twobits1)/(amp*twobits))))
print p[:]
####################################################
h=p*mt
############CALCULATING DNL ERROR###################
dnl=[]
for i in range (2**b):
dnl.append(e[i]/h[i]-1)
print ("T H E DNL E R R O R S A R E :"),dnl[:]
####################################################
from math import *
from matplotlib import pyplot as plt
from numpy import *
##########MAKING THE HISTOGRAM##################
def histo(bits, samples):
c=[]
d=[]
c,d=histogram(samples,2**bits)
plt.hist(samples,2**bits)
# plt.show()
return c
b=input("give number of bits :")
name=raw_input("give me the name of the file :")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
#########CALCULATE THE NUMBER OF SAMPLES###########
a=array(a)
mt=a.size
print ("number of samples is"),mt
###################################################
e=[]
e=histo(b,a)
print ("the number of occurencies per bin are "),e[:]
h_first=e[0]
last=int(2**b-1)
h_last=e[last]
#########CALCULATING THE ESTIMATED AMPLITUDE########
fsr=input("give me fsr: ")
g=(math.pi/2)
help1=float(mt+h_first+h_last)
help=(mt/help1)
w=(g*(help))
k=float(math.sin(w))
amp=float(fsr/k)
####################################################
##########CALCULATING THE p(n)######################
p=[]
print("the amplitude is "),amp
for i in range(2**b):
twobits = 2**b
twobits1 = 2**(b-1)
pirecip = 1/math.pi
p.append(pirecip * (math.asin(fsr*(i -twobits1)/(amp*twobits))
-math.asin(fsr*(i-1-twobits1)/(amp*twobits))))
print p[:]
####################################################
h=p*mt
inl=0
############CALCULATING DNL ERROR###################
dnl=[]
for i in range (2**b):
dnl.append(e[i]/h[i]-1)
inl=inl+dnl[i]
print ("T H E DNL E R R O R S A R E :"),dnl[:]
####################################################
print ("T H E INL E R R O R S A R E :"),inl
from math import *
from matplotlib import pyplot as plt
from numpy import *
def histo(bits, samples):
#making the histogram of the digital samples of a sinewave#
c=[]
d=[]
c,d=histogram(samples,2**bits)
plt.hist(samples,2**bits)
plt.show()
return c
b=input("give number of bits :")
name=raw_input("give me the name of the file :")
f=file(name)
a=[]
for line in f:
value=int(line)
a.append(value)
e=[]
e=histo(b,a)
print e[:]
from numpy import*
from math import *
import matplotlib.pyplot as plt
##############################MAKING THE SINEWAVE######################
def argument(n,sampl_rate,fr,ph):
#produce a vector of the arguments of the sinewave#
arg=[]
for i in range(n):
arg.append(2*pi*fr*i/sampl_rate+ph*2*pi)
return arg
def make_sinewave (n,v,amp):
#produces the values if the sinewave#
b=[]
for i in range (n):
b.append(amp*sin(v[i]))
return b
###############################MAKING THE TRANSFER FUNCTION###########
def adc_transfer(v, fsr, bits,num_of_samples):
#MAKING THE TRANSFER FUNCTION
c=2**bits
a=float(2**bits)
lsb=(fsr/a)
print("the LSB is"),lsb
digital=[]
analog=[]
for i in range (c):
b=lsb*i
analog.append(b)
digital.append(i)
#PLOTTING THE TRANSFER FUNCTION
#pl.plot(analog, digital)
#pl.show()
#AND NOW THE CORRESPONDANCE!!!
vdig=[]
for j in range(num_of_samples):
i=0
if (v[j]>=analog[0]) and (v[j]<=analog[int(math.pow(2,bits)-1)]): #if the value given is in tha full scale range#
while i<c:
if (v[j]>=analog[i]) and (v[j]<analog[i+1]):
flag=digital[i]
vdig.append(flag)
i=i+1
elif (v[j]>analog[int(math.pow(2,bits)-1)]) :
vdig.append(digital[int(math.pow(2,bits)-1)])
else:
vdig.append(digital[0])
return vdig[:]
a=input("please give amplitude:")
f=input("please give the sinewave's frequency:")
p=input("please give phase:")
sr=input("please give sampling rate:")
s=input("please give number of samples:")
vector=argument(s,sr,f,p)
print ("these are the values of the sinewave")
sine=make_sinewave(s,vector,a)
print sine[:]
############################################################################
full_scale_range=input("GIVE ME THE FULL SCALE RANGE: ")
num_of_bits=input("GIVE ME THE NUMBER OF BITS: ")
digital_value=adc_transfer(sine,full_scale_range,num_of_bits,s)
print ("THE DIGITAL VALUE CORRESPONDING TO THE ANALOG IS :"),digital_value[:]
####################DNL AND INL ERRORS####################################
##########MAKING THE HISTOGRAM##################
def histo(bits, samples):
c=[]
d=[]
c,d=histogram(samples,2**bits)
plt.hist(samples,2**bits)
# plt.show()
return c
b=num_of_bits
a=[]
for i in range (s):
value=digital_value[i]
a.append(value)
#########CALCULATE THE NUMBER OF SAMPLES###########
a=array(a)
mt=s
###################################################
e=[]
e=histo(b,a)
print ("the number of occurencies per bin are "),e[:]
h_first=e[0]
last=int(2**b-1)
h_last=e[last]
#########CALCULATING THE ESTIMATED AMPLITUDE########
fsr=full_scale_range
g=(math.pi/2)
help1=float(mt+h_first+h_last)
help=(mt/help1)
w=(g*(help))
k=float(math.sin(w))
amp=float(fsr/k)
####################################################
##########CALCULATING THE p(n)######################
p=[]
print("the amplitude is "),amp
for i in range(2**b):
twobits = 2**b
twobits1 = 2**(b-1)
pirecip = 1/math.pi
p.append(pirecip * (math.asin(fsr*(i -twobits1)/(amp*twobits))
-math.asin(fsr*(i-1-twobits1)/(amp*twobits))))
print p[:]
####################################################
h=p*mt
inl=0
############CALCULATING DNL ERROR###################
dnl=[]
for i in range (2**b):
dnl.append(e[i]/h[i]-1)
inl=inl+dnl[i]
print ("T H E DNL E R R O R S A R E :"),dnl[:]
####################################################
print ("T H E INL E R R O R S A R E :"),inl
from math import *
from numpy import *
from matplotlib import pyplot as plt
##################### OPEN THE FILE ###########################################################
num_of_bits=input("GIVE ME THE NUMBER OF BITS :")
real_amplit=input("GIVE ME THE INPUT AMPLITUDE :") #(I NEED both real_amplit AND full_scale_amplitud
full_scale_amplitude=input("GIVE ME THE FULLSCALE AMPLITUDE :") # IN ORDER TO MEASURE ENOB )
name=raw_input("GIVE ME THE NAME OF THE FILE:")
f=open(name)
a=[]
for line in f:
value=int(line)
a.append(value)
#################### MAKING THE FFT ###########################################################
a=a-mean(a)
a=array(a)
asize=a.size
x=log2(asize)
print ("NUMBER OF SAMPLES ARE(-SIZE OF a IS) : "),asize
print ("THE SIZE OF a EQUALS TO: 2 TO THE "),x
b=abs(fft.fft(a))
maxb=max(b)
d=b/maxb
e=log10(d)
f=20*e
h=fft.fftshift(f)
m=h.size
################ I 'LL MAKE A COUPLE:VECTOR h AND VECTOR freq #################################
freq=[]
for i in range (m):
freq.append(-50000000+i*100000000/m)
######## I'LL MAKE ANOTHER COUPLE:Vector hhalfh AND VECTOR freq_shift #########################
hhalf=[]
freq_shift=[]
for i in range(m/2,m):
freq_shift.append(freq[i])
hhalf.append(h[i])
hhalf=array(hhalf)
freq_shift=array(freq_shift)
ser=hhalf.size
print ("SIZE OF hhalf IS:"),ser
########## SEARCH FOR THE POSITION OF THE MAXMUM OF hhalf=>EXPECTING THE INPUT FREQUENCY #########
for i in range (ser):
maximum=hhalf[i]
for j in range (ser):
if hhalf[j]>maximum:
maximum=hhalf[j]
sinefreq=freq_shift[j]
print("the frequency of the sinewave is "),sinefreq
print("maximum of hhalf is "),maximum
#############WINDOW FUNCTION################
nbart=asize/2
d=hamming(nbart)
print d[:]
#e=abs(fft.fft(d))
#e=array(e)
#maximum=max(e)
#f=e/maximum
#g=log10(f)
#h=20*g
#i=fft.fftshift(h)
#plt.plot(i)
#plt.show()
gerog=a[0:(asize/2)]
gerog=array(gerog)
d=array(d)
mult=d*gerog
mult=array(mult)
mult1=abs(fft.fft(mult))
maxmult1=max(mult1)
mult2=mult1/maxmult1
mult3=log10(mult2)
mult4=20*mult3
mult5=fft.fftshift(mult4)
multsize=mult5.size
freq_shift1=[]
for i in range (gerog.size):
freq_shift1.append(-50000000+i*100000000/nbart)
for i in range (gerog.size):
if freq_shift1[i]==0:
flag=i
fourievector=mult5[flag:multsize]
freqvector=freq_shift1[flag:multsize] #the distance between two elements of freqvector is 2fs/M and not fs/M. -(THE SAME HAPPENS FOR freq_shift1[])
###
#helpvect=mult2[flag:multsize]
################################################ CALCULATION OF THE DISTORTION WHEN THERE IS ALSO PROCESS GAIN SO THE HARMONICS ARE A LITTLE SPREAD ############################################################################
############################################################# THE ARRAYS THAT ARE GOING TO BE USED ARE: fourievector and freqvector ############################################################################################
position=[]
distortion=[]
for i in range (fourievector.size):
#I TRY TO FIND THE POSITION OF THE HARMONICS BY SEARCHING IN freq_shift VECTOR FOR FREQUENCIES CLOSE TO THE:f=n*sinefreq #
if (freqvector[i]%sinefreq==0) :#if you find a harmonic
if x%2==0 :
magnitude=[]
helpfreq=[]
if i>=2**(((x-2)/2)-1) and i<=fourievector.size-2**(((x-2)/2)-1)-1:
for j in range (int(-2**(((x-2)/2)-1)),int(2**(((x-2)/2)-1))):
magnitude.append(fourievector[i+j])
helpfreq.append(freqvector[i+j])
elif i<2**(((x-2)/2)-1):
for j in range (0,int(i+2**(((x-2)/2)-1))):
magnitude.append(fourievector[j])
helpfreq.append(freqvector[j])
else:
for j in range (int(i-2**(((x-2)/2)-1)),fourievector.size):
magnitude.append(fourievector[j])
helpfreq.append(freqvector[j])
magnitude=array(magnitude)
helpfreq=array(helpfreq)
maxmag=max(magnitude)
sizemag=magnitude.size
for w in range(sizemag):
if magnitude[w]>=maxmag:
maxmag=magnitude[w]
position.append(helpfreq[w])
distortion.append(magnitude[w])
else:
magnitude=[]
helpfreq=[]
for j in range(int(-2**(((x-3)/2)-1)),int(2**(((x-3)/2)-1))):
magnitude.append(fourievector[i+j])
helpfreq.append(freqvector[i+j])
magnitude=array(magnitude)
helpfreq=array(helpfreq)
maxmag=max(magnitude)
sizemag=magnitude.size
for w in range(sizemag):
if magnitude[w]>=maxmag:
maxmag=magnitude[w]
position.append(helpfreq[w])
distortion.append(magnitude[w])
############################################# I ASSUMED THAT WHEN THERE IS A SIGNAL LEACAGE,ONLY THE HIGHEST PEAK IS A HARMONIC AND THE REST OF THE PEAKS ARE NOTHING,NOT EVEN NOISE ###################
distortion=array(distortion)
distsize=distortion.size
position=array(position)
meandistortion=mean(distortion)
realdistortion=[]
realposition=[]
noise1=[]
for i in range(distsize):
if (distortion[i]>=meandistortion) and (position[i]>sinefreq):
realdistortion.append(distortion[i])
realposition.append(position[i])
#*********************************************************** C A L C U L A T I O N O F N O I S E ==> SNR *********************************************************************************************
for i in range (ser):
if hhalf[i]<meandistortion:
noise1.append(hhalf[i])
noise1=array(noise1)
noisesize=noise1.size
noise2=[]
for i in range(noisesize):
if noise1[i]>-140.0:
noise2.append(noise1[i])
print ("THE NOISE FLOOR IS :"),mean(noise2)
snr=maximum-mean(noise2)-10*log10(asize/2) # there is also the process gain:10*log10(asize/2) #
snr_theoret=6.02*num_of_bits+1.76
print("******************************* SNR ********************************************")
print ("SNR IS (quick and dirty) :" ),snr
print ("SNRtheoretical IS :"),snr_theoret
#*********************************************************************************************************************************************************************************************************
#**************************************************************** C A L C U L A T I O N O F D I S T O R T I O N ==> THD ******************************************************************************
print("******************************* THD*********************************************")
print("the REAL position of distortion is: "),realposition[:]
print("the REAL distortion is: "),realdistortion[:]
realposition=array(realposition)
realdistortion=array(realdistortion)
thd1=[]
for i in range (realdistortion.size):
thd1.append(realdistortion[i]/20.0)
thd1=array(thd1)
thd2=thd1*2
thd2=array(thd2)
thd3=10**(thd2)
thd4=0
for i in range (realdistortion.size-1):
if thd3[i]!=1 :
thd4=thd4+thd3[i]
thd=10*log10(thd4)
print ("THD IS :"),thd
#********************************************************************************************************************************************************************************************************
#*********************************************************************************************** C A L C U L A T I O N O F SINAD *************************************************************************
print("**************************** SINAD ***********************************************")
sinad1=-(snr)/10.0
sinad2=10**(sinad1)
sinad3=-abs(thd)/10.0
sinad4=10**(sinad3)
sinad5=sinad2+sinad4
sinad=-10*log10(sinad5)
print("SINAD IS :"),sinad
#************************************************************************************************************************************************************************************************************
#****************************************************************************************** C A L C U L A T I O N O F ENOB ********************************************************************************
print("**************************** ENOB ************************************************")
factor=20*log10(full_scale_amplitude/real_amplit)
enob=(sinad-1.76+factor)/6.02
print ("ENOB IS :"),enob
#*************************************************************************************************************************************************************************************************************
#******************************************************************************************** PLOTTING *******************************************************************************************************
freqvector=array(freqvector)
fourievector=array(fourievector)
plt.plot(freqvector,fourievector)
plt.title("The FFT of the signal")
plt.xlabel("frequency")
plt.ylabel("dB")
#plt.plot(a[0:500])
plt.show()
from math import *
from matplotlib import pyplot as plt
from numpy import *
#################################################################### CREATING THE DISTORTED SINEWAVE #################################################
def make_sinewaveforunipolar (n,sampl_rate,fr,ph,amp,fullsr):
#produces the values of the sinewave#
b=[]
maj=[]
for i in range (n):
b.append(fullsr/2.0+amp*sin(2.0*pi*fr*i/sampl_rate+ph*2.0*pi))
#b.append(fullsr/2+amp*sin(2*pi*fr*i/sampl_rate+ph*2*pi)+0.02*amp*sin(4.44*pi*fr*i/sampl_rate+ph*2*pi)+0.09*amp*sin(6.66*pi*fr*i/sampl_rate+ph*2*pi))
return b
def make_sinewaveforbipolar (n,sampl_rate,fr,ph,amp,fullsr):
#produces the values of the sinewave#
b=[]
for i in range (n):
b.append(amp*sin(2.0*pi*fr*i/sampl_rate+ph*2.0*pi))
#b.append(amp*sin(2.0*pi*fr*i/sampl_rate+ph*2.0*pi)+0.02*amp*sin(4.44*pi*fr*i/sampl_rate+ph*2*pi)+0.09*amp*sin(6.66*pi*fr*i/sampl_rate+ph*2*pi))
return b
#################################################################### ANALOG TO DIGITAL ################################################################
def adc_transferunipolar(v, fsr, bits):
#MAKING THE TRANSFER FUNCTION FOR UNIPOLAR ADC
a=2.0**bits
lsb=float(fsr/a)
digital=[]
analog=[]
for i in range (int(a)):
b=lsb*i
analog.append(b)
digital.append(i)
#PLOTTING THE TRANSFER FUNCTION
#pl.plot(analog, digital)
#pl.show()
#AND NOW THE CORRESPONDENCE!!!
i=0
if (v>=analog[0]) and (v<=analog[int(math.pow(2,bits)-1)]):
while i<=a-1:
if (v>=analog[i]) and (v<analog[i+1]):
d=(digital[i])
i=i+1
elif (v>analog[int(math.pow(2,bits)-1)]) :
d=( digital[int(math.pow(2,bits)-1)])
else:
d=(digital[0])
return d
def adc_transferbipolar(v, fsr, bits,vfs):
#MAKING THE TRANSFER FUNCTION FOR BIPOLAR ADC
a=2.0**bits
lsb=float(fsr/a)
digital=[]
analog=[]
for i in range (int(a)):
b=-vfs+lsb*i
analog.append(b)
digital.append(i)
#PLOTTING THE TRANSFER FUNCTION
#plt.plot(analog, digital)
#plt.show()
#AND NOW THE CORRESPONDENCE!!!
i=0
if (v>=analog[0]) and (v<=analog[int(math.pow(2,bits)-1)]):
while i<=a-1:
if (v>=analog[i]) and (v<analog[i+1]):
d=(digital[i])
i=i+1
elif (v>analog[int(math.pow(2,bits)-1)]) :
d=( digital[int(math.pow(2,bits)-1)])
else:
d=(digital[0])
return d
#################################################################### MAKING THE HISTOGRAM #############################################################
#def histo(bits, samples):
# c=[]
# d=[]
# c,d=histogram(samples,2**bits)
# plt.hist(samples,2**bits)
# plt.show()
# return c
def histo(bits,samples):
samples=array(samples)
c=[]
for i in range (2**bits):
c.append(0)
i=0
for j in range (2**bits):
for i in range(samples.size):
if (samples[i]==j):
c[j]=c[j]+1
return c
##################################################################### THE INPUTS #######################################################################
#b=input("give number of bits :")
#fsr=input("give me fsr(volts): ")
#a=input("please give amplitude(volts):")
#f=input("please give the sinewave's frequency(Hertz):")
#p=input("please give phase:")
#sr=input("please give sampling rate(Hertz):")
#s=input("please give number of samples:")
#bipolar=input("if the ADC is bipolar then press 1,else press 0 :")
b=8
fsr=10
a=5
f=0.31415164576
p=0
sr=8000
s=100000
bipolar=1
#######################################
fs=fsr/2
samples=[] #making the sinewave's samples
if (bipolar==0):
samples=make_sinewaveforunipolar(s,sr,f,p,a,fsr)
elif (bipolar==1):
samples=make_sinewaveforbipolar(s,sr,f,p,a,fsr)
samples=array(samples)
dig_samples=[] #the convertion
if (bipolar==0):
for i in range (s):
dig_samples.append(adc_transferunipolar(samples[i], fsr, b))
elif (bipolar==1):
for i in range (s):
dig_samples.append(adc_transferbipolar(samples[i], fsr, b, fs))
dig_samples=array(dig_samples)
#to be sure that the frequency of the sinewave and the sampling frequency are not correlated,i need dig_samples to have a lot of different from each other values
e=[]
e=histo(b,dig_samples)
#print ("the number of occurencies per bin are "),e[:]
print (" ")
e=array(e)
ala=0 #this variable shows the number of different values
for i in range (e.size):
if (e[i]!=0):
ala=ala+1
h_first=e[0]
last=e.size
h_last=e[last-1]
#########CALCULATING THE ESTIMATED AMPLITUDE########
lsb=fsr/(2.0**b)
print("the lsb is :"),lsb
print (" ")
g=(math.pi/2)
help1=float(s+h_first+h_last)
help2=float((s/help1))
w=float((g*(help2)))
k=float(math.sin(float(w)))
amp=float(fs/k)
print("the estimated amplitude is "),amp
print (" ")
####################################################
##########CALCULATING THE p(n)######################
p=[]
twobits = 2.0**b
twobits1 = 2.0**(b-1)
pirecip = 1.0/math.pi
for i in range(1,int(twobits)+1):
p.append(pirecip*( math.asin(2*fs*(i -twobits1)/(amp*twobits)) - math.asin(2*fs*(i-1-twobits1)/(amp*twobits)) ))
p=array(p)
print (" ")
##########CALCULATING h(n)theoretical##############
h=[]
for i in range(p.size):
h.append(p[i]*s)
#print(" ")
h=array(h)
#print("the theoretical number of samples is :"),sum(h)
############CALCULATING DNL ERROR###################
dnl=[]
help4=0.0
help5=0.0
#for i in range (1,2**b+-1):
for i in range (0,2**b):
help4=(e[i]/h[i])
help5=help4-1.0
dnl.append(help5)
dnl=array(dnl)
alala=0
for i in range ((2**b)-2):
if (dnl[i]!=-1.0):
alala=alala+1 #this variable calculates how many different values dnl vector has
##print ("T H E DNL E R R O R S A R E :"),dnl[:]
##########CALCULATING INL ERROR#####################
dnl=dnl[1:dnl.size-2]
inl=[]
for i in range (dnl.size):
inl.append(0)
for i in range (dnl.size):
for j in range (i+1):
inl[i]=inl[i]+dnl[j]
print(inl[0])
print (" The maximum deviation of the transfer function is :") ,max(dnl) ,("LSBs.Which means :"), ((max(dnl)/(2**b))*100),("%FSR.")
####################################################
rang=range(dig_samples.size)
plt.plot(rang,samples,rang,dig_samples)
plt.plot(inl)
plt.plot(dig_samples)
plt.show()
from math import *
from matplotlib import pyplot as plt
from numpy import *
name=raw_input("give me the name of the file :")
f=file(name)
a=[]
b=[]
i=0
for line in f:
value=int(line)
a.append(value)
b.append(i)
i=i+1
plt.plot(b,a)
plt.show()
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment