#!   /usr/bin/env   python

# Author:
# Wojciech M. Zabolotny <wzab@ise.pw.edu.pl>
# Institute of Electronic Systems, Warsaw University of Technology
# Based on:
# Copyright Creotech SA, 2015
# Author: Marek Guminski <marek.guminski@creotech.pl>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org


import sys
import time
import os
import csr
import time
import numpy
from pylab import *
import scipy
import scipy.signal
#import scipy.io.numpyio as nio

from spec import *
from ad9516 import *
from dac import *
from ptsexcept import PtsCritical


"""
test01: 
    DAC tests
"""


FIRMWARE_PATH = '/../syn/spec_top.bin'


card=None
default_directory='.'
suite=None

delay = 0;

carrier=spec( FIRMWARE_PATH, 1, True );
    

sys_pll = ad9516(carrier);
dacinst = dac(carrier);
n_samples = 16384

gen_figs = False

def measure_spectrum(bit_amp,gain,f):
  n_repeat=30
  #n_chans=16
  dacinst.set_en(1);
  dacinst.set_ampl_bit(bit_amp)
  dacinst.set_shape(dacinst.SHAPE_SQUARE);
  dacinst.set_frequency(f);
  time.sleep(1.0)
  os.system("./acq.sh "+str(n_samples*n_repeat)+" "+gain)
  print bit_amp
  with open("data.bin","rb") as fin:
    x=fin.read(512) # Discard header
    d=numpy.fromfile(file=fin,dtype=numpy.int16).reshape(n_samples*n_repeat,4)
    for i in range(0,n_repeat):
      #print i
      y=range(n_samples*i,n_samples*(i+1))
      dd=scipy.signal.detrend(d[y,0])
      #dd=scipy.signal.detrend(dd)
      wt=abs(scipy.fft(dd))
      if i==0:
         w=wt*wt
      else:
         w+=wt*wt
    #Now we also average power in n_chan consecutive channels 
    #wa=w.reshape(n_samples/n_chans,n_chans)
    #wa=numpy.sum(wa,1)/n_chans
  return w/n_repeat
#Test frequencies
f=["10.512e6","12.121e6"]
results=[[],[]]
for i in [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192]:
#for i in [1,2,4]:
  if i < 512:
     gain = "1"
  else:
     gain = "10"
  for nf in range(0,len(f)):
    fm=float(f[nf])
    #Measure the spectrum of the background noise
    w_bkgr=measure_spectrum(0, gain,fm)
    w_sig_bk=measure_spectrum(i, gain,fm)
    w_sig=w_sig_bk-w_bkgr
    if gen_figs:
      plot(w_sig_bk)
      title("s+b: bit value="+str(i)+" frequency="+f[nf])
      grid()
      savefig("widmo_z_tlem_u"+str(i)+"_f"+f[nf]+".png")
      #show()
      clf()
      plot(w_sig)
      title("s+b-b: bit value="+str(i)+" frequency="+f[nf])
      grid()
      savefig("widmo_po_odjeciu_tla_u"+str(i)+"_f"+f[nf]+".png")
      #show()
      clf()
    #Calculate the power of the signal
    #Expected position of the signal
    n_pos=(n_samples*float(f[nf]))/100e6+1
    #Mean power (with noise!)
    m_pow=sum(w_sig_bk)/n_samples
    #Power of the signal 
    s_pow=sum(w_sig[(n_pos-2):(n_pos+3)])/5
    results[nf].append([i,s_pow, m_pow])
for nf in range(0,len(f)):
    print "Frequency="+f[nf]
    for i in range(0,len(results[nf])):
      r=results[nf][i]
      if i==0:
         print "bit=%d P=%g P/Pt=%g" % (r[0], r[1], r[1]/r[2])
      else:
         print "bit=%d P=%g P/Pt=%g ratio=%g" % (r[0], r[1], r[1]/r[2], r[1]/results[nf][i-1][1])

