#!/usr/bin/env python

# (c) 2010 oswald berthold
#     during topology workshop, tm10

# - read usrp_spectrum_navigation log data, essentially the
#   output of usrp_spectrum_sense.py over a band of 800M - 2.46G
# - gps-tagged
# - multiple scans each with 2214*256 entries have to be split into
#   separate files
# - make very wide landscape format plots, ca. 4000xY pixels

import time, sys
import numpy as np
import csv
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.ticker as ticker
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm


def dBm2mW(x):
    return 10**(x/10)/1000

#fname = "data/usrp_spectrum_navigation-20100205-141133-14.0-100.dat"
#fname = "data/usrp_spectrum_navigation-20100205-160603-2214.0-100.dat"


#reader = csv.reader(open(fname, "r"), delimiter="\t")
#rec = np.recfromcsv(fname, )

chunklen = 2214*256
numchunk = 1
i = 1
for i in range(30,33):
#for i in range(1,1+1):
    fname = "../data/usn-05-16-%d.dat" % i
    print "fname:", fname
    r = mlab.csv2rec(fname, delimiter="\t",
                     names=["freq", "dbm", "N", "E", "time", "alt", "nix"])

    assert chunklen == r.size

    # # 2D
    #width = (2**15-1)/72 # 2214*256/72 # stupid max img size
    width = 28
    fig = plt.figure(figsize=(width, 8))
    ax = fig.add_subplot(111)
    ticks= np.arange(8e8, 2.6e9, 5e7) # 1e7
    ax.set_xticks(ticks)
    ax.grid(True)
    # plt.plot(r['freq'][:256], \
    #          r['dbm'][:256], axes=ax, clip_on=False)
    
    # plt.plot(r['freq'][257:512], \
    #          r['dbm'][257:512], axes=ax, clip_on=False)

    plt.plot(r['freq'], dBm2mW(r['dbm']), axes=ax, clip_on=False)

    # plt.show()

    fname2 = "../data/usn-05-16-%d-%d.png" % (i, width)

    print "fname2: ", fname2
    plt.savefig(fname2, orientation="landscape", dpi=72)

