#!   /usr/bin/env   python
#    coding: utf8

# Copyright CERN, 2011
# Author: Matthieu Cattin <matthieu.cattin@cern.ch>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org
# Last modifications: 30/5/2012

# Import system modules
import sys
import time
import os

# Import specific modules
from numpy import *
from pylab import *


"""
test10: Plot frequency response summary data from test09_freq_resp.txt file

Note: Requires test00.py to run first to load the firmware and
      test09.py to generate the file.
"""

def show_result_graph(points, ch_att):
    pt = array(points)
    freq = pt[:,0]
    a_min = pt[:,1] - pt[:,2]
    a_max = pt[:,1] + pt[:,2]
    cutoff = [-3] * len(points)
    semilogx(freq, ch_att[0], 'b', label='Channel 1')
    semilogx(freq, ch_att[1], 'g', label='Channel 2')
    semilogx(freq, ch_att[2], 'm', label='Channel 3')
    semilogx(freq, ch_att[3], 'c', label='Channel 4')
    semilogx(freq, a_min, 'r:')
    semilogx(freq, a_max, 'r:')
    semilogx(freq, cutoff, 'r', label='-3dB')
    grid(color='k', linestyle='--', linewidth=1)
    legend(loc='upper left')
    show()
    return 0

def main (default_directory='.'):

    # Open test09_freq_resp.txt file in read mode
    file_name = "test09_freq_resp.txt"
    f = open(file_name, 'r+')

    # Read file
    points = []
    ch_att = [[],[],[],[]]
    for line in f:
        freq,expect_val,tol,ch1,ch2,ch3,ch4 = line.split(',')
        points.append([float(freq),float(expect_val),float(tol)])
        ch_att[0].append(float(ch1))
        ch_att[1].append(float(ch2))
        ch_att[2].append(float(ch3))
        ch_att[3].append(float(ch4))
    f.close()

    # Plot results
    show_result_graph(points, ch_att)


if __name__ == '__main__' :
    main()
