Adding the new tree for 0.1

parent dc2c0e65
[Desktop Entry]
Version=1.0
Name=LibreFDATool
Comment=Libre Filter Design and Analysis Tool
Type=Application
Exec=/usr/bin/librefdatool
Icon=/usr/share/librefdatool/data/icons/logo.png
Terminal=false
[Desktop Entry]
Version=1.0
Name=LibreFDATool
Comment=Libre Filter Design and Analysis Tool
Type=Application
Exec=/usr/bin/librefdatool
Icon=/usr/share/librefdatool/data/icons/librefdatool.svg
Terminal=false
Gespeaker is a GTK+ frontend for eSpeak and mbrola.
Copyright 2009 Fabio Castelli <muflone@vbsimple.net>
License: GPL-2+ (please see the copyright file)
Description:
Gespeaker allows to play a text in many languages with settings for voice,
pitch, volume, speed and word gap.
Since version 0.6 it can use mbrola package and voices to obtain a more
realistic text reading experience.
Requirements:
Python >= 2.4
eSpeak (program + voices)
Python bindings for GTK2
Python bindings for Glade and libglade support
Python bindings for gObject
ALSA (aplay) or Pulseaudio server (paplay)
Support for mbrola:
If mbrola package and mbrola voices are available then the program could use
them. Just enable them from the preferences dialog.
Personal configuration
User's configuration will be kept under ~/.gespeaker
Please report any bugs in Gespeaker to the author:
Fabio Castelli <muflone@vbsimple.net>
Homepage:
Official project: http://code.google.com/p/gespeaker/
Italian project : http://ubuntrucchi.wordpress.com/progetti-projects/gespeaker/
librefdatool (0.1-1) saucy; urgency=low
* First snapshot from OHR sources
-- Javier D. Garcia-Lasheras (Javi) <javier@garcialasheras.com> Wed, 30 Oct 2013 01:26:07 +0100
Copyright 2009 Fabio Castelli <muflone@vbsimple.net>
License: GPL-2+
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program 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; either version 2 of the License, or
(at your option) any later version.
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.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
#!/bin/bash
cd /usr/share/librefdatool/src
env python librefdatool.py
.\" $Id: gespeaker.1 0.7 2009-12-06 14:12 muflone $
.\"
.\" Copyright (c) 2009 Fabio Castelli
.TH GESPEAKER "1" "December 06, 2009"
.SH NAME
.B Gespeaker
\- A GTK+ frontend for eSpeak and mbrola
.SH SYNOPSIS
gespeaker
.SH DESCRIPTION
.PP
.B Gespeaker
is a GTK+ frontend for eSpeak and mbrola.
It allows to play a text in many languages with settings for voice, pitch,
volume, speed and word gap.
.PP
Since version 0.6 it can use mbrola package and voices to
obtain a more realistic text reading experience.
.PP
If mbrola was installed then the voices path must be selected from the mbrola
voices tab on the preferences page.
.SH FILES
Personal settings will be kept under ~/.gespeaker
.SH AUTHORS
.B Gespeaker
was written by Fabio Castelli <muflone@vbsimple.net>
.SH HOMEPAGE
International project: http://code.google.com/p/gespeaker/
Italian project: http://ubuntrucchi.wordpress.com/progetti-projects/gespeaker/
#!/usr/bin/env python
# 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
#
from distutils.core import setup
from distutils.command.install_data import install_data
from distutils.dep_util import newer
from distutils.log import info
import glob
import os
import sys
__version__ = '0.1'
class InstallData(install_data):
def run (self):
install_data.run (self)
setup(
name='librefdatool',
version=__version__,
namespace_packages=['librefdatool'],
include_package_data=True,
maintainer='Javier D. Garcia-Lasheras',
maintainer_email='javier@garcialasheras.com',
license='LGPLv3',
url='http:www.owhr.org/projects/libre-fdatool',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: '
'GNU Lesser General Public License v3 or later (LGPLv3+)',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
scripts=['librefdatool'],
data_files=[
('share/applications', ['data/librefdatool.desktop']),
('share/man/man1', ['man/librefdatool.1']),
('share/doc/librefdatool', ['doc/README', 'doc/changelog']),
('share/librefdatool/data/images', glob.glob('data/images/*')),
('share/librefdatool/data/icons', glob.glob('data/icons/*')),
('share/librefdatool/src', glob.glob('src/*.py')),
],
cmdclass={'install_data': InstallData}
)
# This is a manual translation, from perl to python, of :
# http://cpansearch.perl.org/src/GSULLIVAN/Verilog-VCD-0.03/lib/Verilog/VCD.pm
import re
global timescale
global endtime
def croak(*args):
"""Function similar to Perl's Carp::croak, to simplify porting this code"""
a = "".join(args);
raise Exception(a)
def list_sigs(file) :
"""Parse input VCD file into data structure,
then return just a list of the signal names."""
vcd = parse_vcd(file, only_sigs=1)
sigs = []
for k,v in vcd:
nets = v['nets']
sigs.extend( n['hier']+n['name'] for n in nets )
return sigs
def parse_vcd(file, only_sigs=0, use_stdout=0, siglist=[], opt_timescale=''):
"""Parse input VCD file into data structure.
Also, print t-v pairs to STDOUT, if requested."""
usigs = {}
for i in siglist:
usigs[i] = 1
if len(usigs):
all_sigs = 0
else :
all_sigs = 1
data = {}
mult = 0
num_sigs = 0
hier = []
time = 0
re_time = re.compile(r"^#(\d+)")
re_1b_val = re.compile(r"^([01zx])(.+)")
re_Nb_val = re.compile(r"^[br](\S+)\s+(.+)")
fh = open(file, 'r')
while True:
line = fh.readline()
if line == '' : # EOF
break
# chomp
# s/ ^ \s+ //x
line = line.strip()
if "$enddefinitions" in line:
num_sigs = len(data)
if (num_sigs == 0) :
if (all_sigs) :
croak("Error: No signals were found in the VCD file file.",
'Check the VCD file for proper var syntax.')
else :
croak("Error: No matching signals were found in the VCD file file.",
' Use list_sigs to view all signals in the VCD file.')
if ((num_sigs>1) and use_stdout) :
croak("Error: There are too many signals (num_sigs) for output ",
'to STDOUT. Use list_sigs to select a single signal.')
if only_sigs:
break
elif "$timescale" in line:
statement = line
if not "$end" in line:
while fh :
line = fh.readline()
statement += line
if "$end" in line:
break
mult = calc_mult(statement, opt_timescale)
elif "$scope" in line:
# assumes all on one line
# $scope module dff end
hier.append( line.split()[2] ) # just keep scope name
elif "$upscope" in line:
hier.pop()
elif "$var" in line:
# assumes all on one line:
# $var reg 1 *@ data $end
# $var wire 4 ) addr [3:0] $end
ls = line.split()
type = ls[1]
size = ls[2]
code = ls[3]
name = "".join(ls[4:-1])
path = '.'.join(hier)
full_name = path + name
if (full_name in usigs) or all_sigs :
if code not in data :
data[code] = {}
if 'nets' not in data[code]:
data[code]['nets'] = []
var_struct = {
'type' : type,
'name' : name,
'size' : size,
'hier' : path,
}
if var_struct not in data[code]['nets']:
data[code]['nets'].append( var_struct )
elif line.startswith('#'):
re_time_match = re_time.match(line)
time = mult * int(re_time_match.group(1))
endtime = time
elif line.startswith(('0', '1', 'x', 'z', 'b', 'r')):
re_1b_val_match = re_1b_val.match(line)
re_Nb_val_match = re_Nb_val.match(line)
if re_Nb_val_match :
value = re_Nb_val_match.group(1)
code = re_Nb_val_match.group(2)
elif re_1b_val_match :
value = re_1b_val_match.group(1)
code = re_1b_val_match.group(2)
if (code in data) :
if (use_stdout) :
print(time, value)
else :
if 'tv' not in data[code]:
data[code]['tv'] = []
data[code]['tv'].append( (time, value) )
fh.close()
return data
def calc_mult (statement, opt_timescale=''):
"""
Calculate a new multiplier for time values.
Input statement is complete timescale, for example:
timescale 10ns end
Input new_units is one of s|ms|us|ns|ps|fs.
Return numeric multiplier.
Also sets the package timescale variable.
"""
fields = statement.split()
fields.pop() # delete end from array
fields.pop(0) # delete timescale from array
tscale = ''.join(fields)
new_units = ''
if (opt_timescale != ''):
new_units = opt_timescale.lower()
new_units = re.sub(r"\s", '', new_units)
timescale = "1"+new_units
else :
timescale = tscale
return 1
mult = 0
units = 0
ts_match = re.compile(r"(\d+)([a-z]+)")
if ts_match.match(tscale):
mult = ts_match.group(1)
units = ts_match.group(2).lower()
else :
croak("Error: Unsupported timescale found in VCD file: tscale. ",
'Refer to the Verilog LRM.')
mults = {
'fs' : 1e-15,
'ps' : 1e-12,
'ns' : 1e-09,
'us' : 1e-06,
'ms' : 1e-03,
's' : 1e-00,
}
mults_keys = keys(mults)
mults_keys.sort(key=lambda x : mults[x])
usage = '|'.join(mults_keys)
scale = 0
if units in mults :
scale = mults[units]
else :
croak("Error: Unsupported timescale units found in VCD file: "+units+". ",
"Supported values are: "+usage)
new_scale = 0
if new_units in mults :
new_scale = mults[new_units]
else :
croak("Error: Illegal user-supplied timescale: "+new_units+". ",
"Legal values are: "+usage)
return ((mult * scale) / new_scale)
def get_timescale() :
return timescale
def get_endtime() :
return endtime
# =head1 NAME
#
# Verilog_VCD - Parse a Verilog VCD text file
#
# =head1 VERSION
#
# This document refers to Verilog::VCD version 0.03.
#
# =head1 SYNOPSIS
#
# from Verilog_VCD import parse_vcd
# vcd = parse_vcd('/path/to/some.vcd')
#
# =head1 DESCRIPTION
#
# Verilog is a Hardware Description Language (HDL) used to model digital logic.
# While simulating logic circuits, the values of signals can be written out to
# a Value Change Dump (VCD) file. This module can be used to parse a VCD file
# so that further analysis can be performed on the simulation data. The entire
# VCD file can be stored in a python data structure and manipulated using
# standard hash and array operations.
#
# =head2 Input File Syntax
#
# The syntax of the VCD text file is described in the documentation of
# the IEEE standard for Verilog. Only the four-state VCD format is supported.
# The extended VCD format (with strength information) is not supported.
# Since the input file is assumed to be legal VCD syntax, only minimal
# validation is performed.
#
# =head1 SUBROUTINES
#
#
# =head2 parse_vcd(file, $opt_ref)
#
# Parse a VCD file and return a reference to a data structure which
# includes hierarchical signal definitions and time-value data for all
# the specified signals. A file name is required. By default, all
# signals in the VCD file are included, and times are in units
# specified by the C<$timescale> VCD keyword.
#
# vcd = parse_vcd('/path/to/some.vcd')
#
# It returns a reference to a nested data structure. The top of the
# structure is a Hash-of-Hashes. The keys to the top hash are the VCD
# identifier codes for each signal. The following is an example
# representation of a very simple VCD file. It shows one signal named
# C<chip.cpu.alu.clk>, whose VCD code is C<+>. The time-value pairs
# are stored as an Array-of-Tuples, referenced by the C<tv> key. The
# time is always the first number in the pair, and the times are stored in
# increasing order in the array.
#
# {
# '+' : {
# 'tv' : [
# (
# 0,
# '1'
# ),
# (
# 12,
# '0'
# ),
# ],
# 'nets' : [
# {
# 'hier' : 'chip.cpu.alu.',
# 'name' : 'clk',
# 'type' : 'reg',
# 'size' : '1'
# }
# ]
# }
# }
#
# Since each code could have multiple hierarchical signal names, the names are
# stored as an Array-of-Hashes, referenced by the C<nets> key. The example above
# only shows one signal name for the code.
#
#
# =head3 OPTIONS
#
# Options to C<parse_vcd> should be passed as a hash reference.
#
# =over 4
#
# =item timescale
#
# It is possible to scale all times in the VCD file to a desired timescale.
# To specify a certain timescale, such as nanoseconds:
#
# vcd = parse_vcd(file, opt_timescale='ns'})
#
# Valid timescales are:
#
# s ms us ns ps fs
#
# =item siglist
#
# If only a subset of the signals included in the VCD file are needed,
# they can be specified by a signal list passed as an array reference.
# The signals should be full hierarchical paths separated by the dot
# character. For example:
#
# signals = [
# 'top.chip.clk',
# 'top.chip.cpu.alu.status',
# 'top.chip.cpu.alu.sum[15:0]',
# ]
# vcd = parse_vcd(file, siglist=signals)
#
# Limiting the number of signals can substantially reduce memory usage of the
# returned data structure because only the time-value data for the selected
# signals is loaded into the data structure.
#
# =item use_stdout
#
# It is possible to print time-value pairs directly to STDOUT for a
# single signal using the C<use_stdout> option. If the VCD file has
# more than one signal, the C<siglist> option must also be used, and there
# must only be one signal specified. For example:
#
# vcd = parse_vcd(file,
# use_stdout=1,
# siglist=['top.clk']
# )
#
# The time-value pairs are output as space-separated tokens, one per line.
# For example:
#
# 0 x
# 15 0
# 277 1
# 500 0
#
# Times are listed in the first column.
# Times units can be controlled by the C<timescale> option.
#
# =item only_sigs
#
# Parse a VCD file and return a reference to a data structure which
# includes only the hierarchical signal definitions. Parsing stops once
# all signals have been found. Therefore, no time-value data are
# included in the returned data structure. This is useful for
# analyzing signals and hierarchies.
#
# vcd = parse_vcd(file, only_sigs=1)
#
# =back
#
#
# =head2 list_sigs(file)
#
# Parse a VCD file and return a list of all signals in the VCD file.
# Parsing stops once all signals have been found. This is
# helpful for deciding how to limit what signals are parsed.
#
# Here is an example:
#
# signals = list_sigs('input.vcd')
#
# The signals are full hierarchical paths separated by the dot character
#
# top.chip.cpu.alu.status
# top.chip.cpu.alu.sum[15:0]
#
# =head2 get_timescale( )
#
# This returns a string corresponding to the timescale as specified
# by the C<$timescale> VCD keyword. It returns the timescale for
# the last VCD file parsed. If called before a file is parsed, it
# returns an undefined value. If the C<parse_vcd> C<timescale> option
# was used to specify a timescale, the specified value will be returned
# instead of what is in the VCD file.
#
# vcd = parse_vcd(file); # Parse a file first
# ts = get_timescale(); # Then query the timescale
#
# =head2 get_endtime( )
#
# This returns the last time found in the VCD file, scaled
# appropriately. It returns the last time for the last VCD file parsed.
# If called before a file is parsed, it returns an undefined value.
#
# vcd = parse_vcd(file); # Parse a file first
# et = get_endtime(); # Then query the endtime
#
# =head1 EXPORT
#
# Nothing is exported by default. Functions may be exported individually, or
# all functions may be exported at once, using the special tag C<:all>.
#
# =head1 DIAGNOSTICS
#
# Error conditions cause the program to raise an Exception.
#
# =head1 LIMITATIONS
#
# Only the following VCD keywords are parsed:
#
# $end $scope
# $enddefinitions $upscope
# $timescale $var
#
# The extended VCD format (with strength information) is not supported.
#
# The default mode of C<parse_vcd> is to load the entire VCD file into the
# data structure. This could be a problem for huge VCD files. The best solution
# to any memory problem is to plan ahead and keep VCD files as small as possible.
# When simulating, dump fewer signals and scopes, and use shorter dumping
# time ranges. Another technique is to parse only a small list of signals
# using the C<siglist> option; this method only loads the desired signals into
# the data structure. Finally, the C<use_stdout> option will parse the input VCD
# file line-by-line, instead of loading it into the data structure, and directly
# prints time-value data to STDOUT. The drawback is that this only applies to
# one signal.
#
# =head1 BUGS
#
# There are no known bugs in this module.
#
# =head1 SEE ALSO
#
# Refer to the following Verilog documentation:
#
# IEEE Standard for Verilog (c) Hardware Description Language
# IEEE Std 1364-2005
# Section 18.2, "Format of four-state VCD file"
#
# =head1 AUTHOR
#
# Originally written in Perl by Gene Sullivan (gsullivan@cpan.org)
# Translated into Python by Sameer Gauria (sgauria+python@gmail.com)
#
# =head1 COPYRIGHT AND LICENSE
#
# Copyright (c) 2012 Gene Sullivan, Sameer Gauria. All rights reserved.
#
# This module is free software; you can redistribute it and/or modify
# it under the same terms as Perl itself. See L<perlartistic|perlartistic>.
#
# =cut
# 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)
elif filterMethod == 'Manual':
# TODO: Validator needed
b = np.fromstring(str(self.textManualCoeffB.toPlainText()), sep=',')
a = np.fromstring(str(self.textManualCoeffA.toPlainText()), sep=',')
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':
flagManualCoeffA = False
flagManualCoeffB = False
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':
flagManualCoeffA = False
flagManualCoeffB = False
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':
flagManualCoeffA = False
flagManualCoeffB = False
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':
flagManualCoeffA = False
flagManualCoeffB = False
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
elif filterMethod == 'Manual':
flagManualCoeffA = True
flagManualCoeffB = True
flagFIRWindow = False
flagNumtaps = False
flagCutoff = False
flagWidth = False
flagPassZero = False
flagScale = False
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
else :
print('Not recognized filter description method')
# TODO: this is ugly, should be compacted in a cleaner structure!!
self.labelManualCoeffB.setVisible(flagManualCoeffB)
self.textManualCoeffB.setVisible(flagManualCoeffB)
self.labelManualCoeffA.setVisible(flagManualCoeffA)
self.textManualCoeffA.setVisible(flagManualCoeffA)
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 as exVE:
warningMessage = '%s' % exVE
except ZeroDivisionError as exZDE:
warningMessage = '%s' % exZDE
except RuntimeWarning as exRW:
warningMessage = '%s' % exRW
except signal.BadCoefficients as 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.comboFilterOverflow, 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.addItem("Manual") # define the coeff by hand
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)
# Manual configuration
self.labelManualCoeffB = QLabel('B Coeff:')
self.textManualCoeffB = QTextEdit()
self.textManualCoeffB.setText('1')
self.connect(self.textManualCoeffB, SIGNAL('textChanged()'), self.update_parameter_set)
self.connect(self.textManualCoeffB, SIGNAL('textChanged()'), self.on_parameter_change)
self.labelManualCoeffA = QLabel('A Coeff:')
self.textManualCoeffA = QTextEdit()
self.textManualCoeffA.setText('1')
self.connect(self.textManualCoeffA, SIGNAL('textChanged()'), self.update_parameter_set)
self.connect(self.textManualCoeffA, SIGNAL('textChanged()'), 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)
hboxManualCoeffB = QHBoxLayout()
hboxManualCoeffB.addWidget(self.labelManualCoeffB)
hboxManualCoeffB.addWidget(self.textManualCoeffB)
hboxManualCoeffB.setStretch(0,1)
hboxManualCoeffB.setStretch(1,1)
hboxManualCoeffA = QHBoxLayout()
hboxManualCoeffA.addWidget(self.labelManualCoeffA)
hboxManualCoeffA.addWidget(self.textManualCoeffA)
hboxManualCoeffA.setStretch(0,1)
hboxManualCoeffA.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,
hboxManualCoeffB, hboxManualCoeffA,
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
from scope import *
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 generate_stimulus(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
#
grid = self.cbGridStimulus.isChecked()
self.x = self.generate_stimulus()
print('Generate a basic signal using the generator')
stimulusWave = Waveform(value = self.x,
label = 'Stimulus',
color = '#00ff00')
scopeTime(self.figStimulus, [stimulusWave], grid)
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.figStimulus = Figure()
self.canvasStimulus = FigureCanvas(self.figStimulus)
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 Libre-FDATool.
#
# Libre-FDATool 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, either version 3 of the License, or
# (at your option) any later version.
#
# Libre-FDATool 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 Libre-FDATool. If not, see <http://www.gnu.org/licenses/>.
#
# 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 *
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()
simulatorBeginSignal = pyqtSignal()
simulatorEndSignal = pyqtSignal()
def __init__(self):
# TODO: Change to workspace directory!!
self.appPath = os.getcwd()
self.workPath = '/tmp'
os.chdir(self.workPath)
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.simulatorBeginSignal.connect(self.on_simulator_begin)
self.simulatorEndSignal.connect(self.on_simulator_end)
# Choose GHDL as default
self.comboSimulatorEngine.setCurrentIndex(1)
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):
# TODO: point to the correct path using smart method!!
exitAction = QAction(QIcon('/usr/share/librefdatool/data/images/exit_48.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(qApp.quit)
exitAction.setToolTip('Exit Libre-FDATool')
exportAction = QAction(QIcon('/usr/share/librefdatool/data/images/export_48.png'), 'Export', self);
exportAction.setShortcut('Ctrl+E');
exportAction.triggered.connect(self.exportHDL)
exportAction.setToolTip('Export HDL Code')
simulatorAction = QAction(QIcon('/usr/share/librefdatool/data/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()), str(self.comboSimulatorLanguage.currentText()),
str(self.comboSimulatorEngine.currentText()), str(self.comboFilterStructure.currentText()),
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 on_simulator_begin(self):
#QMessageBox.information(self, 'Simulator Begin',
# 'This is only a message', QMessageBox.Ok)
self.status_text.setText('Simulation started...')
def on_simulator_end(self):
#QMessageBox.information(self, 'Simulator End',
# 'This is only a message', QMessageBox.Ok)
self.status_text.setText('Simulation ended!!')
def main():
app = QApplication(sys.argv)
form = LibreFDATool()
form.show()
app.exec_()
if __name__ == "__main__":
main()
# This file is part of Libre-FDATool.
#
# Libre-FDATool 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, either version 3 of the License, or
# (at your option) any later version.
#
# Libre-FDATool 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 Libre-FDATool. If not, see <http://www.gnu.org/licenses/>.
#
# 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.2'
__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 *
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()
simulatorBeginSignal = pyqtSignal()
simulatorEndSignal = pyqtSignal()
def __init__(self):
# TODO: Change to workspace directory!!
self.appPath = os.getcwd()
self.workPath = '/tmp'
os.chdir(self.workPath)
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.simulatorBeginSignal.connect(self.on_simulator_begin)
self.simulatorEndSignal.connect(self.on_simulator_end)
# Choose GHDL as default
self.comboSimulatorEngine.setCurrentIndex(1)
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):
# TODO: point to the correct path using smart method!!
exitAction = QAction(QIcon('/usr/share/librefdatool/data/images/exit_48.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(qApp.quit)
exitAction.setToolTip('Exit Libre-FDATool')
exportAction = QAction(QIcon('/usr/share/librefdatool/data/images/export_48.png'), 'Export', self);
exportAction.setShortcut('Ctrl+E');
exportAction.triggered.connect(self.exportHDL)
exportAction.setToolTip('Export HDL Code')
simulatorAction = QAction(QIcon('/usr/share/librefdatool/data/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()), str(self.comboSimulatorLanguage.currentText()),
str(self.comboSimulatorEngine.currentText()), str(self.comboFilterStructure.currentText()),
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 on_simulator_begin(self):
#QMessageBox.information(self, 'Simulator Begin',
# 'This is only a message', QMessageBox.Ok)
self.status_text.setText('Simulation started...')
def on_simulator_end(self):
#QMessageBox.information(self, 'Simulator End',
# 'This is only a message', QMessageBox.Ok)
self.status_text.setText('Simulation ended!!')
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.
'''
class Waveform:
def __init__(self, value=[0], label='waveform', color='#000000',
linestyle='-', marker='o', markersize=8):
self.value = value
self.label = label
self.color = color
self.linestyle = linestyle
self.marker = marker
self.markersize = markersize
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 as exVE:
warningMessage = '%s' % exVE
except ZeroDivisionError as exZDE:
warningMessage = '%s' % exZDE
except RuntimeWarning as 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 as exVE:
warningMessage = '%s' % exVE
except ZeroDivisionError as exZDE:
warningMessage = '%s' % exZDE
except RuntimeWarning as 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 scopeTime(figure, waveform, 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 Time')
figure.clear()
scopeTimeSubplot = figure.add_subplot(111)
scopeTimeSubplot.set_ylabel('Value')
scopeTimeSubplot.set_xlabel('Sample')
scopeTimeSubplot.set_title(r'Time Scope')
scopeTimeSubplot.grid(grid)
for ii in range(len(waveform)):
scopeTimeSubplot.plot(waveform[ii].value,
color = waveform[ii].color,
label = waveform[ii].label,
linestyle = waveform[ii].linestyle,
marker = waveform[ii].marker,
markersize = waveform[ii].markersize)
scopeTimeSubplot.legend().draggable(state=True, use_blit=True)
def scopePower(figure, waveform, grid):
'''this method shows the estimated power spectrum for a signal:
* s: channel-1 assigned signal (blue)
'''
print('Plotting Power Spectrum...')
figure.clear()
scopePowerSubplot = figure.add_subplot(111)
scopePowerSubplot.set_ylabel('Power (dB)')
scopePowerSubplot.set_xlabel('Normalized Frequency')
scopePowerSubplot.set_title(r'Signal Power')
scopePowerSubplot.grid(grid)
for ii in range(len(waveform)):
Ps,fs = mlab.psd(waveform[ii].value)
scopePowerSubplot.plot(fs, 10*log10(abs(Ps)),
color = waveform[ii].color,
label = waveform[ii].label,
linestyle = waveform[ii].linestyle)
scopePowerSubplot.legend().draggable(state=True, use_blit=True)
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 Verilog_VCD import *
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, language,
engine, name,
busX, busY, busC,
scalingX, scalingC):
self.name = name
self.structure = structure
self.language = language
self.engine = engine
#TODO: debugging prints
print('structure', structure)
print('language', language)
print('engine', engine)
print('name', name)
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(x)
#***********************************************#
# 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.language == 'VHDL':
structure = self.structure
name = self.name
# TODO: temporary assign of style depending on engine
if self.engine == 'GHDL':
style = 'rolled'
elif self.engine == 'Icarus Verilog':
style = 'unrolled'
# 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, structure, style=style))
hdlFile.write('\n')
# *** DECLARE INTERNAL SIGNALS ***
hdlFile.write(hdl.signalZ(self.M, self.N, busX, busY, busC, structure, style=style))
hdlFile.write('\n')
hdlFile.write(hdl.signalC(self.M, self.N, busC, structure, style=style))
hdlFile.write('\n')
hdlFile.write(hdl.signalAdders(self.M, self.N, busX, busY, busC, structure, style=style))
hdlFile.write('\n')
hdlFile.write(hdl.signalProducts(self.M, self.N, busX, busY, busC, structure, style=style))
hdlFile.write('\n')
hdlFile.write(hdl.signalFeedback(self.M, self.N, busX, busY, busC, structure, style=style))
hdlFile.write('\n')
hdlFile.write("-- Begin Architecture\n")
hdlFile.write("begin\n\n")
hdlFile.write(hdl.assignCoeff(M, N, self.icoefB, self.coefB,
self.icoefA, self.coefA, structure, style=style))
hdlFile.write("\n")
hdlFile.write(hdl.sequentialBlock(M, N, clkEdge='posedge', rstActive='high', style=style))
hdlFile.write("\n")
# Products
hdlFile.write(hdl.arithProduct(M, N,
busX, busY, busC,
structure, style=style))
hdlFile.write("\n")
# Sums
hdlFile.write(hdl.arithAdders(M, N,
self.busX, self.busY, self.busC,
structure, style=style))
hdlFile.write("\n")
hdlFile.write(hdl.connectBlocks(M, N,
self.busX, self.busY, self.busC,
structure, style=style))
hdlFile.write('end {!s};\n'.format(structure))
hdlFile.close()
elif self.language == 'Verilog':
structure = self.structure
# 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(structure))
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 language not recognized\n");
return 0
def _generateTB(self, x):
#if self.language == 'vhdl':
# 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
hdl = snippets()
busX = self.busX[0] + self.busX[1]
busY = self.busY[0] + self.busY[1]
name = self.name
xb = self._quantizer(x, self.busX, staircase='midtread')
if self.engine == 'Icarus Verilog':
tbFile = open('tb_{!s}.v'.format(name),'w')
tbFile.write(hdl.verilogTestBench(name, xb, x, busX, busY))
tbFile.close()
elif self.engine == 'GHDL':
tbFile = open('tb_{!s}.vhd'.format(name),'w')
tbFile.write(hdl.vhdlTestBench(name, xb, x, busX, busY))
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
if staircase == 'midtread':
delta = 0.5
elif staircase == 'midriser':
delta = 0
else:
print("Staircase model for quantizer unknown: using default")
delta = 0.5
# Convert the normalized signal to a integer value
signalScaled = signalNorm*(2**(bus[1])) + delta
signalInt = np.floor(signalScaled)
# 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, stimulus):
name = self.name
totalSamples = len(stimulus)
timeStep = 50
if self.language == 'Verilog':
dutExtension = 'v'
elif self.language == 'VHDL':
dutExtension = 'vhd'
else:
print('Unknown model: assuming verilog')
dutExtension = 'v'
# Check if verilog/vhdl filter description is available TBD: make it a variable!!!!!!!!!!!!!!!!
if not os.path.isfile('{!s}.{!s}'.format(name, dutExtension)):
print('File not found: Run generation first')
return None
# Clean design
if os.path.isfile('{!s}'.format(name)):
print('Existing compiled design: erase!! ')
cmd = 'rm {!s}'.format(name)
os.system(cmd)
if self.engine == 'Icarus Verilog':
# 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(name, name, dutExtension, name)
os.system(cmd)
cmd = 'vvp {!s}'.format(name)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
elif self.engine == 'GHDL':
#Running GHDL
stopTime = (5 + totalSamples)*timeStep
# Analyze the UUT
cmd = 'ghdl -a {!s}.vhd'.format(name)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
# Analyze the TestBench
cmd = 'ghdl -a tb_{!s}.vhd'.format(name)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
# Build an executable file
cmd = 'ghdl -e tb_{!s}'.format(name)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print('GHDL executed')
# Run the executable
cmd = 'ghdl -r tb_{!s} --vcd={!s}.vcd --stop-time={!s}ns'.format(name, name, stopTime)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print('GHDL runned')
# *****************************************************************************
#vcdDebug = parse_vcd('{!s}.vcd'.format(name),
# only_sigs=1
# )
#print(vcdDebug)
if self.engine == 'Icarus Verilog':
topName = 'tb_{!s}'.format(name)
timeScale = 1
elif self.engine == 'GHDL':
topName = 'uut'
timeScale = 1000000
print('Parsing VCD')
vcd = parse_vcd('{!s}.vcd'.format(name),
#use_stdout=1,
siglist=['{!s}sig_out[{!s}:0]'.format(
topName, self.busY[0] + self.busY[1] - 1)]
)
for key in sorted(vcd):
vcdKey = key
print('Parsed VCD')
print(vcd[vcdKey]['tv'])
vcdParsedOutput = []
#vcdBinaryOutput = []
outCurrentTime = 0
vcdCurrentValue = vcd[vcdKey]['tv'][0][1]
binOffset = self.busY[0] + self.busY[1] - len(vcdCurrentValue)
for jj in range(binOffset):
vcdCurrentValue = '0' + vcdCurrentValue
for ii in range(len(vcd[vcdKey]['tv'])):
vcdNextTime = vcd[vcdKey]['tv'][ii][0]
vcdNextTime = vcdNextTime/timeScale
vcdNextValue = vcd[vcdKey]['tv'][ii][1]
while vcdNextTime > outCurrentTime:
a = BitArray(bin=vcdCurrentValue)
#vcdBinaryOutput.append(vcdCurrentValue)
vcdParsedOutput.append(a.int/float(2**(self.busY[1])))
vcdCurrentValue = vcdNextValue
binOffset = self.busY[0] + self.busY[1] - len(vcdCurrentValue)
for jj in range(binOffset):
vcdCurrentValue = '0' + vcdCurrentValue
outCurrentTime += timeStep
print('Signal reconstructed')
# remove the output samples from filter initialization
for ii in range(5):
vcdParsedOutput.pop(0)
#vcdBinaryOutput.pop(0)
# Expand signal to match stimulus length
for ii in range(totalSamples - len(vcdParsedOutput)):
vcdParsedOutput.append(vcdParsedOutput[len(vcdParsedOutput)-1])
connect_sample_out = np.zeros(len(vcdParsedOutput))
for ii in range(len(vcdParsedOutput)):
connect_sample_out[ii] = vcdParsedOutput[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()
simulatorBeginSignal = pyqtSignal()
simulatorEndSignal = pyqtSignal()
def on_simulator_draw(self):
""" Redraws the figure
"""
# create waveforms
HDLWave = Waveform(value = self.yhdl,
label = 'HDL',
color = '#ff0000')
floatWave = Waveform(value = self.yfloat,
label = 'float',
color = '#0000ff')
simulatorWaves = [floatWave, HDLWave]
selectedPlot = str(self.comboSimulatorScope.currentText())
grid = self.cbGridSimulator.isChecked()
if selectedPlot == 'Time Plot':
scopeTime(self.figSimulator, simulatorWaves, grid)
elif selectedPlot == 'Error Plot':
scopeError(self.figSimulator, self.yfloat, self.yhdl, grid)
elif selectedPlot == 'Power Spectrum':
scopePower(self.figSimulator, simulatorWaves, grid)
else:
scopeTime(self.figSimulator, simulatorWaves, 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,
engine, structure,
busX, busY, busC,
scalingX, scalingC):
""" Redraws the figure
"""
# Get the coefficients
warningMessage = ''
warnings.simplefilter('error')
try:
self.simulatorBeginSignal.emit()
self.yfloat = signal.lfilter(b, a, x)
self.yhdl = self.simfilter(b, a, x,
structure, language,
engine, name,
busX, busY, busC,
scalingX, scalingC)
self.simulatorEndSignal.emit()
except ValueError as exVE:
warningMessage = '%s' % exVE
except ZeroDivisionError as exZDE:
warningMessage = '%s' % exZDE
except RuntimeWarning as 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("VHDL")
self.comboSimulatorLanguage.addItem("Verilog")
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_language_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,5)
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()
def on_language_modified(self):
# TODO: provisional, check the structure change and force to DF1 Trans
activeLanguage = str(self.comboSimulatorLanguage.currentText())
if activeLanguage == 'VHDL':
self.on_simulator_modified()
else:
QMessageBox.information(self, 'Simulation Language',
'Sorry, but %s is not supported yet!'
% activeLanguage,
QMessageBox.Ok)
self.comboSimulatorLanguage.setCurrentIndex(0)
# This file is part of Libre-FDATool.
#
# Libre-FDATool 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, either version 3 of the License, or
# (at your option) any later version.
#
# Libre-FDATool 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 Libre-FDATool. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
import sys
import datetime
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, structure, style='unrolled'):
#TBD: include the appropriated realization diagram
now = datetime.datetime.now()
archHeadDict = {
'Name': name,
'Structure': structure,
'TimePrint': now.strftime("%Y-%m-%d %H:%M")
}
archHeadString = (
'architecture %(Structure)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'
'-- This file has been generated with Libre-FDATool\n'
'-- Creation Time: %(TimePrint)s\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 = '{!s}({!s} downto {!s}) <= (others => {!s}({!s}));\n'.format(nameY, pY+qY-1, pY+qY-pDiff, nameX, 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 = '{!s}({!s} downto 0) <= (others => \'0\');\n'.format(nameY, 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 = (
'-- Convert Fixed Point to %(nameY)s from %(nameX)s\n'
'%(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'
'\n'
)
return convertFPString % convertFPDict
def sequentialBlock(self, M, N, clkEdge='posedge', rstActive='high', style='unrolled'):
# 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,
'M_2': M - 2,
'N_2': N - 2
}
if M >= 1 or N >= 1:
if style == 'unrolled':
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 <= (others => \'0\');\n' % {'ii': ii}
for ii in range(N-1):
seqString += ' za%(ii)u <= (others => \'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'
)
elif style == 'rolled':
seqString = (
'----------------------------------\n'
'-- Sequential logic description --\n'
'----------------------------------\n'
'\n'
)
#arithProductString += 'pb_temp(%(ii)u) <= v * b%(ii)u;\n' % {'ii': ii}
#for x in 0 to 7 generate
#
#end generate
if M > 1:
seqString += (
'-- Sequential delay chain for the B block\n'
'seq_b_block: for x in 0 to %(M_2)u generate\n'
' reg_b: process (clk)\n'
' begin\n'
' if (clk\'event and clk = \'%(boolEdge)s\') then\n'
' if (rst = \'%(boolRst)s\') then\n'
' zb(x) <= (others => \'0\');\n'
' else\n'
' zb(x) <= zb_next(x);\n'
' end if;\n'
' end if;\n'
' end process reg_b;\n'
'end generate seq_b_block;\n'
'\n'
)
if N > 1:
seqString += (
'-- Sequential delay chain for the A block\n'
'seq_a_block: for x in 0 to %(N_2)u generate\n'
' reg_a: process (clk)\n'
' begin\n'
' if (clk\'event and clk = \'%(boolEdge)s\') then\n'
' if (rst = \'%(boolRst)s\') then\n'
' za(x) <= (others => \'0\');\n'
' else\n'
' za(x) <= za_next(x);\n'
' end if;\n'
' end if;\n'
' end process reg_a;\n'
'end generate seq_a_block;\n'
'\n'
)
return seqString % seqDict
def signalZ(self, M, N, busX, busY, busC, structure, style='unrolled'):
signalZString = '-- Z^-1 delay blocks\n'
if structure == 'Direct_Form_I_Transposed':
if style == 'unrolled':
# Z blocks in the b coefficients side
for ii in range(M-1):
signalZString += 'signal zb%(ii)u, zb%(ii)u_next: signed(%(bus)u downto 0);\n' % {'ii': ii, 'bus': busX + busC -1 -1}
signalZString += '\n'
# Z blocks in the a coefficients side
for ii in range(N-1):
if ii != 0:
bus = busX + busC -1 -1
else:
bus = busX -1
signalZString += 'signal za%(ii)u, za%(ii)u_next: signed(%(bus)u downto 0);\n' % {'ii': ii, 'bus': bus}
signalZString += '\n'
elif style == 'rolled':
if M > 1:
signalZString += 'type zb_array is array (0 to %(aMax)u) of signed(%(bus)u downto 0);\n' % {'aMax': M -2, 'bus': busX + busC -1 -1}
signalZString += 'signal zb, zb_next: zb_array;\n'
if N > 1:
signalZString += 'type za_array is array (0 to %(aMax)u) of signed(%(bus)u downto 0);\n' % {'aMax': N -2, 'bus': busX + busC -1 -1}
signalZString += 'signal za, za_next: za_array;\n'
signalZString += '\n'
return signalZString
def signalC(self, M, N, busC, structure, style='unrolled'):
signalCString = '-- Filter constants\n'
if structure == 'Direct_Form_I_Transposed':
if style == 'unrolled':
# Z blocks in the b coefficients side
for ii in range(M):
signalCString += 'signal b%(ii)u: signed(%(bus)u downto 0);\n' % {'ii': ii, 'bus': busC - 1}
signalCString += '\n'
# Z blocks in the a coefficients side
for ii in range(N):
if ii != 0:
signalCString += 'signal a%(ii)u: signed(%(bus)u downto 0);\n' % {'ii': ii, 'bus': busC - 1}
signalCString += '\n'
elif style == 'rolled':
if M > 0:
signalCString += 'type b_array is array (0 to %(aMax)u) of signed(%(bus)u downto 0);\n' % {'aMax': M -1, 'bus': busC -1}
signalCString += 'signal b: b_array;\n'
if N > 1:
signalCString += 'type a_array is array (0 to %(aMax)u) of signed(%(bus)u downto 0);\n' % {'aMax': N -1, 'bus': busC -1}
signalCString += 'signal a: a_array;\n'
return signalCString
def signalProducts(self, M, N, busX, busY, busC, structure, style='unrolled'):
signalProductString = '-- Filter Products\n'
if structure == 'Direct_Form_I_Transposed':
if style == 'unrolled':
# Products from B coeff
for ii in range(M):
signalProductString += 'signal pb%(ii)u: signed(%(bus)u downto 0);\n' % {'ii': ii, 'bus': busX + busC -1 -1}
signalProductString += '\n'
# Products from A coeff
for ii in range(N):
if ii != 0:
signalProductString += 'signal pa%(ii)u: signed(%(bus)u downto 0);\n' % {'ii': ii, 'bus': busX + busC -1 -1}
signalProductString += '\n'
# Temporal Products from B coeff
for ii in range(M):
signalProductString += 'signal pb%(ii)u_temp: signed(%(bus)u downto 0);\n' % {'ii': ii, 'bus': busX + busC -1}
signalProductString += '\n'
# Temporal Products from A coeff
for ii in range(N):
if ii != 0:
signalProductString += 'signal pa%(ii)u_temp: signed(%(bus)u downto 0);\n' % {'ii': ii, 'bus': busX + busC -1}
signalProductString += '\n'
elif style == 'rolled':
if M > 0:
signalProductString += 'type product_b_array is array (0 to %(Mmax)u) of signed(%(bus)u downto 0);\n' % {'Mmax': M -1, 'bus': busX + busC -1 -1}
signalProductString += 'signal pb: product_b_array;\n'
signalProductString += 'type product_b_temp_array is array (0 to %(Mmax)u) of signed(%(bus)u downto 0);\n' % {'Mmax': M -1, 'bus': busX + busC -1}
signalProductString += 'signal pb_temp: product_b_temp_array;\n'
if N > 1:
signalProductString += 'type product_a_array is array (0 to %(Mmax)u) of signed(%(bus)u downto 0);\n' % {'Mmax': N -2, 'bus': busX + busC -1 -1}
signalProductString += 'signal pa: product_a_array;\n'
signalProductString += 'type product_a_temp_array is array (0 to %(Mmax)u) of signed(%(bus)u downto 0);\n' % {'Mmax': N -2, 'bus': busX + busC -1}
signalProductString += 'signal pa_temp: product_a_temp_array;\n'
return signalProductString
def signalAdders(self, M, N, busX, busY, busC, structure, style='unrolled'):
signalAddString = '-- Filter Adders\n'
if structure == 'Direct_Form_I_Transposed':
if style == 'unrolled':
# Adders in the b coefficients side
for ii in range(M-1):
signalAddString += 'signal sb%(ii)u: signed(%(bus)u downto 0);\n' % {'ii': ii, 'bus': busX + busC -1 -1}
signalAddString += '\n'
# Adders in the a coefficients side
for ii in range(N-1):
if ii != 0:
bus = busX + busC -1 -1
else:
bus = busX -1
signalAddString += 'signal sa%(ii)u: signed(%(bus)u downto 0);\n' % {'ii': ii, 'bus': bus}
signalAddString += '\n'
if style == 'rolled':
if M > 1:
signalAddString += 'type sum_b_array is array (0 to %(Mmax)u) of signed(%(bus)u downto 0);\n' % {'Mmax': M -2, 'bus': busX + busC -1 -1}
signalAddString += 'signal sb: sum_b_array;\n'
if N > 1:
signalAddString += 'type sum_a_array is array (0 to %(Mmax)u) of signed(%(bus)u downto 0);\n' % {'Mmax': N -2, 'bus': busX + busC -1 -1}
signalAddString += 'signal sa: sum_a_array;\n'
return signalAddString
def signalFeedback(self, M, N, busX, busY, busC, structure, style='unrolled'):
signalFeedbackString = ''
if structure == 'Direct_Form_I_Transposed':
# the same for rolled and unrolled
if N > 0:
signalFeedbackString += '-- Feedback loop accumulator\n'
signalFeedbackString += 'signal v: signed(%(bus)u downto 0);\n' % {'bus': busX -1}
if N > 1:
signalFeedbackString += 'signal add_in: signed(%(bus)u downto 0);\n' % {'bus': busX + busC -1 -1}
return signalFeedbackString
def assignCoeff(self, M, N, bCoeffBin, bCoeffFloat,
aCoeffBin, aCoeffFloat, structure, style='unrolled'):
if structure == 'Direct_Form_I_Transposed':
if style == 'unrolled':
assignCoeffString = '-- Assign Coefficients\n'
# Z blocks in the b coefficients side
for ii in range(M):
assignCoeffString += 'b%(ii)u <= \"%(BCoeffBin)s\"; -- %(BCoeffFloat)f\n' % {'ii': ii, 'BCoeffBin': bCoeffBin[ii], 'BCoeffFloat': bCoeffFloat[ii]}
assignCoeffString += '\n'
# Z blocks in the a coefficients side
for ii in range(N):
if ii != 0:
assignCoeffString += 'a%(ii)u <= \"%(ACoeffBin)s\"; -- %(ACoeffFloat)f\n' % {'ii': ii, 'ACoeffBin': aCoeffBin[ii], 'ACoeffFloat': aCoeffFloat[ii]}
assignCoeffString += '\n'
if style == 'rolled':
assignCoeffString = '-- Assign Coefficients\n'
# Z blocks in the a coefficients side
for ii in range(M):
assignCoeffString += 'b(%(ii)u) <= \"%(BCoeffBin)s\"; -- %(BCoeffFloat)f\n' % {'ii': ii, 'BCoeffBin': bCoeffBin[ii], 'BCoeffFloat': bCoeffFloat[ii]}
assignCoeffString += '\n'
for ii in range(N -1):
assignCoeffString += 'a(%(ii)u) <= \"%(ACoeffBin)s\"; -- %(ACoeffFloat)f\n' % {'ii': ii, 'ACoeffBin': aCoeffBin[ii+1], 'ACoeffFloat': aCoeffFloat[ii+1]}
assignCoeffString += '\n'
return assignCoeffString
def arithProduct(self, M, N, busX, busY, busC, structure, style='unrolled'):
if structure == 'Direct_Form_I_Transposed':
if style == 'unrolled':
arithProductString = '-- Product Arithmetics\n'
# Execute products from B side
for ii in range(M):
arithProductString += 'pb%(ii)u_temp <= v * b%(ii)u;\n' % {'ii': ii}
arithProductString += 'pb%(ii)u <= pb%(ii)u_temp(%(bus)u downto 0);\n' % {'ii': ii, 'bus': busX + busC -1 -1}
#arithProductString += 'pb%(ii)u <= pb_temp(%(ii)u);\n' % {'ii': ii, 'bus': busX + busC -1 -1}
arithProductString += '\n'
# Execute products from A side
for ii in range(N):
if ii != 0:
arithProductString += 'pa%(ii)u_temp <= v * a%(ii)u;\n' % {'ii': ii}
arithProductString += 'pa%(ii)u <= pa%(ii)u_temp(%(bus)u downto 0);\n' % {'ii': ii, 'bus': busX + busC -1 -1}
arithProductString += '\n'
elif style == 'rolled':
arithProductString = ''
return arithProductString
def arithAdders(self, M, N, busX, busY, busC, structure, style='unrolled'):
if structure == 'Direct_Form_I_Transposed':
if style == 'unrolled':
arithAddersString = '-- Adder Arithmetics\n'
# Z blocks in the b coefficients side
for ii in range(M-1):
arithAddersString += 'sb%(ii)u <= pb%(ii)u + zb%(ii)u;\n' % {'ii': ii}
arithAddersString += '\n'
# Z blocks in the a coefficients side
for ii in range(N-1):
if ii == 0:
arithAddersString += 'sa%(ii)u <= sig_in + za%(ii)u;\n' % {'ii': ii}
else:
arithAddersString += 'sa%(ii)u <= pa%(ii)u + za%(ii)u;\n' % {'ii': ii}
arithAddersString += '\n'
elif style == 'rolled':
arithAddersString = '\n'
return arithAddersString
def connectBlocks(self, M, N, busX, busY, busC, structure, style='unrolled'):
if structure == 'Direct_Form_I_Transposed':
if style == 'unrolled':
connectBlocksString = '-- Structure Blocks Connection\n'
# Z blocks in the b coefficients side
for ii in range(M):
if ii == 0:
if M == 1:
outputStage = 'pb0'
else:
outputStage = 'sb0'
connectBlocksString += self.convertFixedPoint(outputStage, busC[0] + busX[0] -1, busC[1] + busX[1],
'sig_out', busY[0], busY[1])
else:
if ii == (M-1):
sourceTypeB = 'p'
else:
sourceTypeB = 's'
bConnectDict = {
'SrcType': sourceTypeB,
'Src': ii,
'Dst': ii - 1
}
connectBlocksString += 'zb%(Dst)u_next <= %(SrcType)sb%(Src)u;\n' % bConnectDict
connectBlocksString += '\n'
for ii in range(N):
if ii == 0:
if N == 1:
connectBlocksString += 'v <= sig_in;\n'
else:
connectBlocksString += 'v <= sa0;\n'
elif ii == 1:
if ii == (N-1):
firstStageA = 'pa1'
else:
firstStageA = 'sa1'
connectBlocksString += self.convertFixedPoint(firstStageA, busC[0] + busX[0] -1, busC[1] + busX[1],
'za0_next', busX[0], busX[1])
else:
if ii == (N-1):
sourceTypeA = 'p'
else:
sourceTypeA = 's'
aConnectDict = {
'SrcType': sourceTypeA,
'Src': ii,
'Dst': ii - 1
}
connectBlocksString += 'za%(Dst)u_next <= %(SrcType)sa%(Src)u;\n' % aConnectDict
connectBlocksString += '\n'
if style == 'rolled':
connectDict = {
'bus': busX[0] + busX[1] + busC[0] + busC[1] -1 -1,
'M_1': M - 1,
'M_2': M - 2,
'N_2': N - 2
}
connectBlocksString = (
'----------------------------------\n'
'-- Processing logic description --\n'
'----------------------------------\n'
'\n'
)
if N == 1:
connectBlocksString += (
'-- Bypassing the A processing block\n'
'v <= sig_in;\n'
'\n'
)
else:
connectBlocksString += self.convertFixedPoint('sig_in', busX[0], busX[1],
'add_in', busC[0] + busX[0] -1, busC[1] + busX[1])
connectBlocksString += (
'-- Processing block for the Filter structure A side\n '
'connect_a_block: for n in 0 to %(N_2)u generate\n'
' -- Calculate products being generated\n'
' pa_temp(n) <= v * a(n);\n'
' pa(n) <= pa_temp(n)(%(bus)u downto 0);\n'
' -- Calculate sums being generated\n'
' -- ... input adder\n'
' add_a_block: if (n = 0) generate\n'
' sa(n) <= add_in + za(n);\n'
' end generate add_a_block;\n'
' -- ... the other adders in the loop\n'
' add_in_block: if (n /= 0) generate\n'
' sa(n) <= pa(n-1) + za(n);\n'
' end generate add_in_block;\n'
' -- Generate za_next connections\n'
' -- ... those halfway in the loop\n'
' mid_a_tap: if (n < %(N_2)u) generate\n'
' za_next(n) <= sa(n+1);\n'
' end generate mid_a_tap;\n'
' -- ... the final structure tap\n'
' final_a_tap: if (n = %(N_2)u) generate\n'
' za_next(n) <= pa(n);\n'
' end generate final_a_tap;\n'
'end generate connect_a_block;\n'
'\n'
)
connectBlocksString += self.convertFixedPoint('sa(0)', busC[0] + busX[0] -1, busC[1] + busX[1],
'v', busX[0], busX[1])
if M == 1:
connectBlocksString += (
'-- Calculate the only product\n'
'pb_temp(0) <= v * b(0);\n'
'pb(0) <= pb_temp(0)(%(bus)u downto 0);\n'
'\n'
)
connectBlocksString += self.convertFixedPoint('pb(0)', busC[0] + busX[0] -1, busC[1] + busX[1],
'sig_out', busY[0], busY[1])
else:
connectBlocksString += (
'-- Processing block for the Filter structure B side\n '
'process_b_block: for n in 0 to %(M_1)u generate\n'
' -- Calculate products being generated\n'
' pb_temp(n) <= v * b(n);\n'
' pb(n) <= pb_temp(n)(%(bus)u downto 0);\n'
' -- Calculate sums being generated\n'
' add_b_block: if (n < %(M_1)u) generate\n'
' sb(n) <= pb(n) + zb(n);\n'
' end generate add_b_block;\n'
' -- Calculate values for zb_next\n'
' -- ... those halfway in the loop\n'
' mid_b_tap: if (n < %(M_2)u) generate\n'
' zb_next(n) <= sb(n+1);\n'
' end generate mid_b_tap;\n'
' -- ... final structure\n'
' final_b_tap: if (n = %(M_2)u) generate\n'
' zb_next(n) <= pb(n+1);\n'
' end generate final_b_tap;\n'
'end generate process_b_block;\n'
'\n'
)
connectBlocksString += self.convertFixedPoint('sb(0)', busC[0] + busX[0] -1, busC[1] + busX[1],
'sig_out', busY[0], busY[1])
connectBlocksString = connectBlocksString % connectDict
return connectBlocksString
def verilogTestBench(self, name, stimulusBin, stimulusFloat, busX, busY):
# Write Verilog Dictionary
testBenchDict = {
'Name': name,
'BusX': busX,
'BusY': busY,
'MSBX': busX - 1,
'MSBY': busY - 1,
'ClkPosWidth': 25,
'ClkNegWidth': 25,
}
testBenchString = (
'// This file has been generated with Libre-FDATool\n'
'module tb_%(Name)s;\n'
'\n'
'reg clk;\n'
'reg rst;\n'
'reg [%(MSBX)u:0] sig_in;\n'
'wire [%(MSBY)u:0] sig_out;\n'
'\n'
'%(Name)s dut(\n'
' clk,\n'
' rst,\n'
' sig_in,\n'
' sig_out\n'
');\n'
'\n'
'always begin\n'
' clk <= 1;\n'
' #%(ClkPosWidth)u;\n'
' clk <= 0;\n'
' #%(ClkNegWidth)u;\n'
'end\n'
'\n'
'\n'
'initial begin\n'
' $dumpfile(\"%(Name)s.vcd\");\n'
' $dumpvars;\n'
'end\n'
'\n'
'initial begin\n'
' sig_in <= %(BusX)u\'b0; // signal is initially zero\n'
' rst <= 1\'b1; #100;\n'
' rst <= 1\'b0; #150;\n'
) % testBenchDict
for ii in range(len(stimulusBin)):
stimulusDict = {
'BusX': busX,
'CoeffBin': stimulusBin[ii],
'CoeffFloat': stimulusFloat[ii]
}
tempString = ' #50; sig_in <= %(BusX)u\'b%(CoeffBin)s; // %(CoeffFloat)f\n'
testBenchString += tempString % stimulusDict
testBenchString += (
' $finish;\n'
'end\n'
'\n'
'\n'
'endmodule\n'
)
return testBenchString
def vhdlTestBench(self, name, stimulusBin, stimulusFloat, busX, busY):
# Write Verilog Dictionary
testBenchDict = {
'Name': name,
'BusX': busX,
'BusY': busY,
'MSBX': busX - 1,
'MSBY': busY - 1,
'ClkPosWidth': 25,
'ClkNegWidth': 25,
}
testBenchString = (
'-- This file has been generated with Libre-FDATool\n'
'LIBRARY ieee;\n'
'USE ieee.std_logic_1164.ALL;\n'
'USE ieee.numeric_std.all;\n'
'\n'
'ENTITY tb_%(Name)s IS\n'
'END tb_%(Name)s;\n'
'\n'
'ARCHITECTURE behavior OF tb_%(Name)s IS\n'
' -- Component Declaration for the Unit Under Test (UUT)\n'
' COMPONENT %(Name)s\n'
' PORT(\n'
' clk: IN std_logic;\n'
' rst: IN std_logic;\n'
' sig_in: IN signed(%(MSBX)u downto 0);\n'
' sig_out: OUT signed(%(MSBY)u downto 0)\n'
' );\n'
' END COMPONENT;\n'
'\n'
' -- Signal Declaration\n'
' signal clk : std_logic := \'0\';\n'
' signal rst : std_logic := \'1\';\n'
' signal sig_in : signed(%(MSBX)u downto 0);\n'
' signal sig_out : signed(%(MSBY)u downto 0);\n'
'\n'
'BEGIN\n'
' -- Instantiate the Unit Under Test (UUT)\n'
' uut: %(Name)s PORT MAP (\n'
' clk => clk,\n'
' rst => rst,\n'
' sig_in => sig_in,\n'
' sig_out => sig_out\n'
' );\n'
'\n'
' clk_process : process\n'
' begin\n'
' clk <= \'1\';\n'
' wait for %(ClkPosWidth)u ns;\n'
' clk <= \'0\';\n'
' wait for %(ClkNegWidth)u ns;\n'
' end process;'
'\n'
' stimulus_process : process\n'
' begin\n'
' sig_in <= (others => \'0\');\n'
' rst <= \'1\'; wait for 100 ns;\n'
' rst <= \'0\'; wait for 125 ns;\n'
) % testBenchDict
for ii in range(len(stimulusBin)):
stimulusDict = {
'BusX': busX,
'CoeffBin': stimulusBin[ii],
'CoeffFloat': stimulusFloat[ii]
}
tempString = ' wait for 50 ns; sig_in <= "%(CoeffBin)s"; -- %(CoeffFloat)f\n'
testBenchString += tempString % stimulusDict
testBenchString += (
#' wait;\n'
#' -- Terminate Simulation\n'
#' assert false report "Simulation completed" severity failure;\n'
' end process;\n'
'\n'
'END;\n'
)
return testBenchString
\ No newline at end of file
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