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 diff is collapsed.
This diff is collapsed.
# 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 diff is collapsed.
This diff is collapsed.
# 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