filter.py 41.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
# This file is part of librefdatool. librefdatool is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Javier D. Garcia-Lasheras
#

import warnings

import numpy as np
from numpy import pi, log10
from scipy import signal
from matplotlib import pyplot as plt
from matplotlib import mlab

import sys, os, random
from PyQt4.QtCore import *
from PyQt4.QtGui import *

import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure

from scope import *



class Filter():
    '''This class instantiate a librefdatool signal generator object.
    This can be used for generating configurable signals in an easy way.
    The generated signals can be directly feeded to devices or scopes
    TBD: almost all!! Noise, DC, correct configuration...
    '''
    
    # Declare signals that will be sended to other classes
    filterUpdatedSignal = pyqtSignal()
    
    def __init__(self):
        self.a = np.ones[1]
        self.b = np.ones[1]
        

    
    def calculate_filter_coefficients(self):
        '''This method calculate the different filter coefficients as a
        funtion of the filter parameters
        '''
        
        
        filterMethod = str(self.comboResponseType.currentText())
        if  filterMethod == 'FIR 1':
            
            # Get filter parameters
            numtaps = int(self.textNumtaps.text())
            # TODO: Handle Value error exception in np.fromstring
            cutoff = np.fromstring(str(self.textCutoff.text()), sep=',')
           
            if cutoff[0] == 0:
                cutoff[0] = 0.00000001
            if cutoff[len(cutoff)-1] == 1:
                cutoff[len(cutoff)-1] = 0.99999999
            window = str(self.comboFIRWindow.currentText())
            if window == 'kaiser':
                if str(self.textWidth.text()) == None:
                    width = str(self.textWidth.text())
                else:
                    width = float(self.textWidth.text())
            else:
                width = None
            pass_zero = bool(self.cbPassZero.isChecked())
            scale = bool(self.cbScale.isChecked())
            
            # Denominator is [1]
            a = np.ones(1)
            
            # Calculate Numerator
            b = signal.fir_filter_design.firwin(numtaps, cutoff, width = width, 
                                                window = window, 
                                                pass_zero = pass_zero, scale = scale)
            
                       
        elif filterMethod == 'FIR 2':
            
            # Get filter parameters
            # TODO: handle raise ValueError from Numpy!!
            # The values in freq must be nondecreasing. 
            # A value can be repeated once to implement a discontinuity.
            numtaps = int(self.textNumtaps.text())
            freq = np.fromstring(str(self.textFreq.text()), sep=',')
            # The first value in freq must be 0, and the last value must be nyq.
            if freq[0] != 0:
                tempFreq = np.zeros(len(freq)+1)
                for ii in range(len(freq)):
                    tempFreq[ii+1] = freq[ii]
                freq = tempFreq
            if freq[len(freq)-1] != 1:
                tempFreq = np.ones(len(freq)+1)
                for ii in range(len(freq)):
                    tempFreq[ii] = freq[ii]
                freq = tempFreq  
            
            # TODO: handle raise ValueError from Numpy!!
            # gain: The filter gains at the frequency sampling points.
            # See notes in (ValueError messages raised) --> dump console to status bar??
            # http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.firwin2.html#scipy.signal.firwin2
            gain = np.fromstring(str(self.textGain.text()), sep=',')
            window = str(self.comboFIRWindow.currentText())
            antisymmetric = bool(self.cbAntisymmetric.isChecked())
            
            # Denominator is [1]
            a = np.ones(1)
            
            # Calculate Numerator
            b = signal.fir_filter_design.firwin2(numtaps, freq, gain, 
                                                 window = window, 
                                                 antisymmetric = antisymmetric)
            

        elif filterMethod == 'IIR 1':
            
            # Get the filter parameters
            wp = float(self.textWp.text())
            ws = float(self.textWs.text())
            gpass = float(self.textGpass.text())
            gstop = float(self.textGstop.text())
            ftype = str(self.comboIIRMethod.currentText())
            
            # Calculate coefficients
            b, a = signal.filter_design.iirdesign(wp, ws, gpass, gstop, 
                                                  ftype = ftype)
        
        elif filterMethod == 'IIR 2':
            
            # Get the filter parameters
            N = int(self.textOrder.text())
            # TODO: we need to handle the fromstring possible errors!!
            Wn = np.fromstring(str(self.textWn.text()), sep=',')
            btype = str(self.comboBType.currentText())
            ftype = str(self.comboIIRMethod.currentText())
            
            if ftype in {'ellip',
                                                          'cheby1',
                                                          'cheby2'}:
                rp = float(self.textRp.text())
                rs = float(self.textRs.text())
            else:
                rp = None
                rs = None
                
            # Calculate coefficients
            b, a = signal.filter_design.iirfilter(N, Wn, 
                                                  rp = rp, rs = rs,
                                                  btype = btype, 
                                                  ftype = ftype)

      

        else :
            print('Not recognized filter description method')
            a = np.ones(1)
            b = np.ones(1)
        
        return b, a
        

    def update_parameter_set(self):
        '''This method hide and show the appropriated filter parameters
        as a function of the filter description method that has been selected
        '''
        
        filterMethod = str(self.comboResponseType.currentText())
        

        if  filterMethod == 'FIR 1':
            flagFIRWindow = True
            flagNumtaps = True
            flagCutoff = True
            if str(self.comboFIRWindow.currentText()) == 'kaiser':
                flagWidth = True
            else:
                flagWidth = False
            flagPassZero = True
            flagScale = True
            flagFrequency = False
            flagGain = False
            flagAntisymmetric = False 
            flagIIRMethod = False
            flagWp = False
            flagWs = False
            flagGpass = False
            flagGstop = False
            flagOrder = False
            flagOrder = False
            flagWn = False
            flagRp = False
            flagRs = False
            flagBType = False

            # Pass Zero special requirement
            if int(self.textNumtaps.text())%2 == 0:
                # Numtaps is even, Pass Zero must be True
                self.cbPassZero.setChecked(True)
                self.cbPassZero.setDisabled(True)
            else:
                # Numtaps is odd, Pass Zero can be False
                self.cbPassZero.setEnabled(True)
            
        elif filterMethod == 'FIR 2':
            flagFIRWindow = True
            flagNumtaps = True
            flagCutoff = False
            flagWidth = False
            flagPassZero = False
            flagScale = False
            flagFrequency = True
            flagGain = True
            flagAntisymmetric = True 
            flagIIRMethod = False
            flagWp = False
            flagWs = False
            flagGpass = False
            flagGstop = False
            flagOrder = False
            flagOrder = False
            flagWn = False
            flagRp = False
            flagRs = False
            flagBType = False

        elif filterMethod == 'IIR 1':
            flagFIRWindow = False
            flagNumtaps = False
            flagCutoff = False
            flagWidth =False
            flagPassZero = False
            flagScale = False
            flagFrequency = False
            flagGain = False
            flagAntisymmetric = False 
            flagIIRMethod = True
            flagWp = True
            flagWs = True
            flagGpass = True
            flagGstop = True
            flagOrder = False
            flagOrder = False
            flagWn = False
            flagRp = False
            flagRs = False
            flagBType = False
        
        elif filterMethod == 'IIR 2':
            flagFIRWindow = False
            flagNumtaps = False
            flagCutoff = False
            flagWidth = False
            flagPassZero = False
            flagScale = False
            flagFrequency = False
            flagGain = False
            flagAntisymmetric = False 
            flagIIRMethod = True
            flagWp = False
            flagWs = False
            flagGpass = False
            flagGstop = False
            flagOrder = True
            flagOrder = True
            flagWn = True
            if str(self.comboIIRMethod.currentText()) in {'ellip',
                                                          'cheby1',
                                                          'cheby2'}:
                flagRp = True
                flagRs = True
            else:
                flagRp = False
                flagRs = False
            flagBType = True

        else :
            print('Not recognized filter description method')
        

        # TODO: this is ugly, should be compacted in a cleaner structure!!
        self.labelFIRWindow.setVisible(flagFIRWindow)
        self.comboFIRWindow.setVisible(flagFIRWindow) 
            
        self.labelNumtaps.setVisible(flagNumtaps)
        self.textNumtaps.setVisible(flagNumtaps)
        
        self.labelCutoff.setVisible(flagCutoff)
        self.textCutoff.setVisible(flagCutoff)
            
        # If Kaiser is selected!!
        self.labelWidth.setVisible(flagWidth)
        self.textWidth.setVisible(flagWidth)
           
        self.cbPassZero.setVisible(flagPassZero)
        self.cbScale.setVisible(flagScale)
            
        self.labelFreq.setVisible(flagFrequency)
        self.textFreq.setVisible(flagFrequency) 
        
        self.labelGain.setVisible(flagGain)
        self.textGain.setVisible(flagGain)
        
        self.cbAntisymmetric.setVisible(flagAntisymmetric)
        
        self.labelIIRMethod.setVisible(flagIIRMethod)
        self.comboIIRMethod.setVisible(flagIIRMethod)
        
        self.labelWp.setVisible(flagWp)
        self.textWp.setVisible(flagWp) 
        
        self.labelWs.setVisible(flagWs)
        self.textWs.setVisible(flagWs)
        
        self.labelGpass.setVisible(flagGpass)
        self.textGpass.setVisible(flagGpass)
        
        self.labelGstop.setVisible(flagGstop)
        self.textGstop.setVisible(flagGstop)
        
        self.labelOrder.setVisible(flagOrder)
        self.textOrder.setVisible(flagOrder)
        
        self.labelWn.setVisible(flagWn)
        self.textWn.setVisible(flagWn)
        
        self.labelRp.setVisible(flagRp)
        self.textRp.setVisible(flagRp)
        
        self.labelRs.setVisible(flagRs)
        self.textRs.setVisible(flagRs)
        
        self.labelBType.setVisible(flagBType)
        self.comboBType.setVisible(flagBType)        

        
    def on_parameter_change(self):
        """ Execute when a filter parameter has changed
        """
        self.pbUpdateFilter.setText('Update filter parameters')
        self.pbUpdateFilter.setDisabled(False)
        self.pbUpdateFilter.setStyleSheet('QPushButton {background-color: #FF0000; color: #FFFFFF}')
        

    def on_filter_draw(self):
        """ Redraws the figure
        """
        # Get the coefficient bus
        coefP = int(self.spinBoxCoefficientP.value())
        coefQ = int(self.spinBoxCoefficientQ.value())
    
        
        # TODO: if divide by zero or other errors in plotting,
        # ask for increasing the filter resolution!!
        
        
        if self.comboAnalysis.currentText() == 'Magnitude / Phase':
            successFlag, logMessage = analyze_frequency_response(
                                            self.figFilter, 
                                            self.b, self.a, 
                                            coefP, coefQ, 
                                            self.cbGridFilter.isChecked())
        elif self.comboAnalysis.currentText() == 'Pole / Zero':
            successFlag, logMessage = analyze_pole_zero(
                                   self.figFilter, 
                                   self.b, self.a, 
                                   coefP, coefQ, 
                                   self.cbGridFilter.isChecked())
        else:
            successFlag, logMessage = analyze_pole_zero(
                                   self.figFilter, 
                                   self.b, self.a, 
                                   coefP, coefQ, 
                                   self.cbGridFilter.isChecked())
        
        self.canvasFilter.draw()
        
        if successFlag:
            print('scope updated')
            
        else:
            QMessageBox.warning(self, 'Error on filter plotting',
                        'TIP: increase coefficient bus width\n' 
                        "%s" % logMessage, QMessageBox.Ok)



    def on_filter_update(self):
        """ Update the filter
        """
        
        # Get the coefficients
        warningMessage = ''
        warnings.simplefilter('error')
        try:
            self.b, self.a = self.calculate_filter_coefficients()
410
        except ValueError as exVE:
411
            warningMessage = '%s' % exVE
412
        except ZeroDivisionError as exZDE:
413
            warningMessage = '%s' % exZDE
414
        except RuntimeWarning as exRW:
415
            warningMessage = '%s' % exRW
416
        except signal.BadCoefficients as exBC:
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
            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()
490 491 492
        self.comboFilterStructure.addItem("Direct_Form_I_Transposed")
        self.comboFilterStructure.addItem("Direct_Form_II_Transposed")
        self.comboFilterStructure.addItem("Direct_Form_I")
493 494
        self.comboFilterStructure.addItem("Parallel")
        self.comboFilterStructure.addItem("Cascade")
495
        self.comboFilterStructure.addItem("Direct_Form_II")
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
        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
517
        self.connect(self.comboFilterOverflow, SIGNAL('currentIndexChanged(int)'), self.on_overflow_change)
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
        
        
        labelResponseType = QLabel('Filtering Method:')
        self.comboResponseType = QComboBox()
        self.comboResponseType.addItem("FIR 1") # scipy.signal.firwin
        self.comboResponseType.addItem("FIR 2") # scipy.signal.firwin2
        self.comboResponseType.addItem("IIR 1") # scipy.signal.iirdesign
        # TODO: this IIR 2 filter causes undetected problems!! We disable this
        self.comboResponseType.addItem("IIR 2") # scipy.signal.iirfilter
        self.comboResponseType.setEditable(True) 
        self.comboResponseType.lineEdit().setReadOnly(True)
        self.comboResponseType.lineEdit().setAlignment(Qt.AlignRight)
        for ii in range(self.comboResponseType.count()):
            self.comboResponseType.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
        self.connect(self.comboResponseType, SIGNAL('currentIndexChanged(int)'), self.update_parameter_set)
        self.connect(self.comboResponseType, SIGNAL('currentIndexChanged(int)'), self.on_parameter_change)



        # The Elements for filter configuration are:  
            
        # window: FIR 1, FIR 2
        self.labelFIRWindow = QLabel('FIR Window:')
        self.comboFIRWindow = QComboBox()
        self.comboFIRWindow.addItem("boxcar")
        self.comboFIRWindow.addItem("triang")
        self.comboFIRWindow.addItem("blackman")
        self.comboFIRWindow.addItem("hamming")
        self.comboFIRWindow.addItem("hann")
        self.comboFIRWindow.addItem("bartlett")
        self.comboFIRWindow.addItem("flattop")
        self.comboFIRWindow.addItem("parzen")
        self.comboFIRWindow.addItem("bohman")
        self.comboFIRWindow.addItem("blackmanharris")
        self.comboFIRWindow.addItem("nuttall")
        self.comboFIRWindow.addItem("barthann")
        self.comboFIRWindow.addItem("kaiser") # needs beta
        self.comboFIRWindow.addItem("gaussian") # needs std
        self.comboFIRWindow.addItem("general_gaussian") # needs power, width
        self.comboFIRWindow.addItem("slepian") # needs width
        self.comboFIRWindow.addItem("chebwin") # needs attenuation
        self.comboFIRWindow.setCurrentIndex(0)
        self.comboFIRWindow.setEditable(True) 
        self.comboFIRWindow.lineEdit().setReadOnly(True)
        self.comboFIRWindow.lineEdit().setAlignment(Qt.AlignRight)
        for ii in range(self.comboFIRWindow.count()):
            self.comboFIRWindow.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
        self.connect(self.comboFIRWindow, SIGNAL('currentIndexChanged(int)'), self.update_parameter_set)
        self.connect(self.comboFIRWindow, SIGNAL('currentIndexChanged(int)'), self.on_parameter_change)
        
        # numtaps: FIR 1, FIR 2
        self.labelNumtaps = QLabel('Numtaps:')
        self.textNumtaps = QLineEdit()
        validatorNumtaps = QIntValidator(1,1000)
        self.textNumtaps.setValidator(validatorNumtaps)
        self.textNumtaps.setText('100')
        self.textNumtaps.setAlignment(Qt.AlignRight)
        # Pass_Zero must always be active in 'FIR 1' if numtaps is an even value!!
        self.connect(self.textNumtaps, SIGNAL('editingFinished()'), self.update_parameter_set)
        self.connect(self.textNumtaps, SIGNAL('editingFinished()'), self.on_parameter_change)
         
        # cutoff: FIR 1
        #This could be an array!!
        # TODO: we need a validator!!!
        self.labelCutoff = QLabel('Cutoff:')
        self.textCutoff = QLineEdit()
        self.textCutoff.setText('0.5')
        self.textCutoff.setAlignment(Qt.AlignRight)
        self.connect(self.textCutoff, SIGNAL('editingFinished()'), self.on_parameter_change)
        self.textCutoff.setToolTip(
            'An array of cutoff frequencies (that is, band edges).\n' 
            'The frequencies in cutoff should be positive and monotonically increasing between 0 and 1.\n'
            'The values 0 and nyq must not be included in cutoff.\n')
        
        # width: FIR 1 --> only for Kaiser windows!! 'none' value in toher case
        self.labelWidth = QLabel('Width:')
        self.textWidth = QLineEdit()
        # QDoubleValidator.__init__ (self, float bottom, float top, int decimals)
        validatorWidth = QDoubleValidator(0.00000001, 0.99999999, 8)
        self.textWidth.setValidator(validatorWidth)
        self.textWidth.setText('0.5')
        self.textWidth.setAlignment(Qt.AlignRight)
        self.connect(self.textWidth, SIGNAL('editingFinished()'), self.on_parameter_change)
        
        # pass_zero: FIR 1 
        self.cbPassZero = QCheckBox("Pass Zero")
        self.cbPassZero.setChecked(True)
        self.connect(self.cbPassZero, SIGNAL('stateChanged(int)'), self.on_parameter_change)
        
        # scale: FIR 1
        self.cbScale = QCheckBox("Scale")
        self.cbScale.setChecked(True)
        self.connect(self.cbScale, SIGNAL('stateChanged(int)'), self.on_parameter_change)
        
        # freq: FIR 2
        #TODO: We need a validator!! The first value in freq must be 0, 
        # and the last value must be nyq.
        '''
        The frequency sampling points. 
        Typically 0.0 to 1.0 with 1.0 being Nyquist. 
        The Nyquist frequency can be redefined with the argument nyq. 
        The values in freq must be nondecreasing. 
        A value can be repeated once to implement a discontinuity. 
        The first value in freq must be 0, and the last value must be nyq
        '''
        self.labelFreq = QLabel('Frequency:')
        self.textFreq = QLineEdit()
        self.textFreq.setText('0, 0.5, 1')
        self.textFreq.setAlignment(Qt.AlignRight)
        self.connect(self.textFreq, SIGNAL('editingFinished()'), self.on_parameter_change)
        
        # gain: FIR 2
        #TODO: We need a specific validator!!
        self.labelGain = QLabel('Gain:')
        self.textGain = QLineEdit()
        self.textGain.setText('1, 0.5, 0')
        self.textGain.setAlignment(Qt.AlignRight)
        self.connect(self.textGain, SIGNAL('editingFinished()'), self.on_parameter_change)

        # scale: FIR 2
        self.cbAntisymmetric = QCheckBox("Antisymmetric")
        self.cbAntisymmetric.setChecked(False)
        self.connect(self.cbAntisymmetric, SIGNAL('stateChanged(int)'), self.on_parameter_change)       

        # ftype: IIR1, IIR2
        self.labelIIRMethod = QLabel('Filter Type:')
        self.comboIIRMethod = QComboBox()
        self.comboIIRMethod.addItem("ellip")
        self.comboIIRMethod.addItem("butter")
        self.comboIIRMethod.addItem("cheby1")
        self.comboIIRMethod.addItem("cheby2")
        self.comboIIRMethod.addItem("bessel")
        self.comboIIRMethod.setEditable(True) 
        self.comboIIRMethod.lineEdit().setReadOnly(True)
        self.comboIIRMethod.lineEdit().setAlignment(Qt.AlignRight)
        for ii in range(self.comboIIRMethod.count()):
            self.comboIIRMethod.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
        self.connect(self.comboIIRMethod, SIGNAL('currentIndexChanged(int)'), self.update_parameter_set)
        self.connect(self.comboIIRMethod, SIGNAL('currentIndexChanged(int)'), self.on_parameter_change)

        # wp: IIR 1
        self.labelWp = QLabel('wp:')
        self.textWp = QLineEdit()
        validatorWp = QDoubleValidator(0, 1, 8)
        self.textWp.setValidator(validatorWp)
        self.textWp.setText('0.1')
        self.textWp.setAlignment(Qt.AlignRight)
        self.connect(self.textWp, SIGNAL('editingFinished()'), self.on_parameter_change)
        
        # ws: IIR 1
        self.labelWs = QLabel('ws:')
        self.textWs = QLineEdit()
        validatorWs = QDoubleValidator(0, 1, 8)
        self.textWs.setValidator(validatorWs)
        self.textWs.setText('0.5')
        self.textWs.setAlignment(Qt.AlignRight)
        self.connect(self.textWs, SIGNAL('editingFinished()'), self.on_parameter_change)
        
        # gpass: IIR 1
        self.labelGpass = QLabel('Gpass[dB]:')
        self.textGpass = QLineEdit()
        validatorGpass = QDoubleValidator(-100, 100, 8)
        self.textGpass.setValidator(validatorGpass)
        self.textGpass.setText('1')
        self.textGpass.setAlignment(Qt.AlignRight)
        self.connect(self.textGpass, SIGNAL('editingFinished()'), self.on_parameter_change)
        
        # ws: IIR 1
        self.labelGstop = QLabel('Gstop[dB]:')
        self.textGstop = QLineEdit()
        validatorGstop = QDoubleValidator(-100, 100, 8)
        self.textGstop.setValidator(validatorGstop)
        self.textGstop.setText('12')
        self.textGstop.setAlignment(Qt.AlignRight)
        self.connect(self.textGstop, SIGNAL('editingFinished()'), self.on_parameter_change)
        
        # N, order: IIR 2
        self.labelOrder = QLabel('Order:')
        self.textOrder = QLineEdit()
        validatorOrder = QIntValidator(1,1000)
        self.textOrder.setValidator(validatorOrder)
        self.textOrder.setText('5')
        self.textOrder.setAlignment(Qt.AlignRight)
        self.connect(self.textOrder, SIGNAL('editingFinished()'), self.on_parameter_change)
        
        # Wn: IIR 2
        #TODO: we need a validator
        self.labelWn = QLabel('Wn:')
        self.textWn = QLineEdit()
        self.textWn.setText('0, 0.5, 1')
        self.textWn.setAlignment(Qt.AlignRight)
        self.connect(self.textWn, SIGNAL('editingFinished()'), self.on_parameter_change)
        
        # rp: IIR 2 --> only in chebyshev and elliptic
        self.labelRp = QLabel('rp[dB]:')
        self.textRp = QLineEdit()
        validatorRp = QDoubleValidator(-100, 100, 8)
        self.textRp.setValidator(validatorRp)
        self.textRp.setText('0.5')
        self.textRp.setAlignment(Qt.AlignRight)
        self.connect(self.textRp, SIGNAL('editingFinished()'), self.on_parameter_change)
        
        # rs: IIR 2 --> only in chebyshev and elliptic
        self.labelRs = QLabel('rs[dB]:')
        self.textRs = QLineEdit()
        validatorRs = QDoubleValidator(-100, 100, 8)
        self.textRs.setValidator(validatorRs)
        self.textRs.setText('0.5')
        self.textRs.setAlignment(Qt.AlignRight)
        self.connect(self.textRs, SIGNAL('editingFinished()'), self.on_parameter_change)
        
        # btype: IIR 2
        self.labelBType = QLabel('Band Type:')
        self.comboBType = QComboBox()
        self.comboBType.addItem("bandpass") 
        self.comboBType.addItem("lowpass") 
        self.comboBType.addItem("highpass") 
        self.comboBType.addItem("bandstop") 
        self.comboBType.setEditable(True) 
        self.comboBType.lineEdit().setReadOnly(True)
        self.comboBType.lineEdit().setAlignment(Qt.AlignRight)
        for ii in range(self.comboBType.count()):
            self.comboBType.setItemData(ii, Qt.AlignRight, Qt.TextAlignmentRole)
        self.connect(self.comboBType, SIGNAL('currentIndexChanged(int)'), self.on_parameter_change)
        
        #
        # Bus Width SetUp 
        #
        
        self.spinBoxCoefficientP = QSpinBox()
        self.spinBoxCoefficientP.setMaximum(256)
        self.spinBoxCoefficientP.setMinimum(1)
        self.spinBoxCoefficientP.setValue(1)
        self.connect(self.spinBoxCoefficientP, SIGNAL('valueChanged(int)'), self.on_parameter_change)
        self.spinBoxCoefficientQ = QSpinBox()
        self.spinBoxCoefficientQ.setMaximum(256)
        self.spinBoxCoefficientQ.setMinimum(1)
        self.spinBoxCoefficientQ.setValue(7) 
        self.connect(self.spinBoxCoefficientQ, SIGNAL('valueChanged(int)'), self.on_parameter_change)
        
        self.spinBoxInputP = QSpinBox()
        self.spinBoxInputP.setMaximum(256)
        self.spinBoxInputP.setMinimum(1)
        self.spinBoxInputP.setValue(1)
        self.connect(self.spinBoxInputP, SIGNAL('valueChanged(int)'), self.on_parameter_change)
        self.spinBoxInputQ = QSpinBox()
        self.spinBoxInputQ.setMaximum(256)
        self.spinBoxInputQ.setMinimum(1)
        self.spinBoxInputQ.setValue(7)
        self.connect(self.spinBoxInputQ, SIGNAL('valueChanged(int)'), self.on_parameter_change)
        
        self.spinBoxOutputP = QSpinBox()
        self.spinBoxOutputP.setMaximum(256)
        self.spinBoxOutputP.setMinimum(1)
        self.spinBoxOutputP.setValue(1)
        self.connect(self.spinBoxOutputP, SIGNAL('valueChanged(int)'), self.on_parameter_change)
        self.spinBoxOutputQ = QSpinBox()
        self.spinBoxOutputQ.setMaximum(256)
        self.spinBoxOutputQ.setMinimum(1)
        self.spinBoxOutputQ.setMinimum(7)
        self.connect(self.spinBoxOutputQ, SIGNAL('valueChanged(int)'), self.on_parameter_change)
        
        
        #
        # Layout with box sizers
        # 
        
        hboxAnalysis = QHBoxLayout()
        hboxAnalysis.addWidget(labelAnalysis)
        hboxAnalysis.addWidget(self.comboAnalysis)
        hboxAnalysis.setStretch(0,1)
        hboxAnalysis.setStretch(1,1)
        
        hboxFilterStructure = QHBoxLayout()
        hboxFilterStructure.addWidget(labelFilterStructure)
        hboxFilterStructure.addWidget(self.comboFilterStructure)
        hboxFilterStructure.setStretch(0,1)
        hboxFilterStructure.setStretch(1,1)
        
        hboxFilterOverflow = QHBoxLayout()
        hboxFilterOverflow.addWidget(labelFilterOverflow)
        hboxFilterOverflow.addWidget(self.comboFilterOverflow)
        hboxFilterOverflow.setStretch(0,1)
        hboxFilterOverflow.setStretch(1,1)
        
        hboxResponseType = QHBoxLayout()
        hboxResponseType.addWidget(labelResponseType)
        hboxResponseType.addWidget(self.comboResponseType)
        hboxResponseType.setStretch(0,1)
        hboxResponseType.setStretch(1,1)
        
        hboxFIRWindow = QHBoxLayout()
        hboxFIRWindow.addWidget(self.labelFIRWindow)
        hboxFIRWindow.addWidget(self.comboFIRWindow)
        hboxFIRWindow.setStretch(0,1)
        hboxFIRWindow.setStretch(1,1)
        
        
        hboxNumtaps = QHBoxLayout()
        hboxNumtaps.addWidget(self.labelNumtaps)
        hboxNumtaps.addWidget(self.textNumtaps)
        hboxNumtaps.setStretch(0,1)
        hboxNumtaps.setStretch(1,1)
        
        hboxCutoff = QHBoxLayout()
        hboxCutoff.addWidget(self.labelCutoff)
        hboxCutoff.addWidget(self.textCutoff)
        hboxCutoff.setStretch(0,1)
        hboxCutoff.setStretch(1,1)
        
        hboxWidth = QHBoxLayout()
        hboxWidth.addWidget(self.labelWidth)
        hboxWidth.addWidget(self.textWidth)
        hboxWidth.setStretch(0,1)
        hboxWidth.setStretch(1,1)
        
        hboxPassZero = QHBoxLayout()
        hboxPassZero.addWidget(self.cbPassZero)
        hboxPassZero.setStretch(0,1)
        hboxPassZero.setStretch(1,1)
        
        hboxScale = QHBoxLayout()
        hboxScale.addWidget(self.cbScale)
        hboxScale.setStretch(0,1)
        hboxScale.setStretch(1,1)
        
        hboxWidth = QHBoxLayout()
        hboxWidth.addWidget(self.labelWidth)
        hboxWidth.addWidget(self.textWidth)
        hboxWidth.setStretch(0,1)
        hboxWidth.setStretch(1,1)
        
        hboxFrequency = QHBoxLayout()
        hboxFrequency.addWidget(self.labelFreq)
        hboxFrequency.addWidget(self.textFreq)
        hboxFrequency.setStretch(0,1)
        hboxFrequency.setStretch(1,1)
        
        hboxGain = QHBoxLayout()
        hboxGain.addWidget(self.labelGain)
        hboxGain.addWidget(self.textGain)
        hboxGain.setStretch(0,1)
        hboxGain.setStretch(1,1)
        
        hboxAntisymmetric = QHBoxLayout()
        hboxAntisymmetric.addWidget(self.cbAntisymmetric)
        hboxAntisymmetric.setStretch(0,1)
        hboxAntisymmetric.setStretch(1,1)
        
        hboxIIRMethod = QHBoxLayout()
        hboxIIRMethod.addWidget(self.labelIIRMethod)
        hboxIIRMethod.addWidget(self.comboIIRMethod)
        hboxIIRMethod.setStretch(0,1)
        hboxIIRMethod.setStretch(1,1)
        
        
        hboxWp = QHBoxLayout()
        hboxWp.addWidget(self.labelWp)
        hboxWp.addWidget(self.textWp)
        hboxWp.setStretch(0,1)
        hboxWp.setStretch(1,1)
        
        hboxWs = QHBoxLayout()
        hboxWs.addWidget(self.labelWs)
        hboxWs.addWidget(self.textWs)
        hboxWs.setStretch(0,1)
        hboxWs.setStretch(1,1)
        
        hboxGpass = QHBoxLayout()
        hboxGpass.addWidget(self.labelGpass)
        hboxGpass.addWidget(self.textGpass)
        hboxGpass.setStretch(0,1)
        hboxGpass.setStretch(1,1)
        
        hboxGstop = QHBoxLayout()
        hboxGstop.addWidget(self.labelGstop)
        hboxGstop.addWidget(self.textGstop)
        hboxGstop.setStretch(0,1)
        hboxGstop.setStretch(1,1)
        
        hboxOrder = QHBoxLayout()
        hboxOrder.addWidget(self.labelOrder)
        hboxOrder.addWidget(self.textOrder)
        hboxOrder.setStretch(0,1)
        hboxOrder.setStretch(1,1)
        
        hboxWn = QHBoxLayout()
        hboxWn.addWidget(self.labelWn)
        hboxWn.addWidget(self.textWn)
        hboxWn.setStretch(0,1)
        hboxWn.setStretch(1,1)
        
        hboxRp = QHBoxLayout()
        hboxRp.addWidget(self.labelRp)
        hboxRp.addWidget(self.textRp)
        hboxRp.setStretch(0,1)
        hboxRp.setStretch(1,1)
        
        hboxRs = QHBoxLayout()
        hboxRs.addWidget(self.labelRs)
        hboxRs.addWidget(self.textRs)
        hboxRs.setStretch(0,1)
        hboxRs.setStretch(1,1)
        
        hboxBType = QHBoxLayout()
        hboxBType.addWidget(self.labelBType)
        hboxBType.addWidget(self.comboBType)
        hboxBType.setStretch(0,1)
        hboxBType.setStretch(1,1)
        
        
        
        vboxFilterParameters = QVBoxLayout()
        for parameterLayout in (hboxResponseType, hboxFIRWindow, 
                                hboxNumtaps, hboxCutoff,
                                hboxWidth, hboxPassZero, hboxScale, 
                                hboxFrequency, hboxGain, hboxAntisymmetric,
                                hboxIIRMethod, hboxWp, hboxWs,
                                hboxGpass, hboxGstop, hboxOrder,
                                hboxWn, hboxRp, hboxRs, hboxBType):
            vboxFilterParameters.addLayout(parameterLayout)
            
        
        groupBoxFilterParameters = QGroupBox('Filter Parameters')
        groupBoxFilterParameters.setLayout(vboxFilterParameters)
           
        
        groupBoxCoefficientFP = QGroupBox('Coefficient Bus')
        hboxCoefficientFP = QHBoxLayout()
        hboxCoefficientFP.addWidget(QLabel('Integer:'))
        hboxCoefficientFP.addWidget(self.spinBoxCoefficientP)
        hboxCoefficientFP.addWidget(QLabel('Fractional:'))
        hboxCoefficientFP.addWidget(self.spinBoxCoefficientQ)
        groupBoxCoefficientFP.setLayout(hboxCoefficientFP)
        
        groupBoxInputFP = QGroupBox('Input Bus')
        hboxInputFP = QHBoxLayout()
        hboxInputFP.addWidget(QLabel('Integer:'))
        hboxInputFP.addWidget(self.spinBoxInputP)
        hboxInputFP.addWidget(QLabel('Fractional:'))
        hboxInputFP.addWidget(self.spinBoxInputQ)
        groupBoxInputFP.setLayout(hboxInputFP)
        
        groupBoxOutputFP = QGroupBox('Output Bus')
        hboxOutputFP = QHBoxLayout()
        hboxOutputFP.addWidget(QLabel('Integer:'))
        hboxOutputFP.addWidget(self.spinBoxOutputP)
        hboxOutputFP.addWidget(QLabel('Fractional:'))
        hboxOutputFP.addWidget(self.spinBoxOutputQ)
        groupBoxOutputFP.setLayout(hboxOutputFP)


        vboxLeft = QVBoxLayout()
        vboxLeft.addLayout(hboxFilterStructure)
        vboxLeft.addLayout(hboxFilterOverflow)
        vboxLeft.addWidget(groupBoxCoefficientFP)
        vboxLeft.addWidget(groupBoxInputFP)
        vboxLeft.addWidget(groupBoxOutputFP)
        
        
        groupBoxFilterRealization = QGroupBox('Hardware Realization')
        groupBoxFilterRealization.setLayout(vboxLeft)
        
               
        hboxFilterControl = QHBoxLayout()
        hboxFilterControl.addWidget(groupBoxFilterRealization)
        hboxFilterControl.addWidget(groupBoxFilterParameters)
        
        vboxFilterControl =QVBoxLayout()
        vboxFilterControl.addWidget(self.pbUpdateFilter)
        vboxFilterControl.addLayout(hboxFilterControl)
        
        self.groupBoxFilterControl = QGroupBox('Filter Control')
        self.groupBoxFilterControl.setLayout(vboxFilterControl)
        self.groupBoxFilterControl.isCheckable()
        
        hboxDisplay = QHBoxLayout()
        hboxDisplay.addLayout(hboxAnalysis)
        hboxDisplay.addWidget(self.cbGridFilter)
        hboxDisplay.addWidget(self.cbHideFilterConfig)
        
        
        vboxMain = QVBoxLayout()
        vboxMain.addWidget(self.canvasFilter)
        vboxMain.addWidget(self.mpl_toolbar_filter)
        vboxMain.addLayout(hboxDisplay)
        vboxMain.addWidget(self.groupBoxFilterControl)
        
        # Update parameter set and then the window too!!
        # the figure update is include in update parameter!!
        self.update_parameter_set()
        self.on_filter_update()
        
        return vboxMain

1013

1014 1015 1016
    def on_structure_change(self):
        # TODO: provisional, check the structure change and force to DF1 Trans
        activeStructure = str(self.comboFilterStructure.currentText())
1017
        if activeStructure == 'Direct_Form_I_Transposed':
1018 1019 1020 1021 1022 1023 1024
            self.on_parameter_change()
        else:
            QMessageBox.information(self, 'Filter Structure', 
                                 'Sorry, but %s is not supported yet!'
                                 % activeStructure, 
                                 QMessageBox.Ok)
            self.comboFilterStructure.setCurrentIndex(0)
1025
     
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
            
    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()