# from pylayers.util.save import *
from __future__ import print_function
import pickle
import pandas as pd
import h5py
import matplotlib.pyplot as plt
import numpy as np
import pdb
import doctest
import os
import glob
"""
.. currentmodule:: pylayers.simu.exploit_simulnet
.. autosummary::
:members:
"""
[docs]class exploit(object):
"""
This class is for exploitation of simulnet output
"""
def __init__(self, filename='simulnet_TA-Office.h5'):
sa = Save()
self.data = sa.load(filename)
# self.load(filename)
self.saveopt = self.data['saveopt']
self.data.pop('saveopt')
self.type = self.saveopt['type']
self.nodes = self.type
self.layout = Layout(self.saveopt['Layout'])
# color=['r','g','b','k','y','k','k']
color = ['r', 'g', 'b', 'k', 'y', 'k', 'k']
self.agents = []
self.ap = []
for i in self.saveopt['type'].keys():
if self.saveopt['type'][i] == 'ag':
self.agents.append(i)
else:
self.ap.append(i)
self.colors = {}
for i, n in enumerate(self.nodes):
self.colors[n] = color[i]
self.checkpoint = 10.
# def load(self,filename):
# f = h5py.File(filename)
# attrs=f.attrs['attributes']
# self.metadata = pickle.loads(attrs)
# keys = f.keys()
# for k in keys:
# pd.read_hdf(filename,key=k)
[docs] def plot_traj(self, ap=True, ag=True, fig=[], cps=20, ans=40, **kwargs):
"""
Parameters
----------
ap : boolean
ag : boolean
fig : list
cps : int
ans : int
"""
if fig == []:
fig = plt.figure('trajectory', figsize=(20, 5), dpi=100)
fig, ax = self.layout.showG('s', fig=fig, nodes=False, **kwargs)
if ag:
for i, n in enumerate(self.agents):
cp = 0
for j, p in enumerate(self.data[n]['p']):
if j == 0:
ax.plot(p[0], p[1], 'o', color=self.colors[
n], label='agent #' + n, **kwargs)
else: # to avoid multiple label in legend
ax.plot(
p[0], p[1], 'o', color=self.colors[n], **kwargs)
if j % self.checkpoint == 0:
ax.plot(p[0], p[1], 'o', color=self.colors[n], ms=cps)
plt.text(p[0] - 0.2, p[1] - 0.2, str(cp), fontsize=10)
cp = cp + 1
if ap:
for i, n in enumerate(self.ap):
if n == '6' or n == '9':
color = 'r'
else:
color = 'g'
ax.plot(self.data[n]['p'][0, 0], self.data[n]['p'][0, 1],
'^', color=color, label='AP #' + n, ms=ans)
ax.grid('off')
ax.legend(numpoints=1)
return fig, ax
[docs] def plot_ldp(self, node, rat='rat1', ldp='Pr', fig=[], ax=[], title=[], grid=False, **kwargs):
"""
Parameters
----------
node
rat
ldp
fig
ax
title
grid
"""
if ldp == 'Pr':
title_name = 'Received Power'
y_name = 'Power (dBm)'
x_name = 'time (s)'
elif ldp == 'TOA':
title_name = 'Excess time of arrival'
y_name = 'delay (ns)'
x_name = 'time (s)'
if fig == []:
fig = plt.figure('trajectory', figsize=(20, 5), dpi=100)
if ax == []:
nbax = len(self.nodes) - 1
fig, ax = plt.subplots(nbax, 1)
marker = kwargs['marker']
time = np.linspace(
0, self.saveopt['duration'], self.saveopt['nbsamples'])
cptime = time[::self.checkpoint]
label = [str(i) for i in np.arange(0, len(cptime))]
ax_i = 0
for j, n in enumerate(self.nodes):
if n != node:
value = self.data[node][n][rat][ldp][:, 0]
checkpointvalue = self.data[node][
n][rat][ldp][::self.checkpoint, 0]
leg = ax[ax_i].scatter(
time, value, color=self.colors[n], marker=marker)
ax[ax_i].scatter(
cptime, checkpointvalue, color=self.colors[n], **kwargs)
if title == []:
ax[ax_i].set_title(title_name + ' for link ' + self.type[
node] + node + ' and ' + self.type[n] + n)
elif title == False:
ax[ax_i].set_title(
'link ' + self.type[node] + node + ' and ' + self.type[n] + n)
else:
ax[ax_i].set_title(title)
ax[ax_i].set_xlabel(x_name)
ax[ax_i].set_ylabel(y_name)
for i in range(len(label)):
ax[ax_i].annotate(
label[i], (cptime[i], checkpointvalue[i] + 2))
if grid:
ax[ax_i].grid('on')
ax_i = ax_i + 1
fig.tight_layout()
return fig, ax, leg
[docs] def plot_ldps(self, node, rat='rat1', fig=[], ax=[]):
"""
Parameters
----------
node
rat
fig
ax
"""
fig, ax, leg = self.plot_ldp(
node, rat='rat1', ldp='Pr', fig=fig, ax=ax, title=False, marker='o', s=100)
ax2 = []
for a in ax:
ax2.append(a.twinx())
fig, ax, leg2 = self.plot_ldp(
node, rat='rat1', ldp='TOA', fig=fig, ax=ax2, title=False, grid=True, marker='x', s=100)
fig.legend(
(leg, leg2), ('Received Power', 'Excess time of arrival'))
[docs] def plot_poserr(self, n=[], fig=[], ax=[], **kwargs):
"""
Parameters
----------
"""
# if fig ==[]:
# fig = plt.figure('pos err', figsize=(20, 5), dpi=100)
# if ax==[]:
# ax = fig.add_subplot(111)
if n == []:
n = self.agents[0]
marker = kwargs['marker']
err = np.sqrt(
np.sum((self.data[n]['p'] - self.data[n]['pe']) ** 2, axis=1))
pnan = np.where(np.isnan(err))[0]
err[pnan] = 0
checkpointvalue = err[::self.checkpoint]
time = np.linspace(
0, self.saveopt['duration'], self.saveopt['nbsamples'])
cptime = time[::self.checkpoint]
label = [str(i) for i in np.arange(0, len(cptime))]
leg = ax.scatter(time, err, color=self.colors[n], marker=marker)
ax.scatter(cptime, checkpointvalue, color=self.colors[n], **kwargs)
for i in range(len(label)):
ax.annotate(label[i], (cptime[i], checkpointvalue[i]))
ax.grid('on')
fig.tight_layout()
return fig, ax, leg
# import numpy as np
# import matplotlib.pyplot as plt
# fig, ax1 = plt.subplots()
# t = np.arange(0.01, 10.0, 0.01)
# s1 = np.exp(t)
# ax1.plot(t, s1, 'b-')
# ax1.set_xlabel('time (s)')
# Make the y-axis label and tick labels match the line color.
# ax1.set_ylabel('exp', color='b')
# for tl in ax1.get_yticklabels():
# tl.set_color('b')
# ax2 = ax1.twinx()
# s2 = np.sin(2*np.pi*t)
# ax2.plot(t, s2, 'r.')
# ax2.set_ylabel('sin', color='r')
# for tl in ax2.get_yticklabels():
# tl.set_color('r')
# plt.show()
if __name__ == '__main__':
plt.ion()
X = exploit()
# X.plot_traj()
# f,a=X.plot_ldp('1',ldp='Pr')
# f,a=X.plot_ldp('1',ldp='TOA',fig=f,ax=a)
# X.plot_ldps('1')
fig, axes = plt.subplots(2, 1, figsize=(5, 5))
f, ax, leg = X.plot_poserr('1', marker='o', s=100, fig=fig, ax=axes[0])
f, ax, leg2 = X.plot_poserr('2', marker='o', s=100, fig=fig, ax=axes[1])
axes[0].set_xlabel('time (s)')
axes[1].set_xlabel('time (s)')
axes[0].set_ylabel('error (m)')
axes[1].set_ylabel('error (m)')
axes[0].axis([0, 10, 0, 7])
axes[1].axis([0, 10, 0, 7])
axes[1].set_ylabel('error (m)')
fig.legend((leg, leg2), ('agent 1', 'agent 2'), numpoints=1)
f2 = plt.figure(figsize=(15, 15))
f2, ax2 = X.plot_traj(ms=7, cps=17, ans=10, fig=f2)
ax2.axis([-30, 17, 4, 17])
figname = 'mobility2'
fignb = 0
fig.savefig('./' + figname + '_' + str(fignb).zfill(2) + '.pdf',
format='pdf', bbox_inches='tight', pad_inches=0)
fignb = 1
f2.savefig('./' + figname + '_' + str(fignb).zfill(2) + '.pdf',
format='pdf', bbox_inches='tight', pad_inches=0)