Initial Libre-FDATool GUI Version.

Developed at CERN BE-CO H&T in the week 37 of year 2013.
parents
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#
# Analysis class code is based in previous open source work:
# * mfreqz: by Matti Pastell
# * zplane: by Chris Felton
import numpy as np
from numpy import pi, log10
from scipy import signal
from matplotlib import pyplot as plt
from matplotlib import mlab
from matplotlib import patches
from matplotlib.figure import Figure
from matplotlib import rcParams
class Analysis():
'''This class include tools for LTI filter analysis,
sporting math models for studying coefficient quantization effects.
Note (limited to FIR filters)
'''
def analyze_zero_pole(self, c, p, q, filename=None):
'''Plot graphical zero/pole analysis in Z-plane:
* c: FIR filter coefficients array.
* filename: optional file for storing plot and not showing it.
'''
print('Plotting Z Analysis...')
# Quantize coefficients
d = np.zeros(len(c))
for ii in range(len(c)):
d[ii] = int(c[ii]*(2**(p+q-1)))
# Temporal assignation: only valid for FIR
print('Coefficients')
b1 = c
a1 = 1
print(b1)
print(np.max(b1))
b2 = d
a2 = 1
print(b2)
print(np.max(b1))
plt.figure('libre-fdatool analysis');
# get a figure/plot
ax = plt.subplot(111)
# create the unit circle
uc = patches.Circle((0,0), radius=1, fill=False,
color='black', ls='dashed')
ax.add_patch(uc)
# 1 - The coefficients are less than 1, normalize the coeficients
if np.max(b1) > 1:
kn1 = np.max(b1)
b1 = b1/float(kn1)
else:
kn1 = 1
if np.max(a1) > 1:
kd1 = np.max(a1)
a1 = a1/float(kd1)
else:
kd1 = 1
# 2 - The coefficients are less than 1, normalize the coeficients
if np.max(b2) > 1:
kn2 = np.max(b2)
b2 = b2/float(kn2)
else:
kn2 = 1
if np.max(a2) > 1:
kd2 = np.max(a2)
a2 = a2/float(kd2)
else:
kd2 = 1
# Get the poles and zeros
p1 = np.roots(a1)
z1 = np.roots(b1)
k1 = kn1/float(kd1)
p2 = np.roots(a2)
z2 = np.roots(b2)
k2 = kn2/float(kd2)
# 1 - Plot the zeros and set marker properties
tz1 = plt.plot(z1.real, z1.imag, 'bo', ms=10)
plt.setp( tz1, markersize=10.0, markeredgewidth=1.0,
markeredgecolor='b', markerfacecolor='b')
# 1 - Plot the poles and set marker properties
tp1 = plt.plot(p1.real, p1.imag, 'bx', ms=10)
plt.setp( tp1, markersize=12.0, markeredgewidth=3.0,
markeredgecolor='b', markerfacecolor='b')
# 2 - Plot the zeros and set marker properties
tz2 = plt.plot(z2.real, z2.imag, 'ro', ms=10)
plt.setp( tz2, markersize=10.0, markeredgewidth=1.0,
markeredgecolor='r', markerfacecolor='r')
# 2 - Plot the poles and set marker properties
tp2 = plt.plot(p2.real, p2.imag, 'rx', ms=10)
plt.setp( tp2, markersize=12.0, markeredgewidth=3.0,
markeredgecolor='r', markerfacecolor='r')
# set axis
plt.axis('scaled')
plt.ylabel('Imaginary Component')
plt.xlabel('Real Component')
plt.title(r'Zero-Pole Diagram (Blue=Float; Red=Int)')
plt.grid(True)
# show or store plot
return plt
def analyze_frequency_response(self, c, p, q, filename=None):
'''Plot graphical Magnitude/Phase analysis in frequency domain:
* c: FIR filter coefficients array.
* filename: optional file for storing plot and not showing it.
'''
# Quantize coefficients
d = np.zeros(len(c))
for ii in range(len(c)):
d[ii] = int(c[ii]*(2**(p+q-1)))
d = d/(2**(p+q-1))
print(c)
print(d)
wc,hc = signal.freqz(c,1)
hc_dB = 20 * log10 (abs(hc))
wd,hd = signal.freqz(d,1)
hd_dB = 20 * log10 (abs(hd))
plt.figure('libre-fdatool analysis');
plt.subplot(211)
plt.plot(wc/max(wc),hc_dB,'b')
plt.plot(wd/max(wd),hd_dB,'r')
plt.ylim(-150, 5)
plt.ylabel('Magnitude (dB)')
plt.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
plt.title(r'Magnitude response (Blue=Float; Red=Int)')
plt.grid(True)
plt.subplot(212)
hc_Phase = np.unwrap(np.arctan2(np.imag(hc),np.real(hc)))
hd_Phase = np.unwrap(np.arctan2(np.imag(hd),np.real(hd)))
plt.plot(wc/max(wc),hc_Phase,'b')
plt.plot(wd/max(wd),hd_Phase,'r')
plt.ylabel('Phase (radians)')
plt.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
plt.title(r'Phase response (Blue=Float; Red=Int)')
plt.grid(True)
plt.subplots_adjust(hspace=0.5)
return plt
This source diff could not be displayed because it is too large. You can view the blob instead.
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#
import numpy as np
from numpy import pi, log10
from scipy import signal
from matplotlib import pyplot as plt
from matplotlib import mlab
class control:
'''This class acts as control interface for filter parameters,
such as structure realization, fixed-point approximation...
Note (limited to FIR filters)
'''
def __init__(self):
'''This method provides initial filter parameters,
executing each set command with default values when
a new filter object is intantiated.
'''
self.setBus()
self.setScaling()
self.setStructure()
self.setModel()
self.setTrace()
self.setWorkspace()
self.setToolchain()
def setBus(self, busX=[1,15], busY=[1,15], busC=[1,15]):
'''assign the different bus width:
The value is given as a pair of natural numbers [p,q]:
- p is the number of bits representing the integer part.
- q is the number of bits representing the fractional part
There are three different configurable buses:
* busX: Input bit width
* busY: Output bit width
* busC: Coefficient bit width
'''
self.busX = busX
self.busY = busY
self.busC = busC
def setScaling(self, scalingX=16, scalingC=16):
'''assign the different FP scaling factor:
* scalingX: Input FP scaling factor (power of two exponent)
* scalingC: Coefficient FP scaling factor (power of two exponent)
'''
self.scalingX = scalingX
self.scalingC = scalingC
def setStructure(self, structure='firfilt'):
'''assign filter structure or realization.
Availability depends on python-to-HDL toolchain selection.
TBD: only "firfilt" structure is available
Future structures are type I/II direct forms, transposed...
'''
self.structure = structure
def setTrace(self, trace=False):
'''assign activation state for VCD file tracer.
If true, a *.vcd file will be generated by simulation process.
This file can be analyzed with third party tools such as GTKWave.
'''
self.trace = trace
def setModel(self, model='myhdl'):
'''assign HDL model, this is, the languaje for the toolchain.
When not selected the native/default value,
it relies on languaje conversion cogeneration & Icarus cosimulation.
For myhdl toolchain, valid values are [myhdl, verilog, vhdl, vhdl2]
TBD: this mechanism still has to be adapted for toolchain selection
and including migen an other tools (maybe GHDL for cosimulation).
'''
self.model = model
def setWorkspace(self, workspace='.'):
'''assign workspace folder for filter design and analysis.
By default, the path is the one where the librefdatool is called.
In this path, output files will be generated:
* VHDL, Verilog converted files
* VCD simulation files
'''
self.workspace = workspace
def setToolchain(self, toolchain='myhdl'):
'''Choose python-to-HDL toolchain.
By default, MyHDL is the toolchain in use.
TBD: migen toolchain will be developed in the near future
'''
self.toolchain = toolchain
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#
import sys
import os
from simcore import simcore
class core:
'''This class provides the principal librefdatool methods,
including running signal filtering with HDL models.
TBD: limited to FIR filter simulation
'''
def librefilter(self, b, a, x):
'''This method provides filter hardware simulation,
using a HDL description & a simulation engine
parametrized with the device control values.
* c: FIR filter coefficients array.
* x: Input signal array.
* return: simulated output signal
NOTE: the filter behaviour is tuned to match with:
scipy.signal.lfilter
(the purpose is direct comparision of outputs)
'''
# Save path and jump to workspace (TBD: if exists!!)
self.savedPath = os.getcwd()
os.chdir(self.workspace)
runner = simcore();
response = runner.simfilter(b, a, x,
self.structure, self.model, self.trace,
self.busX, self.busY, self.busC,
self.scalingX, self.scalingC)
# Return from workspace folder
os.chdir(self.savedPath)
return response
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#
# LibreFDATool Libraries
from core import *
from analysis import *
from control import *
class device(
control,
core,
Analysis):
'''This class instantiate a librefdatool filter device object.
A device represents an HDL model that can be widely parametrized
and used in python signal processing analysis and simulation.
The device class act as a main wrapper that includes function subclasses
TBD: only FIR filter is supported. General LTI system is in development.
'''
pass
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#
import warnings
import numpy as np
from numpy import pi, log10
from scipy import signal
from matplotlib import pyplot as plt
from matplotlib import mlab
import sys, os, random
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure
from scope import *
class Filter():
'''This class instantiate a librefdatool signal generator object.
This can be used for generating configurable signals in an easy way.
The generated signals can be directly feeded to devices or scopes
TBD: almost all!! Noise, DC, correct configuration...
'''
# Declare signals that will be sended to other classes
filterUpdatedSignal = pyqtSignal()
def __init__(self):
self.a = np.ones[1]
self.b = np.ones[1]
def calculate_filter_coefficients(self):
'''This method calculate the different filter coefficients as a
funtion of the filter parameters
'''
filterMethod = str(self.comboResponseType.currentText())
if filterMethod == 'FIR 1':
# Get filter parameters
numtaps = int(self.textNumtaps.text())
# TODO: Handle Value error exception in np.fromstring
cutoff = np.fromstring(str(self.textCutoff.text()), sep=',')
if cutoff[0] == 0:
cutoff[0] = 0.00000001
if cutoff[len(cutoff)-1] == 1:
cutoff[len(cutoff)-1] = 0.99999999
window = str(self.comboFIRWindow.currentText())
if window == 'kaiser':
if str(self.textWidth.text()) == None:
width = str(self.textWidth.text())
else:
width = float(self.textWidth.text())
else:
width = None
pass_zero = bool(self.cbPassZero.isChecked())
scale = bool(self.cbScale.isChecked())
# Denominator is [1]
a = np.ones(1)
# Calculate Numerator
b = signal.fir_filter_design.firwin(numtaps, cutoff, width = width,
window = window,
pass_zero = pass_zero, scale = scale)
elif filterMethod == 'FIR 2':
# Get filter parameters
# TODO: handle raise ValueError from Numpy!!
# The values in freq must be nondecreasing.
# A value can be repeated once to implement a discontinuity.
numtaps = int(self.textNumtaps.text())
freq = np.fromstring(str(self.textFreq.text()), sep=',')
# The first value in freq must be 0, and the last value must be nyq.
if freq[0] != 0:
tempFreq = np.zeros(len(freq)+1)
for ii in range(len(freq)):
tempFreq[ii+1] = freq[ii]
freq = tempFreq
if freq[len(freq)-1] != 1:
tempFreq = np.ones(len(freq)+1)
for ii in range(len(freq)):
tempFreq[ii] = freq[ii]
freq = tempFreq
# TODO: handle raise ValueError from Numpy!!
# gain: The filter gains at the frequency sampling points.
# See notes in (ValueError messages raised) --> dump console to status bar??
# http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.firwin2.html#scipy.signal.firwin2
gain = np.fromstring(str(self.textGain.text()), sep=',')
window = str(self.comboFIRWindow.currentText())
antisymmetric = bool(self.cbAntisymmetric.isChecked())
# Denominator is [1]
a = np.ones(1)
# Calculate Numerator
b = signal.fir_filter_design.firwin2(numtaps, freq, gain,
window = window,
antisymmetric = antisymmetric)
elif filterMethod == 'IIR 1':
# Get the filter parameters
wp = float(self.textWp.text())
ws = float(self.textWs.text())
gpass = float(self.textGpass.text())
gstop = float(self.textGstop.text())
ftype = str(self.comboIIRMethod.currentText())
# Calculate coefficients
b, a = signal.filter_design.iirdesign(wp, ws, gpass, gstop,
ftype = ftype)
elif filterMethod == 'IIR 2':
# Get the filter parameters
N = int(self.textOrder.text())
# TODO: we need to handle the fromstring possible errors!!
Wn = np.fromstring(str(self.textWn.text()), sep=',')
btype = str(self.comboBType.currentText())
ftype = str(self.comboIIRMethod.currentText())
if ftype in {'ellip',
'cheby1',
'cheby2'}:
rp = float(self.textRp.text())
rs = float(self.textRs.text())
else:
rp = None
rs = None
# Calculate coefficients
b, a = signal.filter_design.iirfilter(N, Wn,
rp = rp, rs = rs,
btype = btype,
ftype = ftype)
else :
print('Not recognized filter description method')
a = np.ones(1)
b = np.ones(1)
return b, a
def update_parameter_set(self):
'''This method hide and show the appropriated filter parameters
as a function of the filter description method that has been selected
'''
filterMethod = str(self.comboResponseType.currentText())
if filterMethod == 'FIR 1':
flagFIRWindow = True
flagNumtaps = True
flagCutoff = True
if str(self.comboFIRWindow.currentText()) == 'kaiser':
flagWidth = True
else:
flagWidth = False
flagPassZero = True
flagScale = True
flagFrequency = False
flagGain = False
flagAntisymmetric = False
flagIIRMethod = False
flagWp = False
flagWs = False
flagGpass = False
flagGstop = False
flagOrder = False
flagOrder = False
flagWn = False
flagRp = False
flagRs = False
flagBType = False
# Pass Zero special requirement
if int(self.textNumtaps.text())%2 == 0:
# Numtaps is even, Pass Zero must be True
self.cbPassZero.setChecked(True)
self.cbPassZero.setDisabled(True)
else:
# Numtaps is odd, Pass Zero can be False
self.cbPassZero.setEnabled(True)
elif filterMethod == 'FIR 2':
flagFIRWindow = True
flagNumtaps = True
flagCutoff = False
flagWidth = False
flagPassZero = False
flagScale = False
flagFrequency = True
flagGain = True
flagAntisymmetric = True
flagIIRMethod = False
flagWp = False
flagWs = False
flagGpass = False
flagGstop = False
flagOrder = False
flagOrder = False
flagWn = False
flagRp = False
flagRs = False
flagBType = False
elif filterMethod == 'IIR 1':
flagFIRWindow = False
flagNumtaps = False
flagCutoff = False
flagWidth =False
flagPassZero = False
flagScale = False
flagFrequency = False
flagGain = False
flagAntisymmetric = False
flagIIRMethod = True
flagWp = True
flagWs = True
flagGpass = True
flagGstop = True
flagOrder = False
flagOrder = False
flagWn = False
flagRp = False
flagRs = False
flagBType = False
elif filterMethod == 'IIR 2':
flagFIRWindow = False
flagNumtaps = False
flagCutoff = False
flagWidth = False
flagPassZero = False
flagScale = False
flagFrequency = False
flagGain = False
flagAntisymmetric = False
flagIIRMethod = True
flagWp = False
flagWs = False
flagGpass = False
flagGstop = False
flagOrder = True
flagOrder = True
flagWn = True
if str(self.comboIIRMethod.currentText()) in {'ellip',
'cheby1',
'cheby2'}:
flagRp = True
flagRs = True
else:
flagRp = False
flagRs = False
flagBType = True
else :
print('Not recognized filter description method')
# TODO: this is ugly, should be compacted in a cleaner structure!!
self.labelFIRWindow.setVisible(flagFIRWindow)
self.comboFIRWindow.setVisible(flagFIRWindow)
self.labelNumtaps.setVisible(flagNumtaps)
self.textNumtaps.setVisible(flagNumtaps)
self.labelCutoff.setVisible(flagCutoff)
self.textCutoff.setVisible(flagCutoff)
# If Kaiser is selected!!
self.labelWidth.setVisible(flagWidth)
self.textWidth.setVisible(flagWidth)
self.cbPassZero.setVisible(flagPassZero)
self.cbScale.setVisible(flagScale)
self.labelFreq.setVisible(flagFrequency)
self.textFreq.setVisible(flagFrequency)
self.labelGain.setVisible(flagGain)
self.textGain.setVisible(flagGain)
self.cbAntisymmetric.setVisible(flagAntisymmetric)
self.labelIIRMethod.setVisible(flagIIRMethod)
self.comboIIRMethod.setVisible(flagIIRMethod)
self.labelWp.setVisible(flagWp)
self.textWp.setVisible(flagWp)
self.labelWs.setVisible(flagWs)
self.textWs.setVisible(flagWs)
self.labelGpass.setVisible(flagGpass)
self.textGpass.setVisible(flagGpass)
self.labelGstop.setVisible(flagGstop)
self.textGstop.setVisible(flagGstop)
self.labelOrder.setVisible(flagOrder)
self.textOrder.setVisible(flagOrder)
self.labelWn.setVisible(flagWn)
self.textWn.setVisible(flagWn)
self.labelRp.setVisible(flagRp)
self.textRp.setVisible(flagRp)
self.labelRs.setVisible(flagRs)
self.textRs.setVisible(flagRs)
self.labelBType.setVisible(flagBType)
self.comboBType.setVisible(flagBType)
def on_parameter_change(self):
""" Execute when a filter parameter has changed
"""
self.pbUpdateFilter.setText('Update filter parameters')
self.pbUpdateFilter.setDisabled(False)
self.pbUpdateFilter.setStyleSheet('QPushButton {background-color: #FF0000; color: #FFFFFF}')
def on_filter_draw(self):
""" Redraws the figure
"""
# Get the coefficient bus
coefP = int(self.spinBoxCoefficientP.value())
coefQ = int(self.spinBoxCoefficientQ.value())
# TODO: if divide by zero or other errors in plotting,
# ask for increasing the filter resolution!!
if self.comboAnalysis.currentText() == 'Magnitude / Phase':
successFlag, logMessage = analyze_frequency_response(
self.figFilter,
self.b, self.a,
coefP, coefQ,
self.cbGridFilter.isChecked())
elif self.comboAnalysis.currentText() == 'Pole / Zero':
successFlag, logMessage = analyze_pole_zero(
self.figFilter,
self.b, self.a,
coefP, coefQ,
self.cbGridFilter.isChecked())
else:
successFlag, logMessage = analyze_pole_zero(
self.figFilter,
self.b, self.a,
coefP, coefQ,
self.cbGridFilter.isChecked())
self.canvasFilter.draw()
if successFlag:
print('scope updated')
else:
QMessageBox.warning(self, 'Error on filter plotting',
'TIP: increase coefficient bus width\n'
"%s" % logMessage, QMessageBox.Ok)
def on_filter_update(self):
""" Update the filter
"""
# Get the coefficients
warningMessage = ''
warnings.simplefilter('error')
try:
self.b, self.a = self.calculate_filter_coefficients()
except ValueError, exVE:
warningMessage = '%s' % exVE
except ZeroDivisionError, exZDE:
warningMessage = '%s' % exZDE
except RuntimeWarning, exRW:
warningMessage = '%s' % exRW
except signal.BadCoefficients, exBC:
warningMessage = '%s' % exBC
if warningMessage != '':
QMessageBox.warning(self, 'Invalid Filter Parameters',
"%s" % warningMessage, QMessageBox.Ok)
else:
# Change pushbutton state
self.pbUpdateFilter.setText('Filter parameters verified')
self.pbUpdateFilter.setDisabled(True)
self.pbUpdateFilter.setStyleSheet('QPushButton {background-color: #00FF00; color: #FFFFFF}')
self.on_filter_draw()
self.filterUpdatedSignal.emit()
def create_filter_layout(self):
# Create the mpl Figure and FigCanvas objects.
# 5x4 inches, 100 dots-per-inch
#
#self.dpi = 100
#self.figFilter = Figure((5.0, 4.0), dpi=self.dpi)
self.figFilter = Figure()
self.canvasFilter = FigureCanvas(self.figFilter)
self.canvasFilter.setParent(self.main_frame)
# Since we have only one plot, we can use add_axes2
# instead of add_subplot, but then the subplot
# configuration tool in the navigation toolbar wouldn't
# work.
#
#self.axes2 = self.fig.add_subplot(111)
# Bind the 'pick' event for clicking on one of the bars
#
self.canvasFilter.mpl_connect('pick_event', self.on_pick)
# Create the navigation toolbar, tied to the canvas
#
self.mpl_toolbar_filter = NavigationToolbar(self.canvasFilter, self.main_frame)
# Other GUI controls
#
self.pbUpdateFilter = QPushButton('Update Filter')
self.connect(self.pbUpdateFilter, SIGNAL('clicked()'), self.on_filter_update)
self.cbGridFilter = QCheckBox("Show &Grid")
self.cbGridFilter.setChecked(True)
self.connect(self.cbGridFilter, SIGNAL('stateChanged(int)'), self.on_filter_draw)
self.cbHideFilterConfig = QCheckBox("Hide Config")
self.cbHideFilterConfig.setChecked(False)
self.connect(self.cbHideFilterConfig, SIGNAL('stateChanged(int)'), self.on_filter_config_hide)
labelAnalysis = QLabel('Analysis:')
self.comboAnalysis = QComboBox()
self.comboAnalysis.addItem("Magnitude / Phase")
self.comboAnalysis.addItem("Pole / Zero")
self.comboAnalysis.setEditable(True)
self.comboAnalysis.lineEdit().setReadOnly(True)
self.comboAnalysis.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboAnalysis.count()):
self.comboAnalysis.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
self.connect(self.comboAnalysis, SIGNAL('currentIndexChanged(int)'), self.on_filter_draw)
labelFilterStructure = QLabel('Structure:')
self.comboFilterStructure = QComboBox()
self.comboFilterStructure.addItem("Direct Form I Transposed")
self.comboFilterStructure.addItem("Direct Form II Transposed")
self.comboFilterStructure.addItem("Direct Form I")
self.comboFilterStructure.addItem("Parallel")
self.comboFilterStructure.addItem("Cascade")
self.comboFilterStructure.addItem("Direct Form II")
self.comboFilterStructure.setEditable(True)
self.comboFilterStructure.lineEdit().setReadOnly(True)
self.comboFilterStructure.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboFilterStructure.count()):
self.comboFilterStructure.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
#self.connect(self.comboFilterStructure, SIGNAL('currentIndexChanged(int)'), self.on_parameter_change)
# TODO: the connected method is still provisional, it forces to DF I Transposed
self.connect(self.comboFilterStructure, SIGNAL('currentIndexChanged(int)'), self.on_structure_change)
labelFilterOverflow = QLabel('Overflow Control:')
self.comboFilterOverflow = QComboBox()
self.comboFilterOverflow.addItem("None")
self.comboFilterOverflow.addItem("Truncate")
self.comboFilterOverflow.addItem("Round")
self.comboFilterOverflow.setEditable(True)
self.comboFilterOverflow.lineEdit().setReadOnly(True)
self.comboFilterOverflow.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboFilterOverflow.count()):
self.comboFilterOverflow.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
#self.connect(self.comboFilterStructure, SIGNAL('currentIndexChanged(int)'), self.on_parameter_change)
# TODO: the connected method is still provisional, it forces to DF I Transposed
self.connect(self.comboFilterStructure, SIGNAL('currentIndexChanged(int)'), self.on_overflow_change)
labelResponseType = QLabel('Filtering Method:')
self.comboResponseType = QComboBox()
self.comboResponseType.addItem("FIR 1") # scipy.signal.firwin
self.comboResponseType.addItem("FIR 2") # scipy.signal.firwin2
self.comboResponseType.addItem("IIR 1") # scipy.signal.iirdesign
# TODO: this IIR 2 filter causes undetected problems!! We disable this
self.comboResponseType.addItem("IIR 2") # scipy.signal.iirfilter
self.comboResponseType.setEditable(True)
self.comboResponseType.lineEdit().setReadOnly(True)
self.comboResponseType.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboResponseType.count()):
self.comboResponseType.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
self.connect(self.comboResponseType, SIGNAL('currentIndexChanged(int)'), self.update_parameter_set)
self.connect(self.comboResponseType, SIGNAL('currentIndexChanged(int)'), self.on_parameter_change)
# The Elements for filter configuration are:
# window: FIR 1, FIR 2
self.labelFIRWindow = QLabel('FIR Window:')
self.comboFIRWindow = QComboBox()
self.comboFIRWindow.addItem("boxcar")
self.comboFIRWindow.addItem("triang")
self.comboFIRWindow.addItem("blackman")
self.comboFIRWindow.addItem("hamming")
self.comboFIRWindow.addItem("hann")
self.comboFIRWindow.addItem("bartlett")
self.comboFIRWindow.addItem("flattop")
self.comboFIRWindow.addItem("parzen")
self.comboFIRWindow.addItem("bohman")
self.comboFIRWindow.addItem("blackmanharris")
self.comboFIRWindow.addItem("nuttall")
self.comboFIRWindow.addItem("barthann")
self.comboFIRWindow.addItem("kaiser") # needs beta
self.comboFIRWindow.addItem("gaussian") # needs std
self.comboFIRWindow.addItem("general_gaussian") # needs power, width
self.comboFIRWindow.addItem("slepian") # needs width
self.comboFIRWindow.addItem("chebwin") # needs attenuation
self.comboFIRWindow.setCurrentIndex(0)
self.comboFIRWindow.setEditable(True)
self.comboFIRWindow.lineEdit().setReadOnly(True)
self.comboFIRWindow.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboFIRWindow.count()):
self.comboFIRWindow.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
self.connect(self.comboFIRWindow, SIGNAL('currentIndexChanged(int)'), self.update_parameter_set)
self.connect(self.comboFIRWindow, SIGNAL('currentIndexChanged(int)'), self.on_parameter_change)
# numtaps: FIR 1, FIR 2
self.labelNumtaps = QLabel('Numtaps:')
self.textNumtaps = QLineEdit()
validatorNumtaps = QIntValidator(1,1000)
self.textNumtaps.setValidator(validatorNumtaps)
self.textNumtaps.setText('100')
self.textNumtaps.setAlignment(Qt.AlignRight)
# Pass_Zero must always be active in 'FIR 1' if numtaps is an even value!!
self.connect(self.textNumtaps, SIGNAL('editingFinished()'), self.update_parameter_set)
self.connect(self.textNumtaps, SIGNAL('editingFinished()'), self.on_parameter_change)
# cutoff: FIR 1
#This could be an array!!
# TODO: we need a validator!!!
self.labelCutoff = QLabel('Cutoff:')
self.textCutoff = QLineEdit()
self.textCutoff.setText('0.5')
self.textCutoff.setAlignment(Qt.AlignRight)
self.connect(self.textCutoff, SIGNAL('editingFinished()'), self.on_parameter_change)
self.textCutoff.setToolTip(
'An array of cutoff frequencies (that is, band edges).\n'
'The frequencies in cutoff should be positive and monotonically increasing between 0 and 1.\n'
'The values 0 and nyq must not be included in cutoff.\n')
# width: FIR 1 --> only for Kaiser windows!! 'none' value in toher case
self.labelWidth = QLabel('Width:')
self.textWidth = QLineEdit()
# QDoubleValidator.__init__ (self, float bottom, float top, int decimals)
validatorWidth = QDoubleValidator(0.00000001, 0.99999999, 8)
self.textWidth.setValidator(validatorWidth)
self.textWidth.setText('0.5')
self.textWidth.setAlignment(Qt.AlignRight)
self.connect(self.textWidth, SIGNAL('editingFinished()'), self.on_parameter_change)
# pass_zero: FIR 1
self.cbPassZero = QCheckBox("Pass Zero")
self.cbPassZero.setChecked(True)
self.connect(self.cbPassZero, SIGNAL('stateChanged(int)'), self.on_parameter_change)
# scale: FIR 1
self.cbScale = QCheckBox("Scale")
self.cbScale.setChecked(True)
self.connect(self.cbScale, SIGNAL('stateChanged(int)'), self.on_parameter_change)
# freq: FIR 2
#TODO: We need a validator!! The first value in freq must be 0,
# and the last value must be nyq.
'''
The frequency sampling points.
Typically 0.0 to 1.0 with 1.0 being Nyquist.
The Nyquist frequency can be redefined with the argument nyq.
The values in freq must be nondecreasing.
A value can be repeated once to implement a discontinuity.
The first value in freq must be 0, and the last value must be nyq
'''
self.labelFreq = QLabel('Frequency:')
self.textFreq = QLineEdit()
self.textFreq.setText('0, 0.5, 1')
self.textFreq.setAlignment(Qt.AlignRight)
self.connect(self.textFreq, SIGNAL('editingFinished()'), self.on_parameter_change)
# gain: FIR 2
#TODO: We need a specific validator!!
self.labelGain = QLabel('Gain:')
self.textGain = QLineEdit()
self.textGain.setText('1, 0.5, 0')
self.textGain.setAlignment(Qt.AlignRight)
self.connect(self.textGain, SIGNAL('editingFinished()'), self.on_parameter_change)
# scale: FIR 2
self.cbAntisymmetric = QCheckBox("Antisymmetric")
self.cbAntisymmetric.setChecked(False)
self.connect(self.cbAntisymmetric, SIGNAL('stateChanged(int)'), self.on_parameter_change)
# ftype: IIR1, IIR2
self.labelIIRMethod = QLabel('Filter Type:')
self.comboIIRMethod = QComboBox()
self.comboIIRMethod.addItem("ellip")
self.comboIIRMethod.addItem("butter")
self.comboIIRMethod.addItem("cheby1")
self.comboIIRMethod.addItem("cheby2")
self.comboIIRMethod.addItem("bessel")
self.comboIIRMethod.setEditable(True)
self.comboIIRMethod.lineEdit().setReadOnly(True)
self.comboIIRMethod.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboIIRMethod.count()):
self.comboIIRMethod.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
self.connect(self.comboIIRMethod, SIGNAL('currentIndexChanged(int)'), self.update_parameter_set)
self.connect(self.comboIIRMethod, SIGNAL('currentIndexChanged(int)'), self.on_parameter_change)
# wp: IIR 1
self.labelWp = QLabel('wp:')
self.textWp = QLineEdit()
validatorWp = QDoubleValidator(0, 1, 8)
self.textWp.setValidator(validatorWp)
self.textWp.setText('0.1')
self.textWp.setAlignment(Qt.AlignRight)
self.connect(self.textWp, SIGNAL('editingFinished()'), self.on_parameter_change)
# ws: IIR 1
self.labelWs = QLabel('ws:')
self.textWs = QLineEdit()
validatorWs = QDoubleValidator(0, 1, 8)
self.textWs.setValidator(validatorWs)
self.textWs.setText('0.5')
self.textWs.setAlignment(Qt.AlignRight)
self.connect(self.textWs, SIGNAL('editingFinished()'), self.on_parameter_change)
# gpass: IIR 1
self.labelGpass = QLabel('Gpass[dB]:')
self.textGpass = QLineEdit()
validatorGpass = QDoubleValidator(-100, 100, 8)
self.textGpass.setValidator(validatorGpass)
self.textGpass.setText('1')
self.textGpass.setAlignment(Qt.AlignRight)
self.connect(self.textGpass, SIGNAL('editingFinished()'), self.on_parameter_change)
# ws: IIR 1
self.labelGstop = QLabel('Gstop[dB]:')
self.textGstop = QLineEdit()
validatorGstop = QDoubleValidator(-100, 100, 8)
self.textGstop.setValidator(validatorGstop)
self.textGstop.setText('12')
self.textGstop.setAlignment(Qt.AlignRight)
self.connect(self.textGstop, SIGNAL('editingFinished()'), self.on_parameter_change)
# N, order: IIR 2
self.labelOrder = QLabel('Order:')
self.textOrder = QLineEdit()
validatorOrder = QIntValidator(1,1000)
self.textOrder.setValidator(validatorOrder)
self.textOrder.setText('5')
self.textOrder.setAlignment(Qt.AlignRight)
self.connect(self.textOrder, SIGNAL('editingFinished()'), self.on_parameter_change)
# Wn: IIR 2
#TODO: we need a validator
self.labelWn = QLabel('Wn:')
self.textWn = QLineEdit()
self.textWn.setText('0, 0.5, 1')
self.textWn.setAlignment(Qt.AlignRight)
self.connect(self.textWn, SIGNAL('editingFinished()'), self.on_parameter_change)
# rp: IIR 2 --> only in chebyshev and elliptic
self.labelRp = QLabel('rp[dB]:')
self.textRp = QLineEdit()
validatorRp = QDoubleValidator(-100, 100, 8)
self.textRp.setValidator(validatorRp)
self.textRp.setText('0.5')
self.textRp.setAlignment(Qt.AlignRight)
self.connect(self.textRp, SIGNAL('editingFinished()'), self.on_parameter_change)
# rs: IIR 2 --> only in chebyshev and elliptic
self.labelRs = QLabel('rs[dB]:')
self.textRs = QLineEdit()
validatorRs = QDoubleValidator(-100, 100, 8)
self.textRs.setValidator(validatorRs)
self.textRs.setText('0.5')
self.textRs.setAlignment(Qt.AlignRight)
self.connect(self.textRs, SIGNAL('editingFinished()'), self.on_parameter_change)
# btype: IIR 2
self.labelBType = QLabel('Band Type:')
self.comboBType = QComboBox()
self.comboBType.addItem("bandpass")
self.comboBType.addItem("lowpass")
self.comboBType.addItem("highpass")
self.comboBType.addItem("bandstop")
self.comboBType.setEditable(True)
self.comboBType.lineEdit().setReadOnly(True)
self.comboBType.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboBType.count()):
self.comboBType.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
self.connect(self.comboBType, SIGNAL('currentIndexChanged(int)'), self.on_parameter_change)
#
# Bus Width SetUp
#
self.spinBoxCoefficientP = QSpinBox()
self.spinBoxCoefficientP.setMaximum(256)
self.spinBoxCoefficientP.setMinimum(1)
self.spinBoxCoefficientP.setValue(1)
self.connect(self.spinBoxCoefficientP, SIGNAL('valueChanged(int)'), self.on_parameter_change)
self.spinBoxCoefficientQ = QSpinBox()
self.spinBoxCoefficientQ.setMaximum(256)
self.spinBoxCoefficientQ.setMinimum(1)
self.spinBoxCoefficientQ.setValue(7)
self.connect(self.spinBoxCoefficientQ, SIGNAL('valueChanged(int)'), self.on_parameter_change)
self.spinBoxInputP = QSpinBox()
self.spinBoxInputP.setMaximum(256)
self.spinBoxInputP.setMinimum(1)
self.spinBoxInputP.setValue(1)
self.connect(self.spinBoxInputP, SIGNAL('valueChanged(int)'), self.on_parameter_change)
self.spinBoxInputQ = QSpinBox()
self.spinBoxInputQ.setMaximum(256)
self.spinBoxInputQ.setMinimum(1)
self.spinBoxInputQ.setValue(7)
self.connect(self.spinBoxInputQ, SIGNAL('valueChanged(int)'), self.on_parameter_change)
self.spinBoxOutputP = QSpinBox()
self.spinBoxOutputP.setMaximum(256)
self.spinBoxOutputP.setMinimum(1)
self.spinBoxOutputP.setValue(1)
self.connect(self.spinBoxOutputP, SIGNAL('valueChanged(int)'), self.on_parameter_change)
self.spinBoxOutputQ = QSpinBox()
self.spinBoxOutputQ.setMaximum(256)
self.spinBoxOutputQ.setMinimum(1)
self.spinBoxOutputQ.setMinimum(7)
self.connect(self.spinBoxOutputQ, SIGNAL('valueChanged(int)'), self.on_parameter_change)
#
# Layout with box sizers
#
hboxAnalysis = QHBoxLayout()
hboxAnalysis.addWidget(labelAnalysis)
hboxAnalysis.addWidget(self.comboAnalysis)
hboxAnalysis.setStretch(0,1)
hboxAnalysis.setStretch(1,1)
hboxFilterStructure = QHBoxLayout()
hboxFilterStructure.addWidget(labelFilterStructure)
hboxFilterStructure.addWidget(self.comboFilterStructure)
hboxFilterStructure.setStretch(0,1)
hboxFilterStructure.setStretch(1,1)
hboxFilterOverflow = QHBoxLayout()
hboxFilterOverflow.addWidget(labelFilterOverflow)
hboxFilterOverflow.addWidget(self.comboFilterOverflow)
hboxFilterOverflow.setStretch(0,1)
hboxFilterOverflow.setStretch(1,1)
hboxResponseType = QHBoxLayout()
hboxResponseType.addWidget(labelResponseType)
hboxResponseType.addWidget(self.comboResponseType)
hboxResponseType.setStretch(0,1)
hboxResponseType.setStretch(1,1)
hboxFIRWindow = QHBoxLayout()
hboxFIRWindow.addWidget(self.labelFIRWindow)
hboxFIRWindow.addWidget(self.comboFIRWindow)
hboxFIRWindow.setStretch(0,1)
hboxFIRWindow.setStretch(1,1)
hboxNumtaps = QHBoxLayout()
hboxNumtaps.addWidget(self.labelNumtaps)
hboxNumtaps.addWidget(self.textNumtaps)
hboxNumtaps.setStretch(0,1)
hboxNumtaps.setStretch(1,1)
hboxCutoff = QHBoxLayout()
hboxCutoff.addWidget(self.labelCutoff)
hboxCutoff.addWidget(self.textCutoff)
hboxCutoff.setStretch(0,1)
hboxCutoff.setStretch(1,1)
hboxWidth = QHBoxLayout()
hboxWidth.addWidget(self.labelWidth)
hboxWidth.addWidget(self.textWidth)
hboxWidth.setStretch(0,1)
hboxWidth.setStretch(1,1)
hboxPassZero = QHBoxLayout()
hboxPassZero.addWidget(self.cbPassZero)
hboxPassZero.setStretch(0,1)
hboxPassZero.setStretch(1,1)
hboxScale = QHBoxLayout()
hboxScale.addWidget(self.cbScale)
hboxScale.setStretch(0,1)
hboxScale.setStretch(1,1)
hboxWidth = QHBoxLayout()
hboxWidth.addWidget(self.labelWidth)
hboxWidth.addWidget(self.textWidth)
hboxWidth.setStretch(0,1)
hboxWidth.setStretch(1,1)
hboxFrequency = QHBoxLayout()
hboxFrequency.addWidget(self.labelFreq)
hboxFrequency.addWidget(self.textFreq)
hboxFrequency.setStretch(0,1)
hboxFrequency.setStretch(1,1)
hboxGain = QHBoxLayout()
hboxGain.addWidget(self.labelGain)
hboxGain.addWidget(self.textGain)
hboxGain.setStretch(0,1)
hboxGain.setStretch(1,1)
hboxAntisymmetric = QHBoxLayout()
hboxAntisymmetric.addWidget(self.cbAntisymmetric)
hboxAntisymmetric.setStretch(0,1)
hboxAntisymmetric.setStretch(1,1)
hboxIIRMethod = QHBoxLayout()
hboxIIRMethod.addWidget(self.labelIIRMethod)
hboxIIRMethod.addWidget(self.comboIIRMethod)
hboxIIRMethod.setStretch(0,1)
hboxIIRMethod.setStretch(1,1)
hboxWp = QHBoxLayout()
hboxWp.addWidget(self.labelWp)
hboxWp.addWidget(self.textWp)
hboxWp.setStretch(0,1)
hboxWp.setStretch(1,1)
hboxWs = QHBoxLayout()
hboxWs.addWidget(self.labelWs)
hboxWs.addWidget(self.textWs)
hboxWs.setStretch(0,1)
hboxWs.setStretch(1,1)
hboxGpass = QHBoxLayout()
hboxGpass.addWidget(self.labelGpass)
hboxGpass.addWidget(self.textGpass)
hboxGpass.setStretch(0,1)
hboxGpass.setStretch(1,1)
hboxGstop = QHBoxLayout()
hboxGstop.addWidget(self.labelGstop)
hboxGstop.addWidget(self.textGstop)
hboxGstop.setStretch(0,1)
hboxGstop.setStretch(1,1)
hboxOrder = QHBoxLayout()
hboxOrder.addWidget(self.labelOrder)
hboxOrder.addWidget(self.textOrder)
hboxOrder.setStretch(0,1)
hboxOrder.setStretch(1,1)
hboxWn = QHBoxLayout()
hboxWn.addWidget(self.labelWn)
hboxWn.addWidget(self.textWn)
hboxWn.setStretch(0,1)
hboxWn.setStretch(1,1)
hboxRp = QHBoxLayout()
hboxRp.addWidget(self.labelRp)
hboxRp.addWidget(self.textRp)
hboxRp.setStretch(0,1)
hboxRp.setStretch(1,1)
hboxRs = QHBoxLayout()
hboxRs.addWidget(self.labelRs)
hboxRs.addWidget(self.textRs)
hboxRs.setStretch(0,1)
hboxRs.setStretch(1,1)
hboxBType = QHBoxLayout()
hboxBType.addWidget(self.labelBType)
hboxBType.addWidget(self.comboBType)
hboxBType.setStretch(0,1)
hboxBType.setStretch(1,1)
vboxFilterParameters = QVBoxLayout()
for parameterLayout in (hboxResponseType, hboxFIRWindow,
hboxNumtaps, hboxCutoff,
hboxWidth, hboxPassZero, hboxScale,
hboxFrequency, hboxGain, hboxAntisymmetric,
hboxIIRMethod, hboxWp, hboxWs,
hboxGpass, hboxGstop, hboxOrder,
hboxWn, hboxRp, hboxRs, hboxBType):
vboxFilterParameters.addLayout(parameterLayout)
groupBoxFilterParameters = QGroupBox('Filter Parameters')
groupBoxFilterParameters.setLayout(vboxFilterParameters)
groupBoxCoefficientFP = QGroupBox('Coefficient Bus')
hboxCoefficientFP = QHBoxLayout()
hboxCoefficientFP.addWidget(QLabel('Integer:'))
hboxCoefficientFP.addWidget(self.spinBoxCoefficientP)
hboxCoefficientFP.addWidget(QLabel('Fractional:'))
hboxCoefficientFP.addWidget(self.spinBoxCoefficientQ)
groupBoxCoefficientFP.setLayout(hboxCoefficientFP)
groupBoxInputFP = QGroupBox('Input Bus')
hboxInputFP = QHBoxLayout()
hboxInputFP.addWidget(QLabel('Integer:'))
hboxInputFP.addWidget(self.spinBoxInputP)
hboxInputFP.addWidget(QLabel('Fractional:'))
hboxInputFP.addWidget(self.spinBoxInputQ)
groupBoxInputFP.setLayout(hboxInputFP)
groupBoxOutputFP = QGroupBox('Output Bus')
hboxOutputFP = QHBoxLayout()
hboxOutputFP.addWidget(QLabel('Integer:'))
hboxOutputFP.addWidget(self.spinBoxOutputP)
hboxOutputFP.addWidget(QLabel('Fractional:'))
hboxOutputFP.addWidget(self.spinBoxOutputQ)
groupBoxOutputFP.setLayout(hboxOutputFP)
vboxLeft = QVBoxLayout()
vboxLeft.addLayout(hboxFilterStructure)
vboxLeft.addLayout(hboxFilterOverflow)
vboxLeft.addWidget(groupBoxCoefficientFP)
vboxLeft.addWidget(groupBoxInputFP)
vboxLeft.addWidget(groupBoxOutputFP)
groupBoxFilterRealization = QGroupBox('Hardware Realization')
groupBoxFilterRealization.setLayout(vboxLeft)
hboxFilterControl = QHBoxLayout()
hboxFilterControl.addWidget(groupBoxFilterRealization)
hboxFilterControl.addWidget(groupBoxFilterParameters)
vboxFilterControl =QVBoxLayout()
vboxFilterControl.addWidget(self.pbUpdateFilter)
vboxFilterControl.addLayout(hboxFilterControl)
self.groupBoxFilterControl = QGroupBox('Filter Control')
self.groupBoxFilterControl.setLayout(vboxFilterControl)
self.groupBoxFilterControl.isCheckable()
hboxDisplay = QHBoxLayout()
hboxDisplay.addLayout(hboxAnalysis)
hboxDisplay.addWidget(self.cbGridFilter)
hboxDisplay.addWidget(self.cbHideFilterConfig)
vboxMain = QVBoxLayout()
vboxMain.addWidget(self.canvasFilter)
vboxMain.addWidget(self.mpl_toolbar_filter)
vboxMain.addLayout(hboxDisplay)
vboxMain.addWidget(self.groupBoxFilterControl)
# Update parameter set and then the window too!!
# the figure update is include in update parameter!!
self.update_parameter_set()
self.on_filter_update()
return vboxMain
def on_structure_change(self):
# TODO: provisional, check the structure change and force to DF1 Trans
activeStructure = str(self.comboFilterStructure.currentText())
if activeStructure == 'Direct Form I Transposed':
self.on_parameter_change()
else:
QMessageBox.information(self, 'Filter Structure',
'Sorry, but %s is not supported yet!'
% activeStructure,
QMessageBox.Ok)
self.comboFilterStructure.setCurrentIndex(0)
def on_overflow_change(self):
# TODO: provisional, check the structure change and force to DF1 Trans
activeOverflow = str(self.comboFilterOverflow.currentText())
if activeOverflow == 'None':
self.on_parameter_change()
else:
QMessageBox.information(self, 'Overflow Control',
'Sorry, but %s is not supported yet!'
% activeOverflow,
QMessageBox.Ok)
self.comboFilterOverflow.setCurrentIndex(0)
def on_filter_config_hide(self):
if self.cbHideFilterConfig.isChecked() == True:
self.groupBoxFilterControl.hide()
else:
self.groupBoxFilterControl.show()
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#
import numpy as np
from numpy import pi, log10
from scipy import signal
from matplotlib import pyplot as plt
from matplotlib import mlab
import sys, os, random
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure
# NOTE: there are some 0.94 ~ 0.98 factors: these are scaling the input to <1
class Generator:
'''This class instantiate a librefdatool signal generator object.
This can be used for generating configurable signals in an easy way.
The generated signals can be directly feeded to devices or scopes
TBD: almost all!! Noise, DC, correct configuration...
'''
# Declare signals that will be sended to other classes
stimulusUpdatedSignal = pyqtSignal()
def __init__(self):
self.x = np.ones(1)
self.on_stimulus_draw()
def waveform(self):
'''This method returns a parametrized waveform signal:
* waveform: assign signal geometry, with valid values:
[doppler, chirp, sawtooth, square, gausspulse, sweep]
* length: number of samples of the generated signal array
* return: numeric array with the values of the generated signal
TBD: the waveform must be parametrizable. Most templates doesnt work.
Duration is in seconds
Is Delay in samples or in seconds?
TBD: we have to deal with discrete frequencies!!!!
Forget the time, only samples and discrete frequencies should be involved!!!
'''
waveform = self.comboWaveform.currentText()
length = int(self.textLength.text())
# Parse the frequency value!!!
# We should use as many array elements as frequencies given
frequency = np.zeros(1)
frequency[0] = float(self.textFrequency.text())
amplitude = float(self.textAmplitude.text())
duration = float(self.textDuration.text())
delay = int(self.textDelay.text())
offset = float(self.textOffset.text())
duty = float(self.textDuty.text())
# Prepare the time array
tInit=float(0)
tFinal=duration
t = np.linspace(tInit, tFinal, num=length)
if waveform == 'chirp':
# Single chirp: Frequency-swept cosine generator.
# (t, f0=0, t1=1, f1=100, method='linear', phi=0, qshape=None)
# We set phi to 270 degrees because we want the signal to start in zero and then progressively rise
wave = signal.chirp(t, f0=0, t1=tFinal, f1=frequency, method='linear', phi=270)
elif waveform == 'sine':
# sweep_poly is a frequency-swept cosine generator, with a time-dependent frequency.
# We set a order zero polinomial, so we get just a cosine
p = np.poly1d(frequency)
wave = signal.sweep_poly(t, p, phi=270)
elif waveform == 'sawtooth':
# Sawtooth example: A 5 Hz waveform sampled at 500 Hz for 1 second:
# t = np.linspace(0, 1, 500)
# signal.sawtooth(2 * np.pi * 5 * t)
wave = signal.sawtooth(2*np.pi*frequency*t, width=duty)
elif waveform == 'square':
# Square Wave
wave = signal.square(2*np.pi*frequency*t, duty=duty)
elif waveform == 'impulse':
# Sweep Poly
wave=np.zeros(length)
wave[delay]=1
elif waveform == 'step':
# Sweep Poly
wave=np.zeros(length)
for ii in range(length-delay):
wave[ii+delay]=1
else :
print('Not recognized waveform function: signal is zero')
# Sweep Poly
wave=np.zeros(length)
for ii in range(len(wave)):
wave[ii] = wave[ii]*amplitude + offset
return wave
def on_stimulus_draw(self):
""" Redraws the figure
"""
# clear the axes and redraw the plot anew
#
self.axes.clear()
self.axes.grid(self.cbGridStimulus.isChecked())
print('Generate a basic signal using the generator')
print(self.comboWaveform.currentText())
self.x = self.waveform()
self.axes.plot(self.x, 'go-', label='Channel 1')
self.axes.set_ylabel('value')
self.axes.set_xlabel('sample')
self.canvasStimulus.draw()
self.stimulusUpdatedSignal.emit()
def create_stimulus_layout(self):
# Create the mpl Figure and FigCanvas objects.
# 5x4 inches, 100 dots-per-inch
#
self.dpi = 100
self.fig = Figure((5.0, 4.0), dpi=self.dpi)
self.canvasStimulus = FigureCanvas(self.fig)
self.canvasStimulus.setParent(self.main_frame)
# Since we have only one plot, we can use add_axes
# instead of add_subplot, but then the subplot
# configuration tool in the navigation toolbar wouldn't
# work.
#
self.axes = self.fig.add_subplot(111)
# Bind the 'pick' event for clicking on one of the bars
#
self.canvasStimulus.mpl_connect('pick_event', self.on_pick)
# Create the navigation toolbar, tied to the canvas
#
self.mpl_toolbar = NavigationToolbar(self.canvasStimulus, self.main_frame)
# Other GUI controls
#
labelWaveform = QLabel('Waveform:')
self.comboWaveform = QComboBox()
self.comboWaveform.addItem("chirp")
self.comboWaveform.addItem("sine")
self.comboWaveform.addItem("sawtooth")
self.comboWaveform.addItem("square")
self.comboWaveform.addItem("impulse")
self.comboWaveform.addItem("step")
self.comboWaveform.setEditable(True)
self.comboWaveform.lineEdit().setReadOnly(True)
self.comboWaveform.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboWaveform.count()):
self.comboWaveform.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
self.connect(self.comboWaveform, SIGNAL('currentIndexChanged(int)'), self.on_stimulus_draw)
self.cbGridStimulus = QCheckBox("Show &Grid")
self.cbGridStimulus.setChecked(True)
self.connect(self.cbGridStimulus, SIGNAL('stateChanged(int)'), self.on_stimulus_draw)
labelLength = QLabel('Sample Length:')
self.textLength = QLineEdit()
validatorLength = QIntValidator(1,100000)
self.textLength.setValidator(validatorLength)
self.textLength.setText('1000')
self.textLength.setAlignment(Qt.AlignRight)
self.connect(self.textLength, SIGNAL('editingFinished()'), self.on_stimulus_draw)
labelFrequency = QLabel('Frequency:')
self.textFrequency = QLineEdit()
# QDoubleValidator.__init__ (self, float bottom, float top, int decimals)
validatorFrequency = QDoubleValidator(0, 1000, 8)
self.textFrequency.setValidator(validatorFrequency)
self.textFrequency.setText('10')
self.textFrequency.setAlignment(Qt.AlignRight)
self.connect(self.textFrequency, SIGNAL('editingFinished()'), self.on_stimulus_draw)
labelAmplitude = QLabel('Amplitude:')
self.textAmplitude = QLineEdit()
# QDoubleValidator.__init__ (self, float bottom, float top, int decimals)
validatorAmplitude = QDoubleValidator(0, 1000, 8)
self.textAmplitude.setValidator(validatorAmplitude)
self.textAmplitude.setText('0.5')
self.textAmplitude.setAlignment(Qt.AlignRight)
self.connect(self.textAmplitude, SIGNAL('editingFinished()'), self.on_stimulus_draw)
labelDuration = QLabel('Duration:')
self.textDuration = QLineEdit()
# QDoubleValidator.__init__ (self, float bottom, float top, int decimals)
validatorDuration = QDoubleValidator(0, 1000, 8)
self.textDuration.setValidator(validatorDuration)
self.textDuration.setText('1')
self.textDuration.setAlignment(Qt.AlignRight)
self.connect(self.textDuration, SIGNAL('editingFinished()'), self.on_stimulus_draw)
labelDelay = QLabel('Delay:')
self.textDelay = QLineEdit()
validatorDelay = QIntValidator(0, 1000)
self.textDelay.setValidator(validatorDelay)
self.textDelay.setText('0')
self.textDelay.setAlignment(Qt.AlignRight)
self.connect(self.textDuration, SIGNAL('editingFinished()'), self.on_stimulus_draw)
labelOffset = QLabel('Offset:')
self.textOffset = QLineEdit()
# QDoubleValidator.__init__ (self, float bottom, float top, int decimals)
validatorOffset = QDoubleValidator(-1000, 1000, 8)
self.textOffset.setValidator(validatorOffset)
self.textOffset.setText('0')
self.textOffset.setAlignment(Qt.AlignRight)
self.connect(self.textOffset, SIGNAL('editingFinished()'), self.on_stimulus_draw)
labelDuty = QLabel('Duty:')
self.textDuty = QLineEdit()
# QDoubleValidator.__init__ (self, float bottom, float top, int decimals)
validatorDuty = QDoubleValidator(0, 1, 8)
self.textDuty.setValidator(validatorDuty)
self.textDuty.setText('0')
self.textDuty.setAlignment(Qt.AlignRight)
self.connect(self.textDuty, SIGNAL('editingFinished()'), self.on_stimulus_draw)
#
# Layout with box sizers
#
hboxWaveform = QHBoxLayout()
hboxWaveform.addWidget(labelWaveform)
hboxWaveform.addWidget(self.comboWaveform)
hboxWaveform.setStretch(0,1)
hboxWaveform.setStretch(1,1)
hboxLength = QHBoxLayout()
hboxLength.addWidget(labelLength)
hboxLength.addWidget(self.textLength)
hboxLength.setStretch(0,1)
hboxLength.setStretch(1,1)
hboxFrequency = QHBoxLayout()
hboxFrequency.addWidget(labelFrequency)
hboxFrequency.addWidget(self.textFrequency)
hboxFrequency.setStretch(0,1)
hboxFrequency.setStretch(1,1)
hboxAmplitude = QHBoxLayout()
hboxAmplitude.addWidget(labelAmplitude)
hboxAmplitude.addWidget(self.textAmplitude)
hboxAmplitude.setStretch(0,1)
hboxAmplitude.setStretch(1,1)
hboxDuration = QHBoxLayout()
hboxDuration.addWidget(labelDuration)
hboxDuration.addWidget(self.textDuration)
hboxDuration.setStretch(0,1)
hboxDuration.setStretch(1,1)
hboxDelay = QHBoxLayout()
hboxDelay.addWidget(labelDelay)
hboxDelay.addWidget(self.textDelay)
hboxDelay.setStretch(0,1)
hboxDelay.setStretch(1,1)
hboxOffset = QHBoxLayout()
hboxOffset.addWidget(labelOffset)
hboxOffset.addWidget(self.textOffset)
hboxOffset.setStretch(0,1)
hboxOffset.setStretch(1,1)
hboxDuty = QHBoxLayout()
hboxDuty.addWidget(labelDuty)
hboxDuty.addWidget(self.textDuty)
hboxDuty.setStretch(0,1)
hboxDuty.setStretch(1,1)
vboxLeft = QVBoxLayout()
vboxLeft.addLayout(hboxWaveform)
vboxLeft.addLayout(hboxLength)
vboxLeft.addLayout(hboxFrequency)
vboxLeft.addLayout(hboxAmplitude)
groupBoxLeft = QGroupBox()
groupBoxLeft.setLayout(vboxLeft)
vboxRight = QVBoxLayout()
vboxRight.addLayout(hboxDuration)
vboxRight.addLayout(hboxDelay)
vboxRight.addLayout(hboxOffset)
vboxRight.addLayout(hboxDuty)
groupBoxRight = QGroupBox()
groupBoxRight.setLayout(vboxRight)
hboxStimulusControl = QHBoxLayout()
hboxStimulusControl.addWidget(groupBoxLeft)
hboxStimulusControl.addWidget(groupBoxRight)
groupBoxStimulusControl = QGroupBox('Stimulus Control')
groupBoxStimulusControl.setLayout(hboxStimulusControl)
groupBoxStimulusControl.isCheckable()
vboxMain = QVBoxLayout()
vboxMain.addWidget(self.canvasStimulus)
vboxMain.addWidget(self.mpl_toolbar)
vboxMain.addWidget(self.cbGridStimulus)
vboxMain.addWidget(groupBoxStimulusControl)
self.on_stimulus_draw()
return vboxMain
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
'''*** LibreFDATool ***
Libre Filter Design and Analysis Tool
LICENSED UNDER GPLv2 TERMS
This package provides the next librefdatool objects:
* device: filter hardware model
* generator: arbitrary waveform generator
* scope: multifunction signal scope
'''
# metadata module
__version__ = '0.1'
__author__ = 'Javier D. Garcia-Lasheras'
__email__ = 'javier@garcialasheras.com'
__url__ = 'http://www.ohwr.org/projects/libre-fdatool'
# LibreFDATool Libraries
from generator import *
from scope import *
#from device import *
from filter import *
from simulator import *
from threading import Thread
import sys, os, random
from PyQt4.QtCore import *
from PyQt4.QtGui import *
#import matplotlib
#from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
#from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
#from matplotlib.figure import Figure
class LibreFDATool(
QMainWindow,
Generator,
Filter,
Simulator
):
# TODO: I need to redeclare the signals here and I don't like it!!
stimulusUpdatedSignal = pyqtSignal()
filterUpdatedSignal = pyqtSignal()
simulatorUpdatedSignal = pyqtSignal()
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle('Libre-FDATool')
self.create_menu()
self.create_toolbar()
self.create_main_frame()
self.create_status_bar()
self.stimulusUpdatedSignal.connect(self.on_stimulus_updated)
self.filterUpdatedSignal.connect(self.on_filter_updated)
self.simulatorUpdatedSignal.connect(self.on_simulator_updated)
self.runSimulator()
self.main_frame.setCurrentIndex(0)
#Generator.__init__(self)
#Filter.__init__(self)
def save_plot(self):
file_choices = "PNG (*.png)|*.png"
path = unicode(QFileDialog.getSaveFileName(self,
'Save file', '',
file_choices))
if path:
self.canvas.print_figure(path, dpi=self.dpi)
self.statusBar().showMessage('Saved to %s' % path, 2000)
def on_about(self):
msg = """ This is Libre-FDATool development version:
* Use stimulus tab to configure the input
* Use filter tab to analyze and configure the filter
* Use simulation to configure the simulator
"""
QMessageBox.about(self, "About the demo", msg.strip())
def on_pick(self, event):
# The event received here is of the type
# matplotlib.backend_bases.PickEvent
#
# It carries lots of information, of which we're using
# only a small amount here.
#
box_points = event.artist.get_bbox().get_points()
msg = "You've clicked on a bar with coords:\n %s" % box_points
QMessageBox.information(self, "Click!", msg)
def create_main_frame(self):
self.main_frame = QTabWidget()
tabStimulus = QWidget()
tabFilter = QWidget()
tabSimulator = QWidget()
self.main_frame.addTab(tabStimulus, "Stimulus")
self.main_frame.addTab(tabFilter, "Filter")
self.main_frame.addTab(tabSimulator, "Simulation")
tabStimulus.setLayout(self.create_stimulus_layout())
tabFilter.setLayout(self.create_filter_layout())
tabSimulator.setLayout(self.create_simulator_layout())
self.setCentralWidget(self.main_frame)
def create_status_bar(self):
self.status_text = QLabel("This is a demo")
self.statusBar().addWidget(self.status_text, 1)
def create_menu(self):
self.file_menu = self.menuBar().addMenu("&File")
load_file_action = self.create_action("&Save plot",
shortcut="Ctrl+S", slot=self.save_plot,
tip="Save the plot")
quit_action = self.create_action("&Quit", slot=self.close,
shortcut="Ctrl+Q", tip="Close the application")
self.add_actions(self.file_menu,
(load_file_action, None, quit_action))
self.help_menu = self.menuBar().addMenu("&Help")
about_action = self.create_action("&About",
shortcut='F1', slot=self.on_about,
tip='About the demo')
self.add_actions(self.help_menu, (about_action,))
def create_toolbar(self):
exitAction = QAction(QIcon('images/exit_48.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(qApp.quit)
exitAction.setToolTip('Exit Libre-FDATool')
exportAction = QAction(QIcon('images/export_48.png'), 'Export', self);
exportAction.setShortcut('Ctrl+E');
exportAction.triggered.connect(self.exportHDL)
exportAction.setToolTip('Export HDL Code')
simulatorAction = QAction(QIcon('images/run_48.png'), 'Run', self);
simulatorAction.setShortcut('Ctrl+E');
simulatorAction.triggered.connect(self.runSimulator)
simulatorAction.setToolTip('Run the simulation')
self.toolbar = self.addToolBar('Stimulus')
self.toolbar.addAction(exitAction)
self.toolbar.addAction(exportAction)
self.toolbar.addAction(simulatorAction)
#self.toolbar = self.addToolBar('Filter')
#self.toolbar.addAction(exitAction)
def add_actions(self, target, actions):
for action in actions:
if action is None:
target.addSeparator()
else:
target.addAction(action)
def create_action( self, text, slot=None, shortcut=None,
icon=None, tip=None, checkable=False,
signal="triggered()"):
action = QAction(text, self)
if icon is not None:
action.setIcon(QIcon(":/%s.png" % icon))
if shortcut is not None:
action.setShortcut(shortcut)
if tip is not None:
action.setToolTip(tip)
action.setStatusTip(tip)
if slot is not None:
self.connect(action, SIGNAL(signal), slot)
if checkable:
action.setCheckable(True)
return action
def runSimulator(self):
# TODO: Simulator takes the configuration values even
# if they are not good!! We make a warning... something cleaner?
if self.pbUpdateFilter.isEnabled():
# The filter parameters are not updated!!
self.status_text.setText('Filter parameters update required')
self.main_frame.setCurrentIndex(1)
QMessageBox.warning(self, 'Filter not updated',
'Filter parameters need to be updated',
QMessageBox.Ok)
else:
self.status_text.setText('Running the simulation...')
self.status_text.repaint()
busX=[int(self.spinBoxInputP.value()),
int(self.spinBoxInputQ.value())]
busY=[int(self.spinBoxOutputP.value()),
int(self.spinBoxOutputQ.value())]
busC=[int(self.spinBoxCoefficientP.value()),
int(self.spinBoxCoefficientQ.value())]
scalingX = 1
scalingC = 1
self.execute_simulation(self.b, self.a,
self.x, str(self.textFilterName.text()), 'vhdl',
busX, busY, busC,
scalingX, scalingC)
self.on_simulator_draw()
self.main_frame.setCurrentIndex(2)
self.status_text.setText('Successful Simulation!!!')
def exportHDL(self):
#QMessageBox.information(self, 'Export HDL',
# 'This is only a message', QMessageBox.Ok)
self.status_text.setText('Filter export tool has been launched')
def on_stimulus_updated(self):
#QMessageBox.information(self, 'Stimulus Updated',
# 'This is only a message', QMessageBox.Ok)
self.status_text.setText('Stimulus configuration has been updated')
def on_filter_updated(self):
#QMessageBox.information(self, 'Filter Updated',
# 'This is only a message', QMessageBox.Ok)
self.status_text.setText('Filter configuration has been updated')
def on_simulator_updated(self):
#QMessageBox.information(self, 'Simulator Updated',
# 'This is only a message', QMessageBox.Ok)
self.status_text.setText('Simulator configuration has been updated')
def main():
app = QApplication(sys.argv)
form = LibreFDATool()
form.show()
app.exec_()
if __name__ == "__main__":
main()
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#
import warnings
import numpy as np
from numpy import pi, log10
from scipy import signal
from matplotlib import pyplot as plt
from matplotlib import patches, mlab
import sys, os, random
'''This module include the figure plotters used in Libre-FDATool.
'''
def analyze_pole_zero(figure, b, a, p, q, grid):
'''Plot graphical zero/pole analysis in Z-plane:
* b: LTI transfer function Numerator.
* a: LTI transfer function Denominator.
* filename: optional file for storing plot and not showing it.
'''
print('Plotting Z Analysis...')
#TODO: use DAC / ADC like function, this is bad!!!
# Quantize coefficients
b2 = np.zeros(len(b))
for ii in range(len(b)):
b2[ii] = int(b[ii]*(2**(p+q-1)))
b2 = b2/(2**(p+q-1))
a2 = np.zeros(len(a))
for ii in range(len(a)):
a2[ii] = int(a[ii]*(2**(p+q-1)))
a2 = a2/(2**(p+q-1))
# Temporal assignation: only valid for FIR
print('Coefficients')
b1 = b
a1 = a
# 1 - The coefficients must be less than 1, normalize the coefficients
if np.max(b1) > 1:
kn1 = np.max(b1)
b1 = b1/float(kn1)
else:
kn1 = 1
if np.max(a1) > 1:
kd1 = np.max(a1)
a1 = a1/float(kd1)
else:
kd1 = 1
# 2 - The coefficients must be than 1, normalize the coefficients
if np.max(b2) > 1:
kn2 = np.max(b2)
b2 = b2/float(kn2)
else:
kn2 = 1
if np.max(a2) > 1:
kd2 = np.max(a2)
a2 = a2/float(kd2)
else:
kd2 = 1
warningMessage = ''
warnings.simplefilter('error')
try:
# Get the poles and zeros
p1 = np.roots(a1)
z1 = np.roots(b1)
p2 = np.roots(a2)
z2 = np.roots(b2)
except ValueError, exVE:
warningMessage = '%s' % exVE
except ZeroDivisionError, exZDE:
warningMessage = '%s' % exZDE
except RuntimeWarning, exRW:
warningMessage = '%s' % exRW
if warningMessage != '':
return False, warningMessage
else:
# Clear the figure
figure.clear()
# get a figure/plot
poleZeroSubplot = figure.add_subplot(111)
# create the unit circle
uc = patches.Circle((0,0), radius=1, fill=False,
color='black', ls='dashed')
#ax.add_patch(uc)
poleZeroSubplot.add_patch(uc)
# 1 - Plot the zeros and set marker properties
poleZeroSubplot.plot(z1.real, z1.imag, 'bo', ms=10)
# 1 - Plot the poles and set marker properties
poleZeroSubplot.plot(p1.real, p1.imag, 'bx', ms=10)
# 2 - Plot the zeros and set marker properties
poleZeroSubplot.plot(z2.real, z2.imag, 'ro', ms=10)
# 2 - Plot the poles and set marker properties
poleZeroSubplot.plot(p2.real, p2.imag, 'rx', ms=10)
# set axis
poleZeroSubplot.axis('scaled')
poleZeroSubplot.set_ylabel('Imaginary Component')
poleZeroSubplot.set_xlabel('Real Component')
poleZeroSubplot.set_title(r'Zero-Pole Diagram (Blue=Float; Red=Int)')
poleZeroSubplot.grid(grid)
return True, 'OK'
def analyze_frequency_response(figure, b, a, p, q, grid):
'''Plot graphical Magnitude/Phase analysis in frequency domain:
* c: FIR filter coefficients array.
* filename: optional file for storing plot and not showing it.
'''
# Quantize coefficients
b2 = np.zeros(len(b))
for ii in range(len(b)):
b2[ii] = int(b[ii]*(2**(p+q-1)))
b2 = b2/(2**(p+q-1))
a2 = np.zeros(len(a))
for ii in range(len(a)):
a2[ii] = int(a[ii]*(2**(p+q-1)))
a2 = a2/(2**(p+q-1))
# TODO: If the coefficients are extremely low, the discretized version
# may be equal to zero, which suppose a log10 crash - divide by zero!
# We need to rise an advice about rising the coefficient bits!!
warningMessage = ''
warnings.simplefilter('error')
try:
wc,hc = signal.freqz(b,a)
hc_dB = 20 * log10 (abs(hc))
wd,hd = signal.freqz(b2,a2)
hd_dB = 20 * log10 (abs(hd))
except ValueError, exVE:
warningMessage = '%s' % exVE
except ZeroDivisionError, exZDE:
warningMessage = '%s' % exZDE
except RuntimeWarning, exRW:
warningMessage = '%s' % exRW
figure.clear()
magnitudeSubplot = figure.add_subplot(211)
magnitudeSubplot.set_ylim(-150, 5)
magnitudeSubplot.set_ylabel('Magnitude (dB)')
magnitudeSubplot.set_xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
magnitudeSubplot.grid(grid)
phaseSubplot = figure.add_subplot(212)
phaseSubplot.set_ylabel('Phase (radians)')
phaseSubplot.set_xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
phaseSubplot.grid(grid)
figure.subplots_adjust(hspace=0.5)
if warningMessage != '':
magnitudeSubplot.plot(wc/max(wc),hc_dB,'b')
hc_Phase = np.unwrap(np.arctan2(np.imag(hc),np.real(hc)))
magnitudeSubplot.set_title(r'Magnitude response (Float=Blue; Int=Error)')
phaseSubplot.plot(wc/max(wc),hc_Phase,'b')
phaseSubplot.set_title(r'Phase response (Float=Blue; Int=Error)')
return False, warningMessage
else:
magnitudeSubplot.plot(wc/max(wc),hc_dB,'b')
magnitudeSubplot.plot(wd/max(wd),hd_dB,'r')
magnitudeSubplot.set_title(r'Magnitude response (Float=Blue; Int=Red)')
hc_Phase = np.unwrap(np.arctan2(np.imag(hc),np.real(hc)))
hd_Phase = np.unwrap(np.arctan2(np.imag(hd),np.real(hd)))
phaseSubplot.plot(wc/max(wc),hc_Phase,'b')
phaseSubplot.plot(wd/max(wd),hd_Phase,'r')
phaseSubplot.set_title(r'Phase response (Float=Blue; Int=Error)')
return True, 'OK'
def scopeDual(figure, s1, s2, grid):
'''this method shows a dual time domain scope:
* s1: channel-1 input signal (blue, float)
* s2: channel-2 input signal (red, int)
'''
# Simulate float system response:
print('Run Scope Dual')
print('len(s1) =', len(s1))
print('len(s2) =', len(s2))
figure.clear()
scopeTimeSubplot = figure.add_subplot(111)
scopeTimeSubplot.plot(s1, 'bo-', label='Float')
scopeTimeSubplot.plot(s2, 'ro-', label='Hardware')
#self.scopeTimeSublot.axis('scaled')
#scopeTimeSubplot.set_title(r'Time Scope (red: int, blue: float)')
scopeTimeSubplot.set_ylabel('value')
scopeTimeSubplot.set_xlabel('sample')
scopeTimeSubplot.legend().draggable(state=True, use_blit=True)
scopeTimeSubplot.grid(grid)
def scopePower(figure, s1, s2, grid):
'''this method shows the estimated power spectrum for a signal:
* s: channel-1 assigned signal (blue)
'''
print('Plotting Power Spectrum...')
Ps1,fs1 = mlab.psd(s1)
Ps2,fs2 = mlab.psd(s2)
figure.clear()
scopePowerSubplot = figure.add_subplot(111)
scopePowerSubplot.plot(fs1, 10*log10(abs(Ps1)), 'b')
scopePowerSubplot.plot(fs2, 10*log10(abs(Ps2)), 'r')
scopePowerSubplot.set_ylabel('Power (dB)')
scopePowerSubplot.set_xlabel('Normalized Frequency')
scopePowerSubplot.set_title(r'Signal Power (red: int, blue: float)')
scopePowerSubplot.grid(grid)
def scopeError(figure, s1, s2, grid):
'''this method shows an error analysis between input signals:
* s1: channel-1 input signal
* s1: channel-2 input signal
'''
# *** Error Analisys ***
sdiff = np.abs(s1 - s2)
print('- Maximum error = ', np.max(sdiff))
print('- Mean error = ', np.mean(sdiff**2))
# Check for error tolerance
# assert np.max(sdiff) < 1e-3, "check if error is too large"
# Plot Error report
figure.clear()
scopeErrorSublot = figure.add_subplot(111)
scopeErrorSublot.plot(sdiff, 'go-')
title = 'Error Max=', np.max(sdiff), ' Mean=', np.mean(sdiff**2)
scopeErrorSublot.set_title(title)
scopeErrorSublot.set_ylabel('abs(error)')
scopeErrorSublot.set_xlabel('sample')
scopeErrorSublot.grid(grid)
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#
import sys
import os
import subprocess
import csv
import numpy as np
from scipy import signal
from bitstring import BitArray
from snippets import *
class Simcore:
'''This is a temporary class
Should it be removed as the development advances??
'''
def simfilter(self, b, a, x,
structure, model,
busX, busY, busC,
scalingX, scalingC):
self.structure = structure
self.model = model
self.busX = busX
self.busY = busY
self.busC = busC
self.scalingX = scalingX
self.scalingC = scalingC
# Define order values
self.M = len(b)
self.N = len(a)
# Convert coef to fixed point
self.coefB = b
self.icoefB = self._quantizer(b, self.busC)
# The A coefficients calculated with scipy uses a different convention and sign changes!!!!
a = -1 * a
self.coefA = a
self.icoefA = self._quantizer(a, self.busC)
print('Coef B')
print(self.icoefB)
print('Coef A')
print(self.icoefA)
# Set DUT
self._generateDUT()
self._generateTB(x)
return self._simulation()
#***********************************************#
# Generate DUT
#***********************************************#
def _generateDUT(self):
# All the products has an extra integer (the 2^1 factor)
# A fixed point number is comprised by integer (P) and fractional bits (Q)
# When you calculate the C product of A and B, then => PC = PA + PB; QC = QA + QB;
# We are dealing with P=1 for all our numbers, so we can discard the resulting MSB.
# By this way, the product of A and B limited to [-1,1) has a width of WC = WA + WB - 1
# NOTE: we need to consider the possibility of P>1 !! (there are bigger than 1 coefficients)
# We are going to allow the full fixed point specification for X, Y and C!!
# In the Sum S = A + B, the worst case for P is 1 + max(PA, PB).
# For QS, we have the must of QA being equal to QB, so QA = QB = QS
# As we have PA = PB = 1, PS would be 1 if there is not overflow.
# In any case, we can discard the overflow and assume that WC = WA = WS
# In order to detect the overflow in the sum S = A + B, WA = WB:
# If MSB(A) != MSB(B) => overflow cannot exist
# if MSB(A)=MSB(B)=1 && MSB(S)=0 => overflow in the minimum range
# if MSB(A)=MSB(B)=0 && MSB(S)=1 => overflow in the maximum range
busX = self.busX[0] + self.busX[1]
busY = self.busY[0] + self.busY[1]
busC = self.busC[0] + self.busC[1]
M = self.M
N = self.N
hdl = snippets()
if self.model == 'vhdl':
structure = self.structure
name = self.structure
realization='direct_form_1_transposed'
# Code generation for a Transposed Direct Form FIR
hdlFile = open('{!s}.vhd'.format(name),'w')
hdlFile.write(hdl.libraries())
hdlFile.write('\n')
hdlFile.write(hdl.entity(name, busX, busY))
hdlFile.write('\n')
hdlFile.write(hdl.architectureHeader(name, realization))
hdlFile.write('\n')
# *** DECLARE INTERNAL SIGNALS ***
if realization == 'direct_form_1_transposed':
hdlFile.write("-- Z^-1 delay blocks\n")
# Z blocks in the b coefficients side
for ii in range(self.M-1):
hdlFile.write('signal zb{!s}, zb{!s}_next: signed({!s} downto 0);\n'.format(ii, ii, busX + busC -1 -1))
hdlFile.write("\n")
# Z blocks in the a coefficients side
for ii in range(self.N-1):
if ii != 0:
hdlFile.write('signal za{!s}, za{!s}_next: signed({!s} downto 0);\n'.format(ii, ii, busX + busC -1 -1))
else:
hdlFile.write('signal za{!s}, za{!s}_next: signed({!s} downto 0);\n'.format(ii, ii, busX -1))
hdlFile.write("\n")
hdlFile.write("-- Filter constants\n")
for ii in range(self.M):
hdlFile.write('signal b{!s}: signed({!s} downto 0); \n'.format(ii, busC -1))
hdlFile.write("\n")
for ii in range(self.N):
if ii != 0:
hdlFile.write('signal a{!s}: signed({!s} downto 0); \n'.format(ii, busC -1))
hdlFile.write("\n")
hdlFile.write("-- Filter Adders\n")
for ii in range(self.M-1):
hdlFile.write('signal sb{!s}: signed({!s} downto 0);\n'.format(ii, busX + busC -1 -1))
hdlFile.write("\n")
for ii in range(self.N-1):
if ii != 0:
hdlFile.write('signal sa{!s}: signed({!s} downto 0);\n'.format(ii, busX + busC -1 -1))
else:
hdlFile.write('signal sa{!s}: signed({!s} downto 0);\n'.format(ii, busX -1))
hdlFile.write("\n")
hdlFile.write("-- Filter Products\n")
for ii in range(self.M):
hdlFile.write('signal pb{!s}: signed({!s} downto 0);\n'.format(ii, busX + busC -1 -1))
hdlFile.write("\n")
for ii in range(self.N):
if ii != 0:
hdlFile.write('signal pa{!s}: signed({!s} downto 0);\n'.format(ii, busX + busC -1 -1))
hdlFile.write("\n")
# Intermediate signal for df1: assume that the width is the same that in x!
# NOTE: we have set v as equal to X, but this may lead to overflow troubles!!!!!!
hdlFile.write('signal v: signed({!s} downto 0);\n\n'.format(busX -1))
hdlFile.write("-- Begin Architecture\n")
hdlFile.write("begin\n\n")
hdlFile.write(hdl.sequentialBlock(M, N, clkEdge='posedge', rstActive='high'))
hdlFile.write("\n")
hdlFile.write('-- Arithmetics\n')
hdlFile.write("\n")
# Coefficients
for ii in range(self.M):
hdlFile.write('b{!s} <= \"{!s}\"; -- {!s}\n'.format(ii, self.icoefB[ii], self.coefB[ii]))
hdlFile.write("\n")
for ii in range(self.N):
if ii != 0:
hdlFile.write('a{!s} <= \"{!s}\"; -- {!s}\n'.format(ii, self.icoefA[ii], self.coefA[ii]))
hdlFile.write("\n")
# Products
for ii in range(self.M):
hdlFile.write('pb{!s} <= v * b{!s};\n'.format(ii, ii))
hdlFile.write("\n")
for ii in range(self.N):
if ii != 0:
hdlFile.write('pa{!s} <= v * a{!s};\n'.format(ii, ii))
hdlFile.write("\n")
# Sums
for ii in range(self.M-1):
hdlFile.write('sb{!s} <= pb{!s} + zb{!s};\n'.format(ii, ii, ii))
hdlFile.write("\n\n")
for ii in range(self.N-1):
if ii == 0:
hdlFile.write('sa{!s} <= sig_in + za{!s};\n'.format(ii, ii))
else:
hdlFile.write('sa{!s} <= pa{!s} + za{!s};\n'.format(ii, ii, ii))
hdlFile.write("\n\n")
hdlFile.write('-- Signal link, trunk, overflow, fixed point...\n')
for ii in range(self.M):
if ii == 0:
# Why always is a Zero as MSB in si? --> this is because the input is always a positive number?????
if self.M == 1:
hdlFile.write(hdl.convertFixedPoint('pb{!s}'.format(ii), self.busC[0] + self.busX[0] -1, self.busC[1] + self.busX[1], 'sig_out', self.busY[0], self.busY[1]))
else:
hdlFile.write(hdl.convertFixedPoint('sb{!s}'.format(ii), self.busC[0] + self.busX[0] -1, self.busC[1] + self.busX[1], 'sig_out', self.busY[0], self.busY[1]))
elif ii == (self.M-1):
hdlFile.write('zb{!s}_next <= pb{!s};\n'.format(ii-1, ii))
else:
hdlFile.write('zb{!s}_next <= sb{!s};\n'.format(ii-1, ii))
for ii in range(self.N):
if ii == 0:
# Why always is a Zero as MSB in si? --> this is because the input is always a positive number?????
if self.N == 1:
hdlFile.write('v <= sig_in;\n')
else:
hdlFile.write('v <= sa0;\n')
elif ii == 1:
if ii != (self.N-1):
hdlFile.write(hdl.convertFixedPoint('sa{!s}'.format(ii), self.busC[0] + self.busX[0] -1, self.busC[1] + self.busX[1], 'za{!s}_next'.format(ii-1), self.busX[0], self.busX[1]))
else:
hdlFile.write(hdl.convertFixedPoint('pa{!s}'.format(ii), self.busC[0] + self.busX[0] -1, self.busC[1] + self.busX[1], 'za{!s}_next'.format(ii-1), self.busX[0], self.busX[1]))
elif ii == (self.N-1):
hdlFile.write('za{!s}_next <= pa{!s};\n'.format(ii-1, ii))
else:
hdlFile.write('za{!s}_next <= sa{!s};\n'.format(ii-1, ii))
hdlFile.write("\n\n")
hdlFile.write('end {!s};\n'.format(realization))
hdlFile.close()
elif self.model == 'verilog':
structure = self.structure
realization='direct_form_transposed'
# Verilog Code generation for a Transposed Direct Form FIR
hdlFile = open('{!s}.v'.format(structure),'w')
hdlFile.write("// This is a transposed direct form test\n\n")
hdlFile.write("`timescale 1ns/10ps\n\n")
hdlFile.write("module {!s} (\n".format(structure))
hdlFile.write(" clk,\n")
hdlFile.write(" rst,\n")
hdlFile.write(" sig_in,\n")
hdlFile.write(" sig_out\n")
hdlFile.write(");\n\n")
hdlFile.write('// Architecture depends on selected structure\n')
hdlFile.write('// It would be nice to have target optimizations too in the future\n')
hdlFile.write('//\n')
hdlFile.write('// example, transposed direct form for FIR:\n')
hdlFile.write('//\n')
hdlFile.write('// z^-1 z^-1 z^-1 z^-1\n')
hdlFile.write('// o-->--o-->--o-->- - - --o-->--o-->--o-->--o y[n]\n')
hdlFile.write('// | | | | | | \n')
hdlFile.write('// ^Bm ^Bm-1 ^Bm-2 ^B2 ^B1 ^B0\n')
hdlFile.write('// | | | | | |\n')
hdlFile.write('// x[n] o-->--o-->--o-->--o-->- - - --o-->--o-->--\n')
hdlFile.write('//\n\n')
hdlFile.write("input clk;\n")
hdlFile.write("input rst;\n")
hdlFile.write("input signed [{!s}:0] sig_in;\n".format(self.busX-1))
hdlFile.write("output signed [{!s}:0] sig_out;\n".format(self.busY-1))
hdlFile.write("// Z^-1 delay blocks\n")
hdlFile.write('reg signed [{!s}:0] z [0:{!s}];\n'.format(self.busX + self.busC -1, len(self.icoef)-1))
hdlFile.write('wire signed [{!s}:0] z_next [0:{!s}];\n'.format(self.busX + self.busC -1, len(self.icoef)-1))
hdlFile.write("\n")
hdlFile.write("// Filter constants\n")
for ii in range(self.M):
hdlFile.write('wire signed [{!s}:0] b{!s};\n'.format(self.busC -1, ii))
hdlFile.write("\n")
hdlFile.write("// Filter Adders\n")
for ii in range(self.M-1):
hdlFile.write('wire signed [{!s}:0] s{!s};\n'.format(self.busX + self.busC -1, ii))
hdlFile.write("\n")
hdlFile.write("// Filter Products\n")
for ii in range(self.M):
hdlFile.write('wire signed [{!s}:0] p{!s};\n'.format(self.busX + self.busC -1, ii))
hdlFile.write("\n")
hdlFile.write("always @(posedge clk) begin: {!s}\n".format(realization))
hdlFile.write(" if (rst == 1'b1) begin\n")
for ii in range(self.M-1):
hdlFile.write(' z[{!s}] <= 0;\n'.format(ii))
hdlFile.write(" end\n")
hdlFile.write(" else begin\n")
for ii in range(self.M-1):
hdlFile.write(' z[{!s}] <= z_next[{!s}];\n'.format(ii, ii))
hdlFile.write(" end\n")
hdlFile.write("end\n")
hdlFile.write("\n")
hdlFile.write('// Arithmetics\n')
hdlFile.write("\n")
for ii in range(self.M):
hdlFile.write('assign b{!s} = {!s}\'b{!s}; // {!s}\n'.format(ii, self.busC, self.icoef[ii], self.coef[ii]))
hdlFile.write("\n")
for ii in range(self.M):
hdlFile.write('assign p{!s} = sig_in * b{!s};\n'.format(ii, ii))
hdlFile.write("\n")
for ii in range(self.M-1):
hdlFile.write('assign s{!s} = p{!s} + z[{!s}];\n'.format(ii, ii, ii))
hdlFile.write("\n\n")
hdlFile.write('// Signal link, trunk, overflow...\n')
for ii in range(self.M):
if ii == 0:
# Why always is a Zero as MSB in si? --> this is because the input is always a positive number?????
hdlFile.write('assign sig_out = s{!s}[{!s}:{!s}];\n'.format(ii, self.busX + self.busC -1, self.busX + self.busC - self.busY))
elif ii == (len(self.coef)-1):
hdlFile.write('assign z_next[{!s}] = p{!s};\n'.format(ii-1, ii))
else:
hdlFile.write('assign z_next[{!s}] = s{!s};\n'.format(ii-1, ii))
hdlFile.write("\n\n")
hdlFile.write("endmodule\n")
hdlFile.write("\n")
hdlFile.close()
else:
print("Error: simulation mode not recognized\n");
return 0
def _generateTB(self, x):
# TBD: the process of input signal and output value parse
# must be aligned and configurable
# This Verilog file is common for verilog and vhdl DUTs in IVerilog
# If we want to add support for more simulators, then would be necessary VHDL
# Code generation for the testbench - myhdl link
busX = self.busX[0] + self.busX[1]
busY = self.busY[0] + self.busY[1]
busC = self.busC[0] + self.busC[1]
structure = self.structure
tbFile = open('tb_{!s}.v'.format(structure),'w')
tbFile.write("module tb_{!s};\n".format(structure))
tbFile.write("\n")
tbFile.write("reg clk;\n")
tbFile.write("reg rst;\n")
tbFile.write("reg [{!s}:0] sig_in;\n".format(busX-1))
tbFile.write("wire [{!s}:0] sig_out;\n".format(busY-1))
tbFile.write("\n")
tbFile.write("{!s} dut(\n".format(structure))
tbFile.write(" clk,\n")
tbFile.write(" rst,\n")
tbFile.write(" sig_in,\n")
tbFile.write(" sig_out\n")
tbFile.write(");\n")
tbFile.write("\n")
clockPosWidth = 25
clockNegWidth = 25
tbFile.write("always begin\n")
tbFile.write(" clk <= 1;\n")
tbFile.write(" #{!s};\n".format(clockNegWidth))
tbFile.write(" clk <= 0;\n")
tbFile.write(" $display(\"%d, %b, %b\", $time, sig_in, sig_out);\n")
tbFile.write(" #{!s};\n".format(clockPosWidth))
tbFile.write("end\n")
tbFile.write("\n")
tbFile.write("\n")
tbFile.write("\n")
tbFile.write("\n")
tbFile.write("initial begin\n")
tbFile.write(" $dumpfile(\"{!s}.vcd\");\n".format(structure))
tbFile.write(" $dumpvars;\n")
tbFile.write("end\n")
tbFile.write("\n")
tbFile.write("initial begin\n")
tbFile.write(' sig_in <= {!s}\'b{!s}; // signal is initially zero\n'.format(busX, 0))
tbFile.write(" rst <= 1'b1; #100;\n")
tbFile.write(" rst <= 1'b0; #150;\n")
xb = self._quantizer(x, self.busX, staircase='midtread')
for ii in range(len(x)):
tbFile.write(' #50; sig_in <= {!s}\'b{!s}; // {!s}\n'.format(busX, xb[ii], x[ii]))
tbFile.write(" $finish;\n")
tbFile.write("end\n")
tbFile.write("\n")
tbFile.write("\n")
tbFile.write("endmodule\n\n")
tbFile.close()
def _quantizer(self, signal, bus, xm=1, staircase= 'midtread'):
# Normalization to the [-1, 1) input range
signalNorm = signal/xm
# Generate the fixed point code in two's complement
#
# xb = -a0*2^0 + a1*2^(-1) + a2*2^(-2) + ... + aB*2^(-B)
# bus = B + 1;
B = bus[1] + bus[0] - 1
# Generate an
if staircase == 'midtread':
delta = 1/2
elif staircase == 'midriser':
delta = 0
else:
print("Staircase model for quantizer unknown: using default")
delta = 1/2
# Convert the normalized signal to a integer value
signalInt = np.floor(signalNorm*(2**(bus[1])) + delta)
# Trunk if the integers cannot be represented using the bus width
# Then assign the correspondent binary code
xBinary = []
for ii in range(len(signal)):
if signalInt[ii] > (2**B -1):
signalInt[ii] = 2**B - 1
elif signalInt[ii] < (-1 * 2**B):
signalInt[ii] = -1 * 2**B
xBinary.append(np.binary_repr(int(signalInt[ii]), width=B+1))
return xBinary
def _simulation(self, simulator='iverilog'):
structure = self.structure
if self.model == 'verilog':
dutExtension = 'v'
elif self.model == 'vhdl':
dutExtension = 'vhd'
else:
print('Unknown model: assuming verilog')
dutExtension = 'v'
print('TESTPOINT_1')
print('Cosimulation...')
print('TEST iverilog -o {!s} {!s}.{!s} tb_{!s}.v'.format(structure, structure, dutExtension, structure))
# Check if verilog/vhdl filter description is available TBD: make it a variable!!!!!!!!!!!!!!!!
if not os.path.isfile('{!s}.vhd'.format(structure)):
print('File not found: Run generation first')
return None
# Clean design
if os.path.isfile('{!s}'.format(structure)):
print('Existing compiled design: erase!! ')
cmd = 'rm {!s}'.format(structure)
os.system(cmd)
# Running Icarus verilog
# ****** TBD: Set the dut file extension according with the HDL language
cmd = 'iverilog -g2012 -o {!s} {!s}.{!s} tb_{!s}.v'.format(structure, structure, dutExtension, structure)
os.system(cmd)
cmd = 'vvp {!s}'.format(structure)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
reportFile = open('{!s}_report.txt'.format(structure),'wb')
reportFile.write(out)
reportFile.close()
#print("program output: {!s}".format(out))
print('TESTPOINT_4')
parsedOutput = []
with open('{!s}_report.txt'.format(structure),'r') as csvfile:
csvString = csv.reader(csvfile, delimiter=',', quotechar='|', skipinitialspace=True)
ii = 0
for row in csvString:
# Only the lines with three fields qualifies
if len(row) == 3:
# Only the values beyond a time are considered valids samples
# Note that init and reset values must be neglected
if int(row[0]) > 250:
a = BitArray(bin=row[2])
#print(a.int)
parsedOutput.append(a.int/float(2**(self.busY[1]) ))
ii = ii + 1
# The fixed point format for Y is calculated in an automatic fashion!!!
connect_sample_out = np.zeros(len(parsedOutput))
for ii in range(len(parsedOutput)):
connect_sample_out[ii] = parsedOutput[ii]
return connect_sample_out
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#
import warnings
from simcore import *
import numpy as np
from numpy import pi, log10
from scipy import signal
from matplotlib import pyplot as plt
import sys, os, random
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure
from scope import *
class Simulator(Simcore):
'''This class is the graphical interface to HDL simulator
'''
# Declare signals that will be sended to other classes
simulatorUpdatedSignal = pyqtSignal()
def on_simulator_draw(self):
""" Redraws the figure
"""
selectedPlot = str(self.comboSimulatorScope.currentText())
grid = self.cbGridSimulator.isChecked()
if selectedPlot == 'Time Plot':
scopeDual(self.figSimulator, self.yfloat, self.yhdl, grid)
elif selectedPlot == 'Error Plot':
scopeError(self.figSimulator, self.yfloat, self.yhdl, grid)
elif selectedPlot == 'Power Spectrum':
scopePower(self.figSimulator, self.yfloat, self.yhdl, grid)
else:
scopeDual(self.figSimulator, self.yfloat, self.yhdl, grid)
# Change pushbutton state
self.pbUpdateFilter.setDisabled(True)
self.pbUpdateFilter.setStyleSheet('QPushButton {background-color: #00FF00; color: #FFFFFF}')
self.canvasSimulator.draw()
def execute_simulation(self, b, a, x,
name, language,
busX, busY, busC,
scalingX, scalingC):
""" Redraws the figure
"""
# Get the coefficients
warningMessage = ''
warnings.simplefilter('error')
try:
self.yfloat = signal.lfilter(b, a, x)
self.yhdl = self.simfilter(b, a, x,
'testfilt', 'vhdl',
busX, busY, busC,
scalingX, scalingC)
except ValueError, exVE:
warningMessage = '%s' % exVE
except ZeroDivisionError, exZDE:
warningMessage = '%s' % exZDE
except RuntimeWarning, exRW:
warningMessage = '%s' % exRW
if warningMessage != '':
QMessageBox.warning(self, 'Error on Simulation',
"%s" % warningMessage, QMessageBox.Ok)
else:
self.on_simulator_draw()
# Clear the Figure
def create_simulator_layout(self):
# Create the mpl Figure and FigCanvas objects.
# 5x4 inches, 100 dots-per-inch
#
#self.dpi = 100
#self.figSimulator = Figure((5.0, 4.0), dpi=self.dpi)
self.figSimulator = Figure()
self.canvasSimulator = FigureCanvas(self.figSimulator)
self.canvasSimulator.setParent(self.main_frame)
# Since we have only one plot, we can use add_axes
# instead of add_subplot, but then the subplot
# configuration tool in the navigation toolbar wouldn't
# work.
#
self.axesSimulator = self.figSimulator.add_subplot(111)
# Bind the 'pick' event for clicking on one of the bars
#
self.canvasSimulator.mpl_connect('pick_event', self.on_pick)
# Create the navigation toolbar, tied to the canvas
#
self.mpl_toolbar_simulator = NavigationToolbar(self.canvasSimulator, self.main_frame)
# Other GUI controls
#
labelSimulatorEngine = QLabel('Simulation Engine:')
self.comboSimulatorEngine = QComboBox()
self.comboSimulatorEngine.addItem("Icarus Verilog")
self.comboSimulatorEngine.addItem("GHDL")
self.comboSimulatorEngine.setEditable(True)
self.comboSimulatorEngine.lineEdit().setReadOnly(True)
self.comboSimulatorEngine.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboSimulatorEngine.count()):
self.comboSimulatorEngine.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
self.connect(self.comboSimulatorEngine, SIGNAL('currentIndexChanged(int)'), self.on_simulator_modified)
labelSimulatorLanguage = QLabel('HDL Language:')
self.comboSimulatorLanguage = QComboBox()
self.comboSimulatorLanguage.addItem("Verilog")
self.comboSimulatorLanguage.addItem("VHDL")
self.comboSimulatorLanguage.setEditable(True)
self.comboSimulatorLanguage.lineEdit().setReadOnly(True)
self.comboSimulatorLanguage.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboSimulatorLanguage.count()):
self.comboSimulatorLanguage.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
self.connect(self.comboSimulatorLanguage, SIGNAL('currentIndexChanged(int)'), self.on_simulator_modified)
labelSimulatorScope = QLabel('Output Scope:')
self.comboSimulatorScope = QComboBox()
self.comboSimulatorScope.addItem("Time Plot")
self.comboSimulatorScope.addItem("Error Plot")
self.comboSimulatorScope.addItem("Power Spectrum")
self.comboSimulatorScope.setEditable(True)
self.comboSimulatorScope.lineEdit().setReadOnly(True)
self.comboSimulatorScope.lineEdit().setAlignment(Qt.AlignRight)
for ii in range(self.comboSimulatorScope.count()):
self.comboSimulatorScope.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
self.connect(self.comboSimulatorScope, SIGNAL('currentIndexChanged(int)'), self.on_simulator_draw)
self.cbGridSimulator = QCheckBox("Show &Grid")
self.cbGridSimulator.setChecked(True)
self.connect(self.cbGridSimulator, SIGNAL('stateChanged(int)'), self.on_simulator_draw)
# filter name
labelFilterName = QLabel('Filter Name:')
self.textFilterName = QLineEdit()
# validate only characters and numbers
regExpFilterName = QRegExp('^[a-zA-Z0-9]+$')
validatorFilterName = QRegExpValidator(regExpFilterName)
self.textFilterName.setValidator(validatorFilterName)
self.textFilterName.setText('myfilter')
self.textFilterName.setAlignment(Qt.AlignRight)
self.connect(self.textFilterName, SIGNAL('editingFinished()'), self.on_simulator_modified)
# Work directory
labelWorkFolder = QLabel('Work Folder:')
self.textWorkFolder = QLineEdit()
self.pbWorkFolder = QPushButton('...')
self.connect(self.pbWorkFolder, SIGNAL('clicked()'), self.on_explore_work_folder)
# TODO: how to validate a path??
#regExpWorkFolder = QRegExp('^[a-zA-Z0-9]+$')
#validatorFilterName = QRegExpValidator(regExpWorkFolder)
#self.textFilterName.setValidator(validatorFilterName)
self.textWorkFolder.setText('.')
self.textWorkFolder.setAlignment(Qt.AlignRight)
self.connect(self.textWorkFolder, SIGNAL('editingFinished()'), self.on_simulator_modified)
#
# Layout with box sizers
#
hboxSimulatorEngine = QHBoxLayout()
hboxSimulatorEngine.addWidget(labelSimulatorEngine)
hboxSimulatorEngine.addWidget(self.comboSimulatorEngine)
hboxSimulatorEngine.setStretch(0,1)
hboxSimulatorEngine.setStretch(1,1)
hboxSimulatorLanguage = QHBoxLayout()
hboxSimulatorLanguage.addWidget(labelSimulatorLanguage)
hboxSimulatorLanguage.addWidget(self.comboSimulatorLanguage)
hboxSimulatorLanguage.setStretch(0,1)
hboxSimulatorLanguage.setStretch(1,1)
hboxSimulatorScope = QHBoxLayout()
hboxSimulatorScope.addWidget(labelSimulatorScope)
hboxSimulatorScope.addWidget(self.comboSimulatorScope)
hboxSimulatorScope.setStretch(0,1)
hboxSimulatorScope.setStretch(1,1)
hboxFilterName = QHBoxLayout()
hboxFilterName.addWidget(labelFilterName)
hboxFilterName.addWidget(self.textFilterName)
hboxFilterName.setStretch(0,1)
hboxFilterName.setStretch(1,1)
hboxWorkFolder = QHBoxLayout()
hboxWorkFolder.addWidget(labelWorkFolder)
hboxWorkFolder.addWidget(self.textWorkFolder)
hboxWorkFolder.addWidget(self.pbWorkFolder)
hboxWorkFolder.setStretch(0,4)
hboxWorkFolder.setStretch(1,4)
hboxWorkFolder.setStretch(2,1)
vboxSimulatorControl = QVBoxLayout()
vboxSimulatorControl.addLayout(hboxFilterName)
vboxSimulatorControl.addLayout(hboxWorkFolder)
vboxSimulatorControl.addLayout(hboxSimulatorEngine)
vboxSimulatorControl.addLayout(hboxSimulatorLanguage)
groupBoxSimulatorControl = QGroupBox('Simulator Control')
groupBoxSimulatorControl.setLayout(vboxSimulatorControl)
groupBoxSimulatorControl.isCheckable()
vboxMain = QVBoxLayout()
vboxMain.addWidget(self.canvasSimulator)
vboxMain.addWidget(self.mpl_toolbar_simulator)
vboxMain.addWidget(self.cbGridSimulator)
vboxMain.addLayout(hboxSimulatorScope)
vboxMain.addWidget(groupBoxSimulatorControl)
#self.on_simulator_draw()
return vboxMain
def on_explore_work_folder(self):
dialogWorkFolder = QFileDialog()
#dialogWorkFolder.setFileMode(QFileDialog.Directory)
#dialogWorkFolder.setOption(QFileDialog.ShowDirsOnly, True)
self.textWorkFolder.setText(dialogWorkFolder.getExistingDirectory(self,
'Select Work Folder', './'))
def on_simulator_modified(self):
print('on_simulator_modified')
self.simulatorUpdatedSignal.emit()
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#
import sys
import os
import subprocess
import csv
import numpy as np
from scipy import signal
from bitstring import BitArray
class snippets:
# we are going to use dictionary-based string formatting
def libraries(self):
libString = (
'library ieee;\n'
'use ieee.std_logic_1164.all;\n'
'use ieee.numeric_std.all;\n\n'
)
return libString
def entity(self, name, busX, busY):
entityDict = {
'Name': name,
'MSBitX': busX - 1,
'MSBitY': busY - 1
}
entityString = (
'entity %(Name)s is\n'
' port (\n'
' clk : in std_logic;\n'
' rst : in std_logic;\n'
' sig_in : in signed(%(MSBitX)u downto 0);\n'
' sig_out : out signed(%(MSBitY)u downto 0)\n'
' );\n'
'end entity;\n'
)
return entityString % entityDict
def architectureHeader(self, name, realization):
#TBD: include the appropriated realization diagram
archHeadDict = {
'Name': name,
'Realization': realization
}
archHeadString = (
'architecture %(Realization)s of %(Name)s is\n\n'
'-- Architecture depends on selected realization\n'
'-- TODO: this header should each different realization\n'
'--\n'
'-- example, transposed direct form for FIR:\n'
'--\n'
'-- z^-1 z^-1 z^-1 z^-1\n'
'-- o-->--o-->--o-->- - - --o-->--o-->--o-->--o y[n]\n'
'-- | | | | | | \n'
'-- ^Bm ^Bm-1 ^Bm-2 ^B2 ^B1 ^B0\n'
'-- | | | | | |\n'
'-- x[n] o-->--o-->--o-->--o-->- - - --o-->--o-->--\n'
'--\n'
)
return archHeadString % archHeadDict
def convertFixedPoint(self, nameX, pX, qX, nameY, pY, qY, overflow=False, language='vhdl'):
# TBD: overflow handling
# The syntax is not very handy when pX, qX, pY, qY, qDiff or pDiff are equal to 1 => (i downto i)???
pDiff = pY - pX
qDiff = qY - qX
# INTEGER PART
if pDiff == 0:
# Destination integer part is == than the input one
signExt = ''
MSBpY = pY + qY - 1
LSBpY = qY
MSBpX = pX + qX - 1
LSBpX = qX
elif pDiff > 0:
signExt = '%(nameY)s({!s} downto {!s}) <= (others => %(nameX)s({!s}));\n'.format(pY+qY-1, pY+qY-pDiff, pX+qX-1)
MSBpY = pY + qY - 1 - pDiff
LSBpY = qY
MSBpX = pX + qX - 1
LSBpX = qX
# Destination integer part is > than the input one
# sign extension in the extra Y bits!!
# Now the rest of the significant bits
else: # pdiff < 0
signExt = ''
MSBpY = pY + qY - 1
LSBpY = qY
MSBpX = pX + qX - 1 + pDiff
LSBpX = qX
# Destination integer part is < than the input one
# We should be carefull with overflow: TBD
# FRACTIONAL PART (condition: qY and qX must be greater than zero???)
if qDiff == 0:
trunkExt = ''
MSBqY = qY - 1
LSBqY = 0
MSBqX = qX - 1
LSBqX = 0
# Destination fractional part is == than the input one
elif qDiff > 0:
# Destination fractional part is > than the input one
# Fill with zeros the unused bits
trunkExt = '%(nameY)s({!s} downto 0) <= (others => \'0\');\n'.format(qDiff-1)
MSBqY = qY - 1
LSBqY = qDiff
MSBqX = qX - 1
LSBqX = 0
else: #qDiff < 0
# Destination fractional part is < than the input one
trunkExt = ''
MSBqY = qY - 1
LSBqY = 0
MSBqX = qX - 1
LSBqX = -1 * qDiff
convertFPDict = {
'nameX': nameX,
'nameY': nameY,
'signExt': signExt,
'MSBpY': MSBpY,
'LSBpY': LSBpY,
'MSBpX': MSBpX,
'LSBpX': LSBpX,
'trunkExt': trunkExt,
'MSBqY': MSBqY,
'LSBqY': LSBqY,
'MSBqX': MSBqX,
'LSBqX': LSBqX
}
convertFPString = (
'%(signExt)s%(nameY)s(%(MSBpY)u downto %(LSBpY)u)'
' <= %(nameX)s(%(MSBpX)u downto %(LSBpX)u);\n'
'%(trunkExt)s%(nameY)s(%(MSBqY)u downto %(LSBqY)u)'
' <= %(nameX)s(%(MSBqX)u downto %(LSBqX)u);\n'
)
return convertFPString % convertFPDict
def sequentialBlock(self, M, N, clkEdge='posedge', rstActive='high'):
# TBD: different rst and clk polarity
# Now, they are true and posedge respectively
# Check the arguments
if clkEdge == 'posedge':
boolEdge = '1'
elif clkEdge == 'negedge':
boolEdge = '0'
else:
sys.exit('ERROR: active clock edge not recognized')
if rstActive == 'high':
boolRst = '1'
elif rstActive == 'low':
boolRst = '0'
else:
sys.exit('ERROR: reset active level not recognized')
seqDict = {
'boolEdge': boolEdge,
'boolRst': boolRst
}
if M >= 1 or N >= 1:
seqString = (
'-- Sequential block\n'
'z_block: process (clk)\n'
' begin\n'
' if (clk\'event and clk = \'%(boolEdge)s\') then\n'
' if (rst = \'%(boolRst)s\') then\n'
)
for ii in range(M-1):
seqString += ' zb%(ii)u <= 0;\n' % {'ii': ii}
for ii in range(N-1):
seqString += ' za%(ii)u <= 0;\n' % {'ii': ii}
seqString += ' else\n'
for ii in range(M-1):
seqString += ' zb%(ii)u <= zb%(ii)u_next;\n' % {'ii': ii}
for ii in range(N-1):
seqString += ' za%(ii)u <= za%(ii)u_next;\n' % {'ii': ii}
seqString += (
' end if;\n'
' end if;\n'
'end process;\n'
)
return seqString % seqDict
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