#!   /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

def measure_spectrum(bit_amp,gain):
  n_repeat=30
  dacinst.set_en(1);
  dacinst.set_ampl_bit(bit_amp)
  dacinst.set_shape(dacinst.SHAPE_SQUARE);
  dacinst.set_frequency(float(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
  return w/n_repeat

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 f in ["8e6","11e6"]:
    w_bkgr=measure_spectrum(0, gain)
    w_sig=measure_spectrum(i, gain)
    plot(w_sig)
    title("signal with background: bit value="+str(i)+" frequency="+f)
    grid()
    savefig("widmo_z_tlem_u"+str(i)+"_f"+f+".png")
    #show()
    clf()
    plot(w_sig-w_bkgr)
    title("signal with background subtracted: bit value="+str(i)+" frequency="+f)
    grid()
    savefig("widmo_po_odjeciu_tla_u"+str(i)+"_f"+f+".png")
    #show()
    clf()



