scope.py 9.41 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
# 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.
'''


35 36 37 38 39 40 41 42 43 44 45
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

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


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)
        
114
    except ValueError as exVE:
115
        warningMessage = '%s' % exVE
116
    except ZeroDivisionError as exZDE:
117
        warningMessage = '%s' % exZDE
118
    except RuntimeWarning as exRW:
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
        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))
        
195
    except ValueError as exVE:
196
        warningMessage = '%s' % exVE
197
    except ZeroDivisionError as exZDE:
198
        warningMessage = '%s' % exZDE
199
    except RuntimeWarning as exRW:
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
        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'
242 243 244


def scopeTime(figure, waveform, grid):
245 246 247
    '''this method shows a dual time domain scope:
    * s1: channel-1 input signal (blue, float)
    * s2: channel-2 input signal (red, int)
248
    '''   
249 250
    
    # Simulate float system response:
251
    print('Run Scope Time') 
252 253
    figure.clear()
    scopeTimeSubplot = figure.add_subplot(111)
254 255 256 257 258 259 260 261 262 263 264 265
    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)
266 267 268
    
    scopeTimeSubplot.legend().draggable(state=True, use_blit=True)

269 270
    
        
271 272


273
def scopePower(figure, waveform, grid):
274 275 276 277 278 279 280 281
    '''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')
282
    scopePowerSubplot.set_title(r'Signal Power')
283
    scopePowerSubplot.grid(grid)
284 285 286 287 288 289 290 291 292 293
        
    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)

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
    

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)