import math
import numpy as np


data = np.genfromtxt('medium1', delimiter=',',usecols=(0,1),names=['y','x'])


timestamp = data['x']
state = data['y']

DCH = 3;
FACH = 1;
IDLE = 0;

# Average signal strength in dBm
x=-85.6394849785
# Average data rate in Mbit
data_rate=1.712

# duration for which we count
time=180

#coefficents
a = 0.002768
b = -0.04745
c = 1.263
d = 0.002113

# Power
power_dch_tail= (-3.686e-07)*math.pow(x,3) + (-4.37e-05)*math.pow(x,2) + (-0.001043)*x + 1.145
power_dch= a*(math.exp(b*x)) + c*(math.exp(d*x))
power_fach=0.5
power_idle=0.2

# declare variable to set in loop
time_dch=0
time_fach=0
time_idle=0
tail=4.1
time_dch_tail=0

previous_stamp=0
previous_state=0
count_tails=0
index = 0

# calculate the time spend in each state
while True:
    current_state = state[index]
    current_time = timestamp[index]
    if time < current_time:
        if previous_state == IDLE:
            time_idle += time - previous_stamp
        if previous_state == FACH:
            time_fach += time - previous_stamp
        if previous_state == DCH:
            time_dch += time - previous_stamp
        break

    if previous_state == DCH and current_state != DCH:
        count_tails = count_tails + 1

    if current_state == IDLE and previous_state == IDLE:
        time_idle += current_time - previous_stamp

    if current_state == FACH and previous_state == FACH:
        time_fach += current_time - previous_stamp

    if current_state == DCH and previous_state == DCH:
        time_dch += current_time - previous_stamp

    previous_state = current_state
    previous_stamp = current_time
    index = index + 1

time_dch = time_dch - (tail*count_tails)
time_dch_tail=tail*count_tails

#   \text{Distance} = \text{Upper Bound}-\text{Lower Bound}\\
#           \text{Percentage}_\text{Lower} = \frac{\text{Distance} - \text{Rate}_i + \text{Lower Bound}}{\text{Distance}} \\
#           \text{Percentage}_\text{Upper} = \frac{\text{Distance} + \text{Rate}_i - \text{Upper Bound}}{\text{Distance}} \\
#           \text{Power}_i = \text{Percentage}_\text{Lower} * \text{Power}_\text{lower} + \text{Percentage}_\text{Upper} * \text{Power}_\text{upper} \\


print "Average RSS: ", x
print "Average data rate: ", data_rate

print "Time in DCH: " , time_dch , ", DCH Tail: " , time_dch_tail
print "Time in FACH: ", time_fach
print "Time in IDLE: ", time_idle




# Calculate the energy consumption
energy_dch = time_dch*power_dch
energy_dch_tail = time_dch_tail*power_dch_tail
energy_fach = time_fach*power_fach
energy_idle = time_idle*power_idle
energy_total = energy_dch + energy_dch_tail + energy_fach + energy_idle

print "Energy consumption in Jouls:"
print "DCH: ", energy_dch, ", DCH tail: ", energy_dch_tail
print "FACH: ", energy_fach
print "IDLE: ", energy_idle
print "Total: ", energy_total