Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions deltasigma/_PlotExampleSpectrum.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,10 @@ def PlotExampleSpectrum(ntf, M=1, osr=64, f0=0, quadrature=False):
NBW = 1.5/N
spec0 = fft(v * window)/(M*N/4)
if not quadrature:
freq = np.linspace(0, 0.5, N/2 + 1)
plt.plot(freq, dbv(spec0[:N/2 + 1]), 'c', linewidth=1)
plt.hold(True)
freq = np.linspace(0, 0.5, N//2 + 1)
plt.plot(freq, dbv(spec0[:N//2 + 1]), 'c', linewidth=1)
spec_smoothed = circ_smooth(np.abs(spec0)**2., 16)
plt.plot(freq, dbp(spec_smoothed[:N/2 + 1]), 'b', linewidth=3)
plt.plot(freq, dbp(spec_smoothed[:N//2 + 1]), 'b', linewidth=3)
Snn = np.abs(evalTF(ntf, np.exp(2j*np.pi*freq)))**2 * 2/12*(delta/M)**2
plt.plot(freq, dbp(Snn*NBW), 'm', linewidth=1)
snr = calculateSNR(spec0[f1_bin:f2_bin + 1], fin - f1_bin)
Expand All @@ -123,15 +122,14 @@ def PlotExampleSpectrum(ntf, M=1, osr=64, f0=0, quadrature=False):
freq = np.linspace(-0.5, 0.5, N + 1)
freq = freq[:-1]
plt.plot(freq, dbv(spec0), 'c', linewidth=1)
plt.hold(True)
spec_smoothed = circ_smooth(abs(spec0)**2, 16)
plt.plot(freq, dbp(spec_smoothed), 'b', linewidth=3)
Snn = abs(evalTF(ntf, np.exp(2j * np.pi * freq))) ** 2 * 2 / 12 * (delta / M) ** 2
plt.plot(freq, dbp(Snn*NBW), 'm', linewidth=1)
snr = calculateSNR(spec0[N/2 + f1_bin:N/2 + f2_bin + 1], fin - f1_bin)
snr = calculateSNR(spec0[N//2 + f1_bin:N//2 + f2_bin + 1], fin - f1_bin)
msg = 'SQNR = %.1fdB\n @ A = %.1fdBFS & osr = %.0f' % \
(snr, dbv(spec0[N/2 + fin]), osr)
if f0 >= 0:
(snr, dbv(spec0[N//2 + fin]), osr)
if f0 >= 0:
plt.text(f0 - 0.05, - 15, msg, horizontalalignment='right',
verticalalignment='bottom')
else:
Expand Down
4 changes: 3 additions & 1 deletion deltasigma/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -915,7 +915,9 @@
# if not os.system('python -c "import matplotlib.pyplot as plt;plt.figure()"')
import matplotlib
import os
if not ('DISPLAY' in os.environ or os.environ.get('READTHEDOCS', None)):
if not ('DISPLAY' in os.environ
or os.name == 'nt'
or os.environ.get('READTHEDOCS', None)):
matplotlib.use('Agg')

from ._DocumentNTF import DocumentNTF
Expand Down
4 changes: 2 additions & 2 deletions deltasigma/_bplogsmooth.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ def bplogsmooth(X, tbin, f0):
m = m - int(n)
lsb1 = np.concatenate((lsb2[1:] + 1, np.ones((1,))))

startbin = np.concatenate((lsb1[::-1], usb1)) - 1
stopbin = np.concatenate((lsb2[::-1], usb2)) - 1
startbin = np.concatenate((lsb1[::-1], usb1)).astype(np.int) - 1
stopbin = np.concatenate((lsb2[::-1], usb2)).astype(np.int) - 1

f = ((startbin + stopbin)/2.)/N - f0
p = np.zeros(f.shape)
Expand Down
2 changes: 1 addition & 1 deletion deltasigma/_ds_optzeros.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def ds_optzeros(n, opt=1):
"""
opt = int(opt)
if opt == 0:
optZeros = np.zeros((np.ceil(n/2.), ))
optZeros = np.zeros((int(np.ceil(n/2.)), ))
else:
optZeros = _oznopt[n][opt]

Expand Down
4 changes: 3 additions & 1 deletion deltasigma/_ds_synNTFobj1.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
"""Module providing the ds_synNTFobj1() function
"""

from __future__ import division

import numpy as np

from ._db import db
Expand All @@ -37,7 +39,7 @@ def ds_synNTFobj1(x, p, osr, f0):
z = np.exp(2j*np.pi*(f0 + 0.5/osr*x))
z = carray(z)
if f0 > 0:
z = padt(z, p.shape[0]/2., np.exp(2j*np.pi*f0))
z = padt(z, p.shape[0]//2, np.exp(2j*np.pi*f0))

z = np.hstack((z, np.conj(z)))
z = z[:]
Expand Down
2 changes: 1 addition & 1 deletion deltasigma/_mapABCD.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def mapABCD(ABCD, form='CRFB'):
for i in range(1, order, 2):
b[i] = b[i] - c[i]*b[i - 1]
if odd:
b[i] = b[i] + g[(i - 1)/2]*b[i + 1]
b[i] = b[i] + g[(i - 1)//2]*b[i + 1]
yscale = ABCD[order + 1, order]
a = a*yscale
b[-1] = b[-1]*yscale
Expand Down
4 changes: 2 additions & 2 deletions deltasigma/_mapCtoD.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,8 @@ def mapCtoD(sys_c, t=(0, 1), f0=0.):
if t1 == 0 and t2 == 1 and D2 == 0: # No fancy stuff necessary
Bp = Bp + padb(B2, npp)
else:
n1 = np.floor(t1)
n2 = np.ceil(t2) - n1 - 1
n1 = int(np.floor(t1))
n2 = int(np.ceil(t2)) - n1 - 1
t1 = t1 - n1
t2 = t2 - n2 - n1
if t2 == 1 and D2 != 0:
Expand Down
3 changes: 0 additions & 3 deletions deltasigma/_peakSNR.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,5 @@ def peakSNR(snr, amp):
if _debug:
import pylab as plt
pred = np.dot(A, ab)
hold = plt.ishold()
plt.hold(True)
plt.plot(dbv(amp), dbv(pred), '-', color='b')
plt.hold(hold)
return peak_snr, peak_amp
9 changes: 2 additions & 7 deletions deltasigma/_plotPZ.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ def plotPZ(H, color='b', markersize=5, showlist=False):
p = np.real_if_close(np.round(p, 5))
z = np.real_if_close(np.round(z, 5))

pole_fmt = {'marker': 'x', 'markersize': markersize}
zero_fmt = {'marker': 'o', 'markersize': markersize}
pole_fmt = {'marker': 'x', 'markersize': markersize, 'mew': markersize}
zero_fmt = {'marker': 'o', 'markersize': markersize, 'mew': markersize}

if isinstance(color, list) or isinstance(color, tuple):
pole_fmt['color'] = color[0]
Expand All @@ -82,12 +82,10 @@ def plotPZ(H, color='b', markersize=5, showlist=False):
pole_fmt['color'] = color
zero_fmt['color'] = color

hold_status = plt.ishold()
plt.grid(True)

# Plot x and o for poles and zeros, respectively
plt.plot(p.real, p.imag, linestyle='None', **pole_fmt)
plt.hold(True)
if len(z) > 0:
plt.plot(z.real, z.imag, linestyle='None', **zero_fmt)

Expand Down Expand Up @@ -128,6 +126,3 @@ def plotPZ(H, color='b', markersize=5, showlist=False):
# plt.axes().set_aspect('equal', 'datalim')
plt.ylabel('Imag')
plt.xlabel('Real')

if not hold_status:
plt.hold(False)
4 changes: 2 additions & 2 deletions deltasigma/_predictSNR.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,12 @@ def powerGain(num, den, Nimp=100):
unstable = False
_, (imp, ) = dimpulse((num, den, 1), t=np.linspace(0, Nimp, Nimp))
if np.sum(abs(imp[Nimp - 11:Nimp])) < 1e-08 and Nimp > 50:
Nimp = np.round(Nimp/1.3)
Nimp = int(np.round(Nimp/1.3))
else:
while np.sum(abs(imp[Nimp - 11:Nimp])) > 1e-06:
Nimp = Nimp*2
_, (imp, ) = dimpulse((num, den, 1), t=np.linspace(0, Nimp, Nimp))
if np.sum(abs(imp[Nimp - 11:Nimp])) >= 50 or Nimp >= 10000.0:
if np.sum(abs(imp[Nimp - 11:Nimp])) >= 50 or Nimp >= 10000:
unstable = True
break

Expand Down
7 changes: 4 additions & 3 deletions deltasigma/_pulse.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,11 @@ def pulse(S, tp=(0., 1.), dt=1., tfinal=10., nosum=False):
nis = int(ni/ndac)

# notice len(S[0]) is the number of outputs for us
if not nosum: # Sum the responses due to each input set
y = np.zeros((np.ceil(tfinal/float(dt)) + 1, len(S[0]), nis))
tceil = int(np.ceil(tfinal/float(dt))) + 1
if not nosum: # Sum the responses due to each input set
y = np.zeros((tceil, len(S[0]), nis))
else:
y = np.zeros((np.ceil(tfinal/float(dt)) + 1, len(S[0]), ni))
y = np.zeros((tceil, len(S[0]), ni))

for i in range(ndac):
n1 = int(np.round(tp[i, 0]/delta_t, 0))
Expand Down
6 changes: 3 additions & 3 deletions deltasigma/_realizeNTF_ct.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def realizeNTF_ct(ntf, form='FB', tdac=(0, 1), ordering=None, bp=None,
ntf_z = carray(ntf_z)
ntf_p = carray(ntf_p)
order = max(ntf_p.shape)
order2 = int(np.floor(order/2.))
order2 = order//2
odd = order - 2*order2
# compensate for limited accuracy of zero calculation
ntf_z[np.abs(ntf_z - 1) < eps**(1./(1. + order))] = 1.
Expand Down Expand Up @@ -154,7 +154,7 @@ def realizeNTF_ct(ntf, form='FB', tdac=(0, 1), ordering=None, bp=None,
bp = np.zeros((order2,))
if not multi_timing:
# Need direct terms for every interval of memory in the DAC
n_direct = np.ceil(tdac[1]) - 1
n_direct = int(np.ceil(tdac[1])) - 1
if tdac[0] > 0 and tdac[0] < 1 and tdac[1] > 1 and tdac[1] < 2:
n_extra = n_direct - 1 # tdac pulse spans a sample point
else:
Expand Down Expand Up @@ -234,7 +234,7 @@ def realizeNTF_ct(ntf, form='FB', tdac=(0, 1), ordering=None, bp=None,
else:
raise ValueError('Sorry, no code for form "%s".', form)

n_imp = np.ceil(2*order + np.max(tdac2[:, 1]) + 1)
n_imp = int(np.ceil(2*order + np.max(tdac2[:, 1]) + 1))
if method == 'LOOP':
# Sample the L1 impulse response
y = impL1(ntf, n_imp)
Expand Down
6 changes: 3 additions & 3 deletions deltasigma/_scaleABCD.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from ._simulateQDSM import simulateQDSM


def scaleABCD(ABCD, nlev=2, f=0, xlim=1, ymax=None, umax=None, N_sim=1e5, N0=10):
def scaleABCD(ABCD, nlev=2, f=0, xlim=1, ymax=None, umax=None, N_sim=100_000, N0=10):
"""Scale the loop filter of a general delta-sigma modulator for dynamic range.

The ABCD matrix is scaled so that the state maxima are less than the
Expand Down Expand Up @@ -96,10 +96,10 @@ def scaleABCD(ABCD, nlev=2, f=0, xlim=1, ymax=None, umax=None, N_sim=1e5, N0=10)
# First get a rough estimate of umax.
ulist = np.arange(0.1, 1.1, 0.1)*(nlev - 1)
umax = nlev - 1
N = 1000.0
N = 1000
u0 = np.hstack((np.exp(2j*np.pi*f*np.arange(-N0, 0))*raised_cosine, \
np.exp(2j*np.pi*f*np.arange(0, N)))) \
+ 0.01*np.dot(np.array([[1, 1j]]), npr.randn(2, N + N0))
+ 0.01*np.dot(np.array([[1, 1j]]), npr.randn(2, N + N0))
if not quadrature:
u0 = np.real(u0)
for u in ulist:
Expand Down
4 changes: 2 additions & 2 deletions deltasigma/_simulateQDSM.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
from scipy.signal import freqz, tf2zpk

from ._config import _debug, setup_args
from ._ds_quantize import ds_quantize
from ._evalTF import evalTF
from ._partitionABCD import partitionABCD
from ._utils import carray, diagonal_indices, _is_zpk, _is_A_B_C_D, _is_num_den
Expand All @@ -38,13 +37,14 @@
try:
import pyximport
pyximport.install(setup_args=setup_args, inplace=True)
from ._simulateQDSM_core import simulateQDSM_core
except ImportError as e:
if _debug:
print(str(e))
# we'll just fall back to the Python version
pass

from ._simulateQDSM_core import simulateQDSM_core


def simulateQDSM(u, arg2, nlev=2, x0=None):
"""Simulate a quadrature delta-sigma modulator.
Expand Down
3 changes: 2 additions & 1 deletion deltasigma/_simulateQDSM_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
from __future__ import division, print_function

import numpy as np

from ._ds_quantize import ds_quantize


def simulateQDSM_core(u, A, B, C, D1, order, nlev, nq, x0):
N = u.shape[1]
v = np.zeros(shape=(nq, N), dtype='complex128')
Expand All @@ -40,6 +40,7 @@ def simulateQDSM_core(u, A, B, C, D1, order, nlev, nq, x0):
xmax = np.max((np.abs(x0), xmax), axis=0)
return v, xn, xmax, y


def ds_qquantize(y, n):
"""Quadrature quantization
"""
Expand Down
8 changes: 4 additions & 4 deletions deltasigma/_simulateSNR.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,25 +224,25 @@ def simulateSNR(arg1, osr, amp=None, f0=0, nlev=2, f=None, k=13,
np.arange(Ntransient/2)))
if not quadrature:
tone = M*np.sin(2*np.pi*F/N*np.arange(N + Ntransient))
tone[:Ntransient/2] = tone[:Ntransient/2] * soft_start
tone[:Ntransient//2] = tone[:Ntransient//2] * soft_start
else:
tone = M*np.exp(2j*np.pi*F/N * np.arange(N + Ntransient))
tone[:Ntransient/2] = tone[:Ntransient/2] * soft_start
tone[:Ntransient//2] = tone[:Ntransient//2] * soft_start
if not quadrature_ntf:
tone = tone.reshape((1, -1))
tone = np.vstack((np.real(tone), np.imag(tone)))
# create a Hann window
window = 0.5*(1 - np.cos(2*np.pi*np.arange(N)/N))
if f0 == 0:
# Exclude DC and its adjacent bin
inBandBins = int(N/2) + np.arange(3,
inBandBins = int(N//2) + np.arange(3,
np.round(N/osr_mult/osr) + 1,
dtype=np.int32)
F = F - 2
else:
f1 = np.round(N*(f0 - 1./osr_mult/osr))
# Should exclude DC
inBandBins = int(N/2) + np.arange(f1,
inBandBins = int(N//2) + np.arange(f1,
np.round(N*(f0 + 1./osr_mult/osr)) + 1,
dtype=np.int32)
F = F - f1 + 1
Expand Down
5 changes: 3 additions & 2 deletions deltasigma/_synthesizeNTF0.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
optimizing the result.
"""

from __future__ import division
from warnings import warn

import numpy as np
Expand Down Expand Up @@ -111,7 +112,7 @@ def synthesizeNTF0(order, osr, opt, H_inf, f0):
# Determine the zeros.
if f0 != 0:
# Bandpass design-- halve the order temporarily.
order = order/2
order = order//2
dw = np.pi/(2*osr)
else:
dw = np.pi/osr
Expand Down Expand Up @@ -192,7 +193,7 @@ def synthesizeNTF0(order, osr, opt, H_inf, f0):
mb2 = c2pif0 + e2*np.exp(1j*w)
p = mb2 - np.sqrt(mb2**2-1)
# Reflect poles to be inside the unit circle
out = abs(p)>1
out = abs(p) > 1
p[out] = 1/p[out]
# The following is not exactly what delsig does.
p = cplxpair(p)
Expand Down
17 changes: 9 additions & 8 deletions deltasigma/_synthesizeNTF1.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def synthesizeNTF1(order, osr, opt, H_inf, f0):
# Determine the zeros.
if f0 != 0:
# Bandpass design-- halve the order temporarily.
order = order/2
order = order//2
dw = np.pi/(2*osr)
else:
dw = np.pi/osr
Expand All @@ -74,7 +74,7 @@ def synthesizeNTF1(order, osr, opt, H_inf, f0):
# Bandpass design-- shift and replicate the zeros.
order = order*2
z = np.sort(z) + 2*np.pi*f0
z = np.vstack((z,-z)).transpose().flatten()
z = np.vstack((z, -z)).transpose().flatten()
z = np.exp(1j*z)
else:
z = opt
Expand Down Expand Up @@ -143,7 +143,7 @@ def synthesizeNTF1(order, osr, opt, H_inf, f0):
warn('Danger! Iteration limit exceeded.')
else:
# Bandpass design
x = 0.3**(order/2-1) # starting guess (not very good for f0~0)
x = 0.3**(order//2-1) # starting guess (not very good for f0~0)
if f0 > 0.25:
z_inf = 1.
else:
Expand Down Expand Up @@ -196,16 +196,17 @@ def synthesizeNTF1(order, osr, opt, H_inf, f0):
# options = optimset(options,'Display','off');
# %options = optimset(options,'Display','iter');
opt_result = fmin_l_bfgs_b(ds_synNTFobj1, x0, args=(p, osr, f0),
approx_grad=True, bounds=list(zip(lb,ub)))
x=opt_result[0]
approx_grad=True, bounds=list(zip(lb, ub)))
x = opt_result[0]
x0 = x
z = np.exp(2j*np.pi*(f0+0.5/osr*x))
if f0 > 0:
z = padl(z, len(p)/2, np.exp(2j*np.pi*f0))
z = np.concatenate((z, z.conj()), axis=1)
z = padl(z, len(p)//2, np.exp(2j*np.pi*f0))
# z = np.concatenate((z, z.conj()), axis=1)
z = np.ravel(np.column_stack( (z, z.conj()) ))
if f0 == 0:
z = padl(z, len(p), 1)
if np.abs(np.real(evalTF((z, p, k), z_inf)) - H_inf ) < ftol:
if np.abs(np.real(evalTF((z, p, k), z_inf)) - H_inf) < ftol:
opt_iteration = 0
else:
opt_iteration = opt_iteration - 1
Expand Down
Loading