Exemplo n.º 1
0
    def _save_entries(self):
        """
        Read table entries and save the values to the filter PZ dict
        """

        logger.debug("=====================\nInputPZ._save_entries called")

        zpk = []

        num_rows = self.tblPZ.rowCount()
        logger.debug("nrows = %d" % num_rows)

        #iterate over both columns
        for col in range(2):
            rows = []
            for row in range(num_rows):
                item = self.tblPZ.item(row, col)
                if item:
                    if item.text() != "":
                        rows.append(simple_eval(item.text()))
                else:
                    rows.append(0.)

            zpk.append(rows)

        zpk.append(simple_eval(self.ledGain.text()))  # append k factor to zpk

        fb.fil[0]['N'] = num_rows

        if np.any(zpk[1]):
            fb.fil[0]['ft'] = 'IIR'
            fb.fil[0]['fc'] = 'Manual_IIR'
            self.cmbFilterType.setCurrentIndex(1)  # set to "IIR"
        else:
            fb.fil[0]['ft'] = 'FIR'
            fb.fil[0]['fc'] = 'Manual_FIR'
            self.cmbFilterType.setCurrentIndex(0)  # set to "FIR"

        fil_save(fb.fil[0], zpk, 'zpk', __name__)  # save & convert to 'ba'

        if self.chkNorm.isChecked():
            # set gain factor k (zpk[2]) in such a way that the max. filter
            # gain remains unchanged
            # TODO: Comparison against Hmax is not robust, need to find another anchor
            [w, H] = freqz(fb.fil[0]['ba'][0], fb.fil[0]['ba'][1])  # (bb, aa)
            Hmax = max(abs(H))
            if not np.isfinite(Hmax) or Hmax > 1e4:
                Hmax = 1.
            zpk[2] = zpk[2] * self.Hmax_last / max(abs(H))
            fil_save(fb.fil[0], zpk, 'zpk', __name__)  # save with new gain

        if __name__ == '__main__':
            self.load_entries()  # only needed for stand-alone test

        self.sigFilterDesigned.emit()

        logger.debug("_save_entries - coeffients / zpk updated:\n"
                     "b,a = %s\n\n"
                     "zpk = %s\n" %
                     (pformat(fb.fil[0]['ba']), pformat(fb.fil[0]['zpk'])))
Exemplo n.º 2
0
    def storeEntries(self):
        """
        Store specification entries in filter dictionary
        Entries are always stored in dB (20 log10) !
        """
        idx = self.cmbUnitsA.currentIndex()  # read index of units combobox

        if idx == 0: # Entry is in dBs, same as in dictionary
            for i in range(len(self.qlineedit)):
                fb.fil[0].update(
                    {self.qlineedit[i].objectName():
                        simple_eval(self.qlineedit[i].text())})

        elif idx == 1:  # Entries are voltages, convert to dBs
            for i in range(len(self.qlineedit)):
                fb.fil[0].update(
                   {self.qlineedit[i].objectName():round(
                      -20 * log10 (simple_eval(self.qlineedit[i].text())),8)})
        else:  # Entries are powers, convert to dBs
            for i in range(len(self.qlineedit)):
                fb.fil[0].update(
                    {self.qlineedit[i].objectName():round(
                       -10 * log10 (simple_eval(self.qlineedit[i].text())),8)})
                       
        self.sigSpecsChanged.emit() # -> input_widgets
Exemplo n.º 3
0
    def _save_entries(self):
        """
        Read table entries and save the values to the filter PZ dict
        """

        logger.debug("=====================\nInputPZ._save_entries called")

        zpk = []

        num_rows = self.tblPZ.rowCount()
        logger.debug("nrows = %d" % num_rows)

        #iterate over both columns
        for col in range(2):
            rows = []
            for row in range(num_rows):
                item = self.tblPZ.item(row, col)
                if item:
                    if item.text() != "":
                        rows.append(simple_eval(item.text()))
                else:
                    rows.append(0.)

            zpk.append(rows)

        zpk.append(simple_eval(self.ledGain.text()))  # append k factor to zpk

        fb.fil[0]["N"] = num_rows
        fil_save(fb.fil[0], zpk, 'zpk', __name__)  # save & convert to 'ba'

        if self.chkNorm.isChecked():
            # set gain factor k (zpk[2]) in such a way that the max. filter
            # gain remains unchanged
            # TODO: Comparison against Hmax is not robust, need to find another anchor
            [w, H] = freqz(fb.fil[0]['ba'][0], fb.fil[0]['ba'][1])  # (bb, aa)
            Hmax = max(abs(H))
            if not np.isfinite(Hmax) or Hmax > 1e4:
                Hmax = 1.
            zpk[2] = zpk[2] * self.Hmax_last / max(abs(H))
            fil_save(fb.fil[0], zpk, 'zpk', __name__)  # save with new gain

        if __name__ == '__main__':
            self.load_entries()  # only needed for stand-alone test

        self.sigFilterDesigned.emit()

        if self.DEBUG:
            print("ZPK - coeffs:", fb.fil[0]['ba'])
            print("ZPK - zpk:", fb.fil[0]['zpk'])
            print("ZPK updated!")
Exemplo n.º 4
0
    def quant_coeffs(self):
        """
        Quantize all coefficients
        """
        # define + instantiate fixed-point object
        myQ = fix.Fixed({
            'QI': int(self.ledQuantI.text()),
            'QF': int(self.ledQuantF.text()),
            'quant': self.cmbQQuant.currentText(),
            'ovfl': self.cmbQOvfl.currentText(),
            'frmt': self.cmbQFormat.currentText()
        })

        num_rows, num_cols = self.tblCoeff.rowCount(),\
                                        self.tblCoeff.columnCount()
        for col in range(num_cols):
            for row in range(num_rows):
                item = self.tblCoeff.item(row, col)
                if item:
                    item.setText(str(myQ.fix(simple_eval(item.text()))))
                else:
                    self.tblCoeff.setItem(row, col,
                                          QtGui.QTableWidgetItem("0.0"))

        self.tblCoeff.resizeColumnsToContents()
        self.tblCoeff.resizeRowsToContents()
Exemplo n.º 5
0
    def saveCoeffs(self):
        """
        Read out coefficients table and save the values to filter 'coeffs'
        and 'zpk' dicts. Is called when clicking the <Save> button, triggers
        a recalculation and replot of all plot widgets.
        """
        if self.DEBUG:
            print("=====================\nInputCoeffs.saveCoeffs")
        coeffs = []
        num_rows, num_cols = self.tblCoeff.rowCount(),\
                                        self.tblCoeff.columnCount()
        if self.DEBUG: print("Tbl rows /  cols:", num_rows, num_cols)
#        if num_cols > 1: # IIR
        for col in range(num_cols):
            rows = []
            for row in range(num_rows):
                item = self.tblCoeff.item(row, col)
                if item:
                    if item.text() != "":
                        rows.append(simple_eval(item.text()))
                else:
                    rows.append(0.)
#                    rows.append(float(item.text()) if item else 0.)
            coeffs.append(rows)

        fb.fil[0]["N"] = num_rows - 1
        save_fil(fb.fil[0], coeffs, 'ba', __name__)

        if self.DEBUG:
            print("Coeffs - ZPK:", fb.fil[0]["zpk"])
            print("Coeffs - b,a:", fb.fil[0]["ba"])
            print ("Coeffs updated!")

        self.sigFilterDesigned.emit()  # -> input_widgets -> pyFDA -> pltWidgets.updateAll()
Exemplo n.º 6
0
    def saveZPK(self):
        """
        Read out table and save the values to the filter PZ dict
        """
            
        if self.DEBUG:
            print("=====================\nInputPZ.saveZPK")
            
        zpk = [] 
        
        num_rows = self.tblPZ.rowCount()
        if self.DEBUG: print("nrows:",num_rows)

        #iterate over both columns
        for col in range(2):
            rows = []
            for row in range(num_rows):
                item = self.tblPZ.item(row, col)
                if item:
                    if item.text() != "":
                        rows.append(simple_eval(item.text()))
                else:
                    rows.append(0.)

            zpk.append(rows)

        zpk.append(simple_eval(self.ledGain.text())) # append k factor to zpk

        fb.fil[0]["N"] = num_rows
        save_fil(fb.fil[0], zpk, 'zpk', __name__) # save & convert to 'ba'
        
        if self.chkNorm.isChecked():
            # set gain factor k (zpk[2]) in such a way that the max. filter 
            # gain remains unchanged
            [w, H] = freqz(fb.fil[0]['ba'][0], fb.fil[0]['ba'][1]) # (bb, aa)
            zpk[2] = zpk[2] * self.Hmax_last / max(abs(H))
            save_fil(fb.fil[0], zpk, 'zpk', __name__) # save with new gain '

        if __name__ == '__main__':
            self.showZPK() # only needed for stand-alone test
            
        self.sigFilterDesigned.emit()

        if self.DEBUG:
            print("ZPK - coeffs:",  fb.fil[0]['ba'])
            print("ZPK - zpk:",  fb.fil[0]['zpk'])
            print("ZPK updated!")
Exemplo n.º 7
0
 def _sort_store_entries(self):
     """
     Sort visible spec entries with ascending frequency if "sort" button is
     pressed and write the sorted freq. specs back into the lineedit widgets
     and into the filter dict.
     """
     if fb.fil[0]['freq_specs_sort']:
         fSpecs = [simple_eval(self.qlineedit[i].text())
                                         for i in range(len(self.qlineedit))]
         fSpecs.sort()
 
         for i in range(len(self.qlineedit)):
             self.qlineedit[i].setText(str(fSpecs[i]))
             
     for i in range(len(self.qlineedit)):
         fb.fil[0].update(
             {self.qlineedit[i].objectName():round(
                 simple_eval(self.qlineedit[i].text())/fb.fil[0]['f_S'],11)})
Exemplo n.º 8
0
 def _store_entry():
     """
     Update filter dictionary, set line edit entry with reduced precision
     again.
     """
     if self.spec_edited:
         fb.fil[0].update({'f_S': simple_eval(source.text())})
         self._freq_range(emit_sig_range=False)  # update plotting range
         self.sigSpecsChanged.emit()  # -> input_widgets
         self.spec_edited = False  # reset flag, changed entry has been saved
Exemplo n.º 9
0
 def storeEntries(self):
     """
     Store specification entries in filter dictionary
     """
     for i in range(len(self.qlabels)):
         fb.fil[0].update(
             {self.qlineedit[i].objectName():
                 simple_eval(self.qlineedit[i].text())})
                    
     self.sigSpecsChanged.emit() # -> input_widgets
Exemplo n.º 10
0
    def store_entries(self):
        """
        Read out coefficients table and save the values to filter 'coeffs'
        and 'zpk' dicts. Is called when clicking the <Save> button, triggers
        a recalculation and replot of all plot widgets.
        """
        coeffs = []
        num_rows, num_cols = self.tblCoeff.rowCount(
        ), self.tblCoeff.columnCount()
        logger.debug("store_entries: \n%s rows x  %s cols" %
                     (num_rows, num_cols))

        if self.cmbFilterType.currentText() == 'IIR':
            fb.fil[0]['ft'] = 'IIR'
            fb.fil[0]['fc'] = 'Manual_IIR'
            self.cmbFilterType.setCurrentIndex(1)  # set to "IIR"
        else:
            fb.fil[0]['ft'] = 'FIR'
            fb.fil[0]['fc'] = 'Manual_FIR'
            self.cmbFilterType.setCurrentIndex(0)  # set to "FIR"

#        if num_cols > 1: # IIR
        for col in range(num_cols):
            rows = []
            for row in range(num_rows):
                item = self.tblCoeff.item(row, col)
                if item:
                    if item.text() != "":
                        rows.append(simple_eval(item.text()))
                else:
                    rows.append(0.)
#                    rows.append(float(item.text()) if item else 0.)
            if num_cols == 1:
                coeffs = rows
            else:
                coeffs.append(rows)  # type: list num_cols x num_rows

        fb.fil[0]["N"] = num_rows - 1
        fb.fil[0]["q_coeff"] = {
            'QI': int(self.ledQuantI.text()),
            'QF': int(self.ledQuantF.text()),
            'quant': self.cmbQQuant.currentText(),
            'ovfl': self.cmbQOvfl.currentText(),
            'frmt': self.cmbQFormat.currentText()
        }

        fil_save(fb.fil[0], coeffs, 'ba', __name__)

        logger.debug("store_entries - coeffients / zpk updated:\n"
                     "b,a = %s\n\n"
                     "zpk = %s\n" %
                     (pformat(fb.fil[0]['ba']), pformat(fb.fil[0]['zpk'])))

        self.sigFilterDesigned.emit(
        )  # -> input_widgets -> pyFDA -> pltWidgets.updateAll()
Exemplo n.º 11
0
 def _store_entry(self, widget):
     """
     When the textfield of `widget` has been edited (`self.spec_edited` =  True),
     store the weight spec in filter dict. This is triggered by `QEvent.focusOut`
     """
     if self.spec_edited:
         w_label = str(widget.objectName())
         w_value = simple_eval(widget.text())
         fb.fil[0].update({w_label: w_value})
         self.sigSpecsChanged.emit()  # -> input_specs
         self.spec_edited = False  # reset flag
     self.load_entries()
Exemplo n.º 12
0
 def _store_entry(self, event_source):
     """
     _store_entry is triggered by `QEvent.focusOut` in the eventFilter:        
     When the textfield of `widget` has been edited (`self.spec_edited` =  True),
     sort and store all entries in filter dict, then reload the text fields. 
     Finally, emit a SpecsChanged signal.
     """
     if self.spec_edited:
         f_label = str(event_source.objectName())
         f_value = simple_eval(event_source.text()) / fb.fil[0]['f_S']
         fb.fil[0].update({f_label: f_value})
         self.sort_dict_freqs()
         self.sigSpecsChanged.emit()  # -> input_specs
         self.spec_edited = False  # reset flag
Exemplo n.º 13
0
 def setCoeffsZero(self):
     """
     Set all coefficients = 0 in table with a magnitude less than eps
     """
     eps = float(self.ledSetEps.text())
     num_rows, num_cols = self.tblCoeff.rowCount(),\
                                     self.tblCoeff.columnCount()
     for col in range(num_cols):
         for row in range(num_rows):
             item = self.tblCoeff.item(row, col)
             if item:
                 if abs(simple_eval(item.text())) < eps:
                     item.setText(str(0.))
             else:
                 self.tblCoeff.setItem(row,col,QtGui.QTableWidgetItem("0.0"))
Exemplo n.º 14
0
    def setZPKZero(self):
        """
        Set all PZs = 0 with a magnitude less than eps
        """
        eps = float(self.ledSetEps.text())
        num_rows= self.tblPZ.rowCount()

        for col in range(2):
            for row in range(num_rows):
                item = self.tblPZ.item(row, col)
                if item:
                    if abs(simple_eval(item.text())) < eps:
                        item.setText(str(0.))
                else:
                    self.tblPZ.setItem(row,col,QtGui.QTableWidgetItem("0.0"))
Exemplo n.º 15
0
    def _zero_PZ(self):
        """
        Set all PZs = 0 with a magnitude less than eps
        """
        eps = float(self.ledSetEps.text())
        num_rows = self.tblPZ.rowCount()

        for col in range(2):
            for row in range(num_rows):
                item = self.tblPZ.item(row, col)
                if item:
                    if abs(simple_eval(item.text())) < eps:
                        item.setText(str(0.))
                else:
                    self.tblPZ.setItem(row, col, QTableWidgetItem("0.0"))
Exemplo n.º 16
0
 def _set_coeffs_zero(self):
     """
     Set all coefficients = 0 in table with a magnitude less than eps
     """
     eps = float(self.ledSetEps.text())
     num_rows, num_cols = self.tblCoeff.rowCount(),\
                                     self.tblCoeff.columnCount()
     for col in range(num_cols):
         for row in range(num_rows):
             item = self.tblCoeff.item(row, col)
             if item:
                 if abs(simple_eval(item.text())) < eps:
                     item.setText(str(0.))
             else:
                 self.tblCoeff.setItem(row, col, QTableWidgetItem("0.0"))
Exemplo n.º 17
0
    def storeEntries(self):
        """
        - Sort spec entries with ascending frequency if button is pressed
        - Store specification entries in filter dictionary:
          Entries are normalized with sampling frequency fb.fil[0]['f_S'] !
          The unit scale factor (khz, ...) is contained neither in f_S nor in 
          the specs, hence, it cancels out.
        - Emit sigFilterChanged signal
        """

        self._sort_store_entries() 
           
        for i in range(len(self.qlineedit)):
            fb.fil[0].update(
                {self.qlineedit[i].objectName():
                    simple_eval(self.qlineedit[i].text())/fb.fil[0]['f_S']})
                      
        self.sigSpecsChanged.emit()
Exemplo n.º 18
0
    def _store_entry(self, source):
        """
        When the textfield of `source` has been edited (flag `self.spec_edited` =  True),
        transform the amplitude spec back to linear unit setting and store it
        in filter dict.
        This is triggered by `QEvent.focusOut`

        Spec entries are *always* stored in linear units; only the
        displayed values are adapted to the amplitude unit, not the dictionary!
        """
        if self.spec_edited:
            unit = str(self.cmbUnitsA.currentText())
            filt_type = fb.fil[0]['ft']
            amp_label = str(source.objectName())
            amp_value = simple_eval(source.text())
            fb.fil[0].update(
                {amp_label: unit2lin(amp_value, filt_type, amp_label, unit)})
            self.sigSpecsChanged.emit()  # -> input_specs
            self.spec_edited = False  # reset flag
        self.load_entries()
Exemplo n.º 19
0
    def quantCoeffs(self):
        """
        Quantize all coefficients
        """
        qI = int(self.ledQuantI.text())
        qF = int(self.ledQuantF.text())
        qQuant = self.cmbQQuant.currentText()
        qOvfl = self.cmbQOvfl.currentText()
        q_obj =  {'QI':qI, 'QF': qF, 'quant': qQuant, 'ovfl': qOvfl}
        myQ = fix.Fixed(q_obj) # instantiate fixed-point object
        num_rows, num_cols = self.tblCoeff.rowCount(),\
                                        self.tblCoeff.columnCount()
        for col in range(num_cols):
            for row in range(num_rows):
                item = self.tblCoeff.item(row, col)
                if item:
                    item.setText(str(myQ.fix(simple_eval(item.text()))))
                else:
                    self.tblCoeff.setItem(row,col,QtGui.QTableWidgetItem("0.0"))

        self.tblCoeff.resizeColumnsToContents()
        self.tblCoeff.resizeRowsToContents()
Exemplo n.º 20
0
 def _store_entry(source):
     if self.spec_edited:
         self.stim_freq = simple_eval(source.text()) / fb.fil[0]['f_S']
         self.spec_edited = False # reset flag
         self.draw()