def test_niculescu2003_sim(self): """Test niculescu2003 default simulation.""" sim = Simulation(self.net) sim.run() i = 0 for node in self.net.nodes(): i += 1 self.assertTrue(len(node.memory.get('pos', [None, None])) == 2\ or 'tp' in node.memory) self.net.savefig(fname=get_path(DATETIME_DIR, "dv-%s" % self.n), title="DV hop Default Simulation - %s nodes" % self.n, x_label="X", y_label="Y") print i, self.net.__len__() print self.net.nodes()[1].get_dic() print self.net.nodes()[20].get_dic() #print self.net.get_dic() print self.net.nodes()[0].type, \ self.net.nodes()[0].get_dic()['Info']['position'],\ self.net.nodes()[0].memory['tp'] for node in self.net.nodes(): act = node.get_dic()['Info']['position'] est = node.memory['pos'] if node.type == 'C': err = sqrt(sum(pow(act - est, 2))) print node.type, act, est, err
def test_niculescu2003_sim(self): """Test niculescu2003 default simulation.""" sim = Simulation(self.net) sim.run() i=0; for node in self.net.nodes(): i += 1 self.assertTrue(len(node.memory.get('pos', [None, None])) == 2\ or 'tp' in node.memory) self.net.savefig(fname=get_path(DATETIME_DIR, "dv-%s" %self.n), title="DV hop Default Simulation - %s nodes" % self.n, x_label="X", y_label="Y") print i, self.net.__len__() print self.net.nodes()[1].get_dic() print self.net.nodes()[20].get_dic() #print self.net.get_dic() print self.net.nodes()[0].type, \ self.net.nodes()[0].get_dic()['Info']['position'],\ self.net.nodes()[0].memory['tp'] for node in self.net.nodes(): act = node.get_dic()['Info']['position'] est = node.memory['pos'] if node.type=='C': err = sqrt(sum(pow(act - est, 2))) print node.type, act, est, err
n_range = np.arange(11, max_n, 5) for n in n_range: # network topology setup Node.cid = 1 net_gen = Toplogy(degree=2, n_count=n) net = net_gen.generate_star_ehwsnnetwork(x_radius=x_radius, y_radius=y_radius, sector=1, clusters=clusters, is_random=1) net.name = "New scheme with EHWSN" # saving topology as PNG image net.savefig(fname=get_path(DATETIME_DIR, "star-%s" % n), title="EHWSN nodes around coordinator - %s nodes" % n, x_label="X", y_label="Y") # simulation start net.algorithms = ((Beacon, {'informationKey': 'Data'}), ) coordinator_node = net.nodes()[0] coordinator_node.memory['Data'] = 'Beacon 1' sim = Simulation(net) sim.run() # simulation ends # capturing results consume = [] energy = []
def gethtmlScatter(x, y, fname, folder="", axis_range={}, labels=None, xlabel="X", ylabel="Y", title=None, comment=".", **kwargs): w = 100 h = 100 title = title or fname report = kwargs.pop('report', comment) plot_type = 'scatter' if 'plot_type' in kwargs: plot_type = kwargs.pop('plot_type') plot_options = [""] if 'plot_options' in kwargs: plot_options = kwargs.pop('plot_options') show_range = kwargs.pop('show_range', 0) circle = "" if show_range: circle = "allowPointSelect:true, marker: { states: { select: { lineColor: 'red', radius: " + str(show_range) + "}}}," series_data = "" series_line = "" k=0 if len(y)>10: series_data += ''' { name: "''' + (labels[k] if k < len(labels) else "") + '''", ''' + (plot_options[k] if k < len(plot_options) else "") + ''' data: ''' + str(y) + ''', ''' + circle + ''' }, ''' else: k=0 for series in y: series_data += ''' { name: "''' + (labels[k] if k < len(labels) else "") + '''", ''' + (plot_options[k] if k < len(plot_options) else "") + ''' data: ''' + str(series) + ''', ''' + circle + ''' }, ''' k += 1 if k > 1: j = 0 for yy in y[1]: try: #print yy['name'], y[1][j]['name'] if yy['name'] == y[2][j]['name']: yyx, yyy = yy['x'], yy['y'] yyx2, yyy2 = y[2][j]['x'], y[2][j]['y'] yyx2 = w + 3 if yyx2 > w + 3 else yyx2 yyx2 = -3 if yyx2 < -3 else yyx2 yyy2 = h + 3 if yyy2 > h+3 else yyy2 yyy2 = -3 if yyy2 < -3 else yyy2 series_line += "chart.renderer.path(['M', chart.xAxis[0].toPixels(" + str(yyx) + \ "), chart.yAxis[0].toPixels(" + str(yyy) + \ "), 'L', chart.xAxis[0].toPixels(" + str(yyx2) + \ "), chart.yAxis[0].toPixels(" + str(yyy2) + \ ")]).attr({'stroke-width': 1, stroke: 'gray'}).add(group);" j += 1 except (ValueError, Exception) as exc: print exc break contents = '''<!DOCTYPE html> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>'''+title+'''</title> <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script> <style type='text/css'> </style> <script type='text/javascript'>//<![CDATA[ var chart; var w; $(function () { var group; vis = true; w = $('#container').width() $('#container').highcharts({ credits: { enabled: false }, exporting: { filename: "''' + fname + '''" }, legend: { margin: -5, padding: 0, y: -5, //layout: 'vertical', align: 'right', verticalAlign: 'middle', shadow: true, backgroundColor: '#FFFFFF', title: { //text: 'Farrukh Shahzad<br/>PhD, KFUPM<br/>Nov. 2015</span>', style: {fontStyle: 'italic', fontSize: '10px'} } }, chart: { zoomType: 'xy', panning: true, panKey: 'shift', type: "''' + plot_type + '''" }, title: { text: "''' + title + '''" }, subtitle: { text: "''' + comment + '''", style: {color:'black', fontSize: '18px', fontFamily: 'Times'} }, tooltip: { borderRadius: 10, crosshairs: [{width: 1, color: 'gray', dashStyle: 'shortdot'}, {width: 1, color: 'gray', dashStyle: 'shortdot'}], pointFormat: 'X: {point.x:.1f}, Y: {point.y:.1f}', headerFormat: '<b>Node: {point.key}</b>, {series.name}<br />', shared: true }, xAxis: [{ // Primary xAxis //minRange : 5, gridLineWidth: 1, min: '''+ json.dumps(axis_range.get('xmin')) + ''', max: '''+ json.dumps(axis_range.get('xmax')) + ''', title: { text: "'''+ xlabel + '''", y: -5, style: {color:'black'}} }], yAxis: [{ // Primary yAxis lineWidth: 1, minPadding: 0.0, maxPadding: 0.0, min: '''+ json.dumps(axis_range.get('ymin')) + ''', max: '''+ json.dumps(axis_range.get('ymax')) + ''', title: {text: "'''+ ylabel + '''", x: 5, style: {color:'black'}} }], series: [''' + series_data + ''' ] }, function (chart) { // on complete group = chart.renderer.g().add(); '''+ series_line + ''' });''' + \ ("$('#button').click(function () {if (vis) group.hide(); else group.show(); vis = !vis; });" if len(series_line)>1 else "") + \ ''' }); //]]> </script> </head> <body> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="http://code.highcharts.com/modules/data.js"></script> <script src="http://code.highcharts.com/highcharts-more.js"></script> <script src="http://code.highcharts.com/modules/exporting.js"></script> <table border="0" align="center"><tr><td align="center"> <span id="container" style="height: 600px; margin: auto; min-width: 600px; max-width: 600px"></span> ''' + ("<button id='button'>Toggle Error Lines</button>" if len(series_line)>1 else "") + \ '''</td><td style="font-family: 'Lucida Console'; font-size: 12px; height: 600px; padding: 25px; max-width: 500px"> <span id="report" ><h3>''' + title + '''</h3>''' + \ report + '''<br><br>Click on the legend on the bottom to hide/show series</span> </td></tr></table> </body> </html> ''' path = get_path(folder,fname) + ".html" if 'open' in kwargs: browseLocal(contents, filename=path) else: strToFile(contents, filename=path)
'name': str(node.id), 'color': 'blue', 'marker': {'radius': '5'}}) nn = net.__len__() n_anchors = (int)(nn * p_anchors/100.0) avg_deg = round(net.avg_degree()) comm_range = node.commRange # set the network name based on no. of Nodes, degree and Comm. Range net.name = "%s*%s - $N=$%s(%s), $D=$%s, $R=$%s m\n$A=$%s$\\times 10^3m^2$, $ND=$%s$/10^3.m^2$" \ % (net_gen.name, str(region), nn, n_anchors, round(avg_deg,1), round(comm_range,1), round(net_gen.area/1000.0, 2), round(net_gen.net_density*1000, 1)) filename = (net.name.split("\n")[0]).replace("$","") folder = DATETIME_DIR+ "-" + net_gen.name net.savefig(fname=get_path(folder, filename), title=net.name, x_label="X-coordinate (m)", y_label="Y-coordinate (m)", show_labels=True, format="pdf") # Now select the algorithm for simulation net.algorithms = ((DVHop, {'truePositionKey': 'tp', 'hopsizeKey': 'hs', 'dataKey': 'I' }), (Trilaterate, {'truePositionKey': 'tp', 'hopsizeKey': 'hs', 'positionKey': 'pos'+str(region), 'dataKey': 'I'}), ) start_time = time.time()
(w, h / 4)]]) #net2.save_json(get_path(TOPOLOGY_DIR, net_gen.name + ".json"), scale=(6, 5)) print Node.cid #net, p_nk = net_gen.get_clusters(net, clusters=clusters, method="Random") #print Node.cid n_anchors = net_gen.anchors node = net.nodes()[0] # saving topology as PNG image avg_deg = net.avg_degree() na = net.__len__() net.name = "%s, $N=$%s(%s), $D=$%s, $R=$%s m\n$A=$%s$\\times 10^3m^2$, $N_D=$%s$/10^3.m^2$" \ % (net_gen.name, na, n_anchors, round(avg_deg,1), round(node.commRange,1), round(net_gen.area/1000.0, 2), round(net_gen.net_density*1000, 1)) filename = (net.name.split("\n")[0]).replace("$", "") net.savefig(fname=get_path(TOPOLOGY_DIR, filename), title=net.name, xlabel="X-coordinate (m)", ylabel="Y-coordinate (m)", show_labels=True, format="pdf") print net.__len__(), avg_deg, node.commRange # # # Node.cid = 1 # #net_gen = Toplogy(n_count=n, degree=degree, n_max=n, n_min=n, connected=False) # net = net_gen.generate_grid_network(name="C-shaped Grid", randomness=0.2, # cut_shape=[[(w/4,3*h/4), (w, h/4)]]) # f_anchors = (int)(100 / p_anchors)
} }) avg_deg = round(net.avg_degree()) comm_range = node.commRange # set the network name based on no. of Nodes, degree and Comm. Range net.name = "%s(%s) - $N=$%s(%s), $D=$%s, $R=$%s m\n$A=$%s$\\times 10^3m^2$, $ND=$%s$/10^3.m^2$" \ % (net_gen.name, vary, nn, n_anchors, round(avg_deg,1), round(comm_range,1), round(net_gen.area/1000.0, 2), round(net_gen.net_density*1000, 1)) filename = (net.name.split("\n")[0]).replace("$", "") area = "A: %s x 1000 m^2, ND: %s /1000 m^2" % (round( net_gen.area / 1000.0, 2), round(net_gen.net_density * 1000, 1)) net.savefig(fname=get_path(folder, filename), title=net.name, x_label="X-coordinate (m)", y_label="Y-coordinate (m)", show_labels=False, format="pdf") # Now select the algorithm for simulation net.algorithms = ( (DVHop, { 'truePositionKey': 'tp', 'hopsizeKey': 'hs', 'dataKey': 'I' }), (Trilaterate, { 'truePositionKey': 'tp',
n_power = [] n_range = np.arange(20, max_n + 1, 10) start_time = time.time() project_name = "IWSN" folder = DATETIME_DIR + "-" + project_name # network topology setup Node.cid = 1 net_gen = Manual() net = net_gen.generate_zigbee_network(name="Zigbee") n = len(net) net.name = "Zigbee Experiment" + "\nN=%s, R=%s m" \ %(n, global_settings.COMM_RANGE) filename = net.name.replace("\n", "-") # saving topology as PNG image net.savefig(fname=get_path(folder, filename), title=net.name, xlabel="X-coordinate (m)", ylabel="Y-coordinate (m)", show_labels=True, format="png", label_color='yellow') print net.__len__(), len(net) net.reset() Node.cid = 1 net_gen = Manual() net = net_gen.generate_mesh_network(name="WirelessHart Mesh") n = len(net) net.name = "WirelessHart Experiment" + "\nN=%s, R=%s m" \ %(n, global_settings.COMM_RANGE)
positions.append({ 'x': net.pos[node][0], 'y': net.pos[node][1], 'name': 'Node: ' + str(node.id) }) nn = net.__len__() n_anchors = (int)(nn * p_anchors / 100.0) avg_deg = round(net.avg_degree()) comm_range = node.commRange # set the network name based on no. of Nodes, degree and Comm. Range net.name = "%s - $N=$%s(%s), $D=$%s, $R=$%s m\n$A=$%s$\\times 10^3m^2$, $ND=$%s$/10^3.m^2$" \ % (net_gen.name, nn, n_anchors, round(avg_deg,1), round(comm_range,1), round(net_gen.area/1000.0, 2), round(net_gen.net_density*1000, 1)) filename = (net.name.split("\n")[0]).replace("$", "") net.savefig(fname=get_path(DATETIME_DIR, filename), title=net.name, x_label="X-coordinate (m)", y_label="Y-coordinate (m)", show_labels=False, format="pdf") # Now select the algorithm for simulation net.algorithms = ( (DVHop, { 'truePositionKey': 'tp', 'hopsizeKey': 'hs', 'dataKey': 'I' }), (Trilaterate, { 'truePositionKey': 'tp',
cut_shape=[[(w/4,3*h/4), (w, h/4)]]) #net2.save_json(get_path(TOPOLOGY_DIR, net_gen.name + ".json"), scale=(6, 5)) print Node.cid #net, p_nk = net_gen.get_clusters(net, clusters=clusters, method="Random") #print Node.cid n_anchors = net_gen.anchors node=net.nodes()[0] # saving topology as PNG image avg_deg = net.avg_degree() na = net.__len__() net.name = "%s, $N=$%s(%s), $D=$%s, $R=$%s m\n$A=$%s$\\times 10^3m^2$, $N_D=$%s$/10^3.m^2$" \ % (net_gen.name, na, n_anchors, round(avg_deg,1), round(node.commRange,1), round(net_gen.area/1000.0, 2), round(net_gen.net_density*1000, 1)) filename = (net.name.split("\n")[0]).replace("$","") net.savefig(fname=get_path(TOPOLOGY_DIR, filename), title=net.name, xlabel="X-coordinate (m)", ylabel="Y-coordinate (m)", show_labels=True, format="pdf") print net.__len__(), avg_deg, node.commRange # # # Node.cid = 1 # #net_gen = Toplogy(n_count=n, degree=degree, n_max=n, n_min=n, connected=False) # net = net_gen.generate_grid_network(name="C-shaped Grid", randomness=0.2, # cut_shape=[[(w/4,3*h/4), (w, h/4)]]) # f_anchors = (int)(100 / p_anchors) # for node in net.nodes(): # if node.id % f_anchors == 0: # anchor nodes # node.compositeSensor = (TruePosSensor,) # node.type = 'C' # Anchors
k += 1 Node.cid = 1 net_gen = Topology(n_count=n, connected=False, commRange=global_settings.COMM_RANGE, comm_range=global_settings.COMM_RANGE) net = net_gen.generate_grid_network(name="Grid", randomness=0, p_anchors=None) net, p = net_gen.get_clusters(net, clusters=clusters, method="EM") node = net.nodes()[int(n/2)] net.remove_node(node) n = len(net) net.name = "Grid Topology" + "\nN=%s, R=%s m" \ %(n, global_settings.COMM_RANGE) filename = net.name.replace("\n", "-") # saving topology as PNG image net.savefig(fname=get_path(folder, filename), title=net.name, xlabel="X-coordinate (m)", ylabel="Y-coordinate (m)", show_labels=True, format="png", label_color='yellow') net.name = filename net.save_json(get_path(folder, filename+".json"), scale=(1, 1)) print net.__len__(), len(net) coordinator_node = net.nodes()[n-1] coordinator_node.type = 'B' coordinator_node.compositeSensor = (NeighborsSensor,) # (TruePosSensor,) # simulation start net.algorithms = ((Beacon, {'informationKey': 'Data', 'detination': coordinator_node}),) coordinator_node.memory['Data'] = 'Beacon 1'
# saving topology as PNG image #n_anchors = (int)(na * p_anchors/100.0) net.name = "%s - $N=$%s(%s), $D=$%s, $R=$%s m\n$A=$%s$\\times 10^3m^2$, $N_D=$%s$/10^3.m^2$, %s=%s" \ % (net_gen.name, na, clusters, round(avg_deg,1), round(node.commRange,1), round(net_gen.area/1000.0, 2), round(net_gen.net_density*1000, 1), global_settings.CHANNEL_TYPE, global_settings.DOI) filename = (net.name.split("\n")[0]).replace("$","") #net.savefig(fname=get_path(TOPOLOGY_DIR, filename), title=net.name, # xlabel="X-coordinate (m)", ylabel="Y-coordinate (m)", # show_labels=True, format="png") net2, p = net_gen.get_clusters(net, clusters=clusters, method="EM") node = net2.nodes()[int(n/2)] net2.remove_node(node) net2.savefig(fname=get_path(TOPOLOGY_DIR, filename+"-anchors"), title=net.name, xlabel="X-coordinate (m)", ylabel="Y-coordinate (m)", show_labels=True, format="png") n_anchors = net_gen.anchors avg_deg = net2.avg_degree() na = net2.__len__() print na, avg_deg, node.commRange, net_gen.area, net_gen.net_density from networkx import * import networkx.algorithms.approximation print networkx.info(net) #print networkx.edges(net) #print networkx.algorithms.approximation.k_components(net) print networkx.algorithms.approximation.average_clustering(net)
def gethtmlmultiplots(x, y, fname, folder="", axis_range={}, labels=None, xlabel="X", ylabel="Y", title=None, comment=".", **kwargs): w = 100 h = 100 title = title or fname report = kwargs.pop('report', comment) plot_type = 'scatter' if 'plot_type' in kwargs: plot_type = kwargs.pop('plot_type') plot_options = [""] if 'plot_options' in kwargs: plot_options = kwargs.pop('plot_options') series_data = "" k=0 if len(y)>10: series_data += ''' { name: "''' + (labels[k] if k < len(labels) else "") + '''", ''' + (plot_options[k] if k < len(plot_options) else "") + ''' data: ''' + str(y) + ''', }, ''' else: for series in y: series_data += ''' { name: "''' + (labels[k] if k < len(labels) else "") + '''", ''' + (plot_options[k] if k < len(plot_options) else "") + ''' data: ''' + str(series) + ''', }, ''' k += 1 contents = '''<!DOCTYPE html> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>'''+title+'''</title> <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script> <style type='text/css'> </style> <script type='text/javascript'>//<![CDATA[ var chart; var w; $(function () { var group; vis = true; w = $('#container').width() $('#container').highcharts({ credits: { enabled: false }, exporting: { filename: "''' + fname + '''" }, legend: { margin: -5, padding: 0, y: -5, //layout: 'vertical', align: 'right', verticalAlign: 'middle', shadow: true, backgroundColor: '#FFFFFF', title: { //text: 'Farrukh Shahzad<br/>PhD, KFUPM<br/>Nov. 2015</span>', style: {fontStyle: 'italic', fontSize: '10px'} } }, chart: { zoomType: 'xy', panning: true, panKey: 'shift', type: "''' + plot_type + '''" }, title: { text: "''' + title + '''" }, subtitle: { text: "''' + comment + '''", style: {color:'black', fontSize: '18px', fontFamily: 'Times'} }, tooltip: { borderRadius: 10, crosshairs: [{width: 1, color: 'gray', dashStyle: 'shortdot'}, {width: 1, color: 'gray', dashStyle: 'shortdot'}], pointFormat: '{point.x:.1f}, {point.y:.1f}', headerFormat: '<b>{series.name}</b><br />', shared: true }, xAxis: [{ // Primary xAxis gridLineWidth: 1, min: '''+ json.dumps(axis_range.get('xmin')) + ''', max: '''+ json.dumps(axis_range.get('xmax')) + ''', title: { text: "'''+ xlabel + '''", y: -5, style: {color:'black'}} }], yAxis: [{ // Primary yAxis lineWidth: 1, minPadding: 0.0, maxPadding: 0.0, min: '''+ json.dumps(axis_range.get('ymin')) + ''', max: '''+ json.dumps(axis_range.get('ymax')) + ''', title: {text: "'''+ ylabel + '''", x: 5, style: {color:'black'}} }], series: [''' + series_data + ''' ] }) }); //]]> </script> </head> <body> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="http://code.highcharts.com/modules/data.js"></script> <script src="http://code.highcharts.com/highcharts-more.js"></script> <script src="http://code.highcharts.com/modules/exporting.js"></script> <table border="0" align="center"><tr><td align="center"> <span id="container" style="height: 600px; margin: auto; min-width: 600px; max-width: 600px"></span> </td><td style="font-family: 'Lucida Console'; font-size: 12px; height: 600px; padding: 25px; max-width: 500px"> <span id="report" ><h3>''' + title + '''</h3>''' + \ report + '''<br><br>Click on the legend on the bottom to hide/show series</span> </td></tr></table> </body> </html> ''' path = get_path(folder,fname) + ".html" if 'open' in kwargs: browseLocal(contents, filename=path) else: strToFile(contents, filename=path)
else: positions.append({ 'x': net.pos[node][0], 'y': net.pos[node][1], 'name': 'Node: ' + str(node.id) }) newpos.append({'x': newx, 'y': newy, 'name': 'Node: ' + str(node.id)}) xestpositions.append(newx) deltapos.append(net.pos[node][0] - newx) avg_deg = round(net.avg_degree()) net.name = "%s - Nodes=%s, Avg degree=%s, Range=%s" \ % (net_gen.name, net.__len__(), int(avg_deg), int(node.commRange)) net.savefig(fname=get_path(TOPOLOGY_DIR, net.name), title=net.name, format='pdf', x_label="X", y_label="Y", show_labels=False) print net.__len__(), avg_deg, node.commRange, n_anchors end_time = time.time() - start_time ntx = 345 comments = "Anchors: " + str(n_anchors) +"="+str(p_anchors) +"%"+ \ ", Runtime(sec): "+ str(round(end_time,2)) + \ ", No. of Tx: " + str(ntx) plotter.gethtmlScatter(xpositions, [anchpositions, positions, newpos], fname="Topology-" + net.name, folder=TOPOLOGY_DIR,
# x_radius=x_radius, y_radius=y_radius, sector=0.7, # cluster_divide=4, randomness=4.8) net = net_gen.generate_gaussian_network(name='', randomness=1) #net = net_gen.generate_grid_network(name="Randomized Grid", randomness=0.7, p_anchors=None) for m in range(2): method = methods[m] net, p_nk = net_gen.get_clusters(net, clusters=clusters, method=method) net.name = "Energy Efficient Clustering-%s\nN=%s, K=%s" \ %(methods2[m], n, clusters) filename = net.name.replace("\n", "-") # saving topology as PNG image net.savefig(fname=get_path(folder, filename), title=net.name, xlabel="X-coordinate (m)", ylabel="Y-coordinate (m)", show_labels=True, format="pdf") print net.__len__(), len(net) # tn = net.neighbors(net.nodes()[1]) # print len(tn), tn # bfs = list(nx.bfs_tree(net, net.nodes()[1])) # print bfs, len(bfs) # print net.nodes()[34].commRange p=nx.shortest_path_length(net) print len(p), p total=1e-3 nn = len(net)-clusters print len(p_nk), p_nk[0][0] for i in range(nn): for k in range(clusters):
Node.cid = 1 #net_gen = NetworkGenerator(n_count=n) #net = net_gen.generate_ring_network(x_radius=x_radius*clusters, y_radius=y_radius*clusters) net_gen = Star(n_count=n) net = net_gen.generate_ring_network(x_radius=x_radius, y_radius=y_radius, sector=0.75) n_anchors = (int)(p_anchors * net.__len__()/100) for node in net.nodes(): if (node.id % n_anchors==0): # anchor nodes node.compositeSensor = (TruePosSensor,) node.type = 'C' # Anchors net.name = "DV on ring" # saving topology as PNG image net.savefig(fname=get_path(TOPOLOGY_DIR, "dv-%s-ring-sect" %n), title="C shaped - %s nodes" % n, x_label="X", y_label="Y") print net.__len__(), net.avg_degree(), node.commRange net.reset() Node.cid = 1 net_gen = Star(n_count=n) net = net_gen.generate_two_ring_network(x_radius=x_radius/2, y_radius=y_radius/2, sector=0.75) n_anchors = (int)(p_anchors * net.__len__()/100) for node in net.nodes(): if (node.id % n_anchors==0): # anchor nodes node.compositeSensor = (TruePosSensor,) node.type = 'C' # Anchors net.name = "DV on ring"
for n in n_range: # network topology setup Node.cid = 1 net_gen = Toplogy(degree=2, n_count=n) net = net_gen.generate_star_ehwsnnetwork( x_radius=x_radius, y_radius=y_radius, sector=1, clusters=clusters, is_random=1) net.name = "New scheme with EHWSN" # saving topology as PNG image net.savefig(fname=get_path(DATETIME_DIR, "star-%s" %n), title="EHWSN nodes around coordinator - %s nodes" %n, x_label="X", y_label="Y") # simulation start net.algorithms = ((Beacon, {'informationKey': 'Data'}), ) coordinator_node = net.nodes()[0] coordinator_node.memory['Data'] = 'Beacon 1' sim = Simulation(net) sim.run() # simulation ends # capturing results consume = [] energy = [] distances = []
node.type = 'C' # Anchors anchpositions.append({'x': net.pos[node][0], 'y': net.pos[node][1], 'name': str(node.id), 'color': 'red', 'marker': {'symbol': 'circle', 'radius': '8'}}) else: node.type = 'N' # Normal node.compositeSensor = ('NeighborsSensor',) positions.append({'x': net.pos[node][0], 'y': net.pos[node][1], 'name': 'Node: ' + str(node.id), 'color': 'blue', 'marker': {'radius': '5'}}) avg_deg = round(net.avg_degree()) comm_range = node.commRange # set the network name based on no. of Nodes, degree and Comm. Range area = "A: %s x 1000 m^2, ND: %s /1000 m^2, DOI: %s" \ %(round(net_gen.area/1000.0, 2), round(net_gen.net_density*1000, 1), round(doi, 1)) net.name = "%s(%s) - $N=$%s(%s), $D=$%s, $R=$%s m\n" \ "$A=$%s$\\times 10^3m^2$, $ND=$%s$/10^3.m^2$, $DOI$=%s" \ % (net_gen.name, vary, nn, n_anchors, round(avg_deg,1), round(comm_range,1), round(net_gen.area/1000.0, 2), round(net_gen.net_density*1000, 1), round(doi, 1)) filename = (net.name.split("\n")[0]).replace("$","") net.savefig(fname=get_path(folder, filename), title=net.name, x_label="X-coordinate (m)", y_label="Y-coordinate (m)", show_labels=True, format="pdf") net.reset()
'marker': {'symbol': 'circle', 'radius': '8'}}) else: positions.append({'x': net.pos[node][0], 'y': net.pos[node][1], 'name': 'Node: ' + str(node.id)}) nn = net.__len__() n_anchors = (int)(nn * p_anchors/100.0) avg_deg = round(net.avg_degree()) comm_range = node.commRange # set the network name based on no. of Nodes, degree and Comm. Range net.name = "%s - $N=$%s(%s), $D=$%s, $R=$%s m\n$A=$%s$\\times 10^3m^2$, $ND=$%s$/10^3.m^2$" \ % (net_gen.name, nn, n_anchors, round(avg_deg,1), round(comm_range,1), round(net_gen.area/1000.0, 2), round(net_gen.net_density*1000, 1)) filename = (net.name.split("\n")[0]).replace("$","") net.savefig(fname=get_path(DATETIME_DIR, filename), title=net.name, x_label="X-coordinate (m)", y_label="Y-coordinate (m)", show_labels=False, format="pdf") # Now select the algorithm for simulation net.algorithms = ((DVHop, {'truePositionKey': 'tp', 'hopsizeKey': 'hs', 'dataKey': 'I' }), (Trilaterate, {'truePositionKey': 'tp', 'hopsizeKey': 'hs', 'positionKey': 'pos', 'dataKey': 'I'}), ) start_time = time.time()
for n in n_range: # network topology setup Node.cid = 1 net_gen = LOS(degree=2, n_count=n) net = net_gen.generate_network(x_radius=x_radius, y_radius=y_radius, sector=0.5, clusters=clusters, is_random=0) net.name = "Yokogawa Industrial Sensor Experiment" # saving topology as PNG image net.savefig( fname=get_path(DATETIME_DIR, "topology-%s" % n), title="Industrial sensor nodes around Base station - %s nodes" % n, x_label="X", y_label="Y") # simulation start net.algorithms = ((Beacon, {'informationKey': 'Data'}), ) coordinator_node = net.nodes()[0] coordinator_node.memory['Data'] = 'Beacon 1' sim = Simulation(net) sim.run() # simulation ends # capturing results consume = [] energy = []
Node.cid = 1 #net_gen = NetworkGenerator(n_count=n) #net = net_gen.generate_ring_network(x_radius=x_radius*clusters, y_radius=y_radius*clusters) net_gen = Star(n_count=n) net = net_gen.generate_ring_network(x_radius=x_radius, y_radius=y_radius, sector=0.75) n_anchors = (int)(p_anchors * net.__len__() / 100) for node in net.nodes(): if (node.id % n_anchors == 0): # anchor nodes node.compositeSensor = (TruePosSensor, ) node.type = 'C' # Anchors net.name = "DV on ring" # saving topology as PNG image net.savefig(fname=get_path(TOPOLOGY_DIR, "dv-%s-ring-sect" % n), title="C shaped - %s nodes" % n, x_label="X", y_label="Y") print net.__len__(), net.avg_degree(), node.commRange net.reset() Node.cid = 1 net_gen = Star(n_count=n) net = net_gen.generate_two_ring_network(x_radius=x_radius / 2, y_radius=y_radius / 2, sector=0.75) n_anchors = (int)(p_anchors * net.__len__() / 100) for node in net.nodes(): if (node.id % n_anchors == 0): # anchor nodes
n_power = [] n_range = np.arange(20, max_n+1, 10) start_time = time.time() project_name = "IWSN - ISA100.11a (obstacle)" folder = DATETIME_DIR+ "-" + project_name # network topology setup Node.cid = 1 net_gen = Manual() net = net_gen.generate_mesh_network(name="ISA100 Mesh", type=2) n = len(net) net.name = "ISA100 Rough Simulation" + "\nN=%s, R=%s m" \ %(n, global_settings.COMM_RANGE) filename = net.name.replace("\n", "-") # saving topology as PNG image net.savefig(fname=get_path(folder, filename), title=net.name, xlabel="X-coordinate (m)", ylabel="Y-coordinate (m)", show_labels=True, format="png", label_color='yellow') print net.__len__(), len(net) # simulation start net.algorithms = ((Beacon, {'informationKey': 'Data'}),) coordinator_node = net.nodes()[0] coordinator_node.memory['Data'] = 'Beacon 1' sim = Simulation(net) sim.run() # simulation ends # capturing results consume = [] energy = []
anchpositions.append({'x': net.pos[node][0], 'y': net.pos[node][1], 'name': str(node.id)}) else: positions.append({'x': net.pos[node][0], 'y': net.pos[node][1], 'name': 'Node: ' + str(node.id)}) newpos.append({'x': newx, 'y': newy, 'name': 'Node: ' + str(node.id)}) xestpositions.append(newx) deltapos.append(net.pos[node][0] - newx) avg_deg = round(net.avg_degree()) net.name = "%s - Nodes=%s, Avg degree=%s, Range=%s" \ % (net_gen.name, net.__len__(), int(avg_deg), int(node.commRange)) net.savefig(fname=get_path(TOPOLOGY_DIR, net.name), title=net.name, format='pdf', x_label="X", y_label="Y", show_labels=False) print net.__len__(),avg_deg, node.commRange, n_anchors end_time = time.time() - start_time ntx = 345 comments = "Anchors: " + str(n_anchors) +"="+str(p_anchors) +"%"+ \ ", Runtime(sec): "+ str(round(end_time,2)) + \ ", No. of Tx: " + str(ntx) plotter.gethtmlScatter(xpositions, [anchpositions, positions, newpos], fname="Topology-"+net.name, folder=TOPOLOGY_DIR, xlabel="X", ylabel="Y", labels=['Anchor','Regular','Localized'], title="Topology-"+net.name, open=1, range={'xmin':0, 'ymin':0, 'xmax': w, 'ymax': h}, comment=comments, show_range=node.commRange,
}, 'pymote.simulation': { 'level': 'INFO', 'handlers': ['simFileHandler'], 'propagate': 1 } }, 'handlers': { 'fileHandler': { 'class': 'logging.FileHandler', 'level': 'DEBUG', 'formatter': 'fileFormatter', 'filename': get_path(LOG_DIR, 'pymote.log') }, 'consoleHandler': { 'class': 'logging.StreamHandler', 'formatter': 'consoleFormatter', 'stream': 'ext://sys.stdout' }, 'simFileHandler': { 'class': 'logging.FileHandler', 'level': 'DEBUG', 'formatter': 'fileFormatter', 'filename': get_path(LOG_DIR, 'simulation.log') } },
# set the network name based on no. of Nodes, degree and Comm. Range net.name = "%s(%s) - $N=$%s(%s), $D=$%s, $R=$%s m\n" \ "$A=$%s$\\times 10^3m^2$, $N_D=$%s$/10^3.m^2$, $DOI$=%s" \ % (net_gen.name, vary, nn, n_anchors, round(avg_deg, 1), round(comm_range, 1), round(net_gen.area / 1000.0, 2), round(net_gen.net_density * 1000, 1), round(doi, 1)) filename = (net.name.split("\n")[0]).replace("$", "") area = "A: %s x 1000 m^2, ND: %s /1000 m^2, DOI: %s" \ % (round(net_gen.area / 1000.0, 2), round(net_gen.net_density * 1000, 1), round(doi, 1)) try: net.savefig(fname=get_path(folder, filename), title=net.name, xlabel="X-coordinate (m)", ylabel="Y-coordinate (m)", show_labels=True, format="pdf") except: pass # Now select the algorithm for simulation net.algorithms = ((algorithm[method][0], {'truePositionKey': 'tp', 'hopsizeKey': 'hs', 'dataKey': 'I', 'maxHop': vary }), (algorithm[method][1], {'truePositionKey': 'tp', 'hopsizeKey': 'hs', 'positionKey': 'pos', 'dataKey': 'I'}),
connected=False, commRange=global_settings.COMM_RANGE, comm_range=global_settings.COMM_RANGE) net = net_gen.generate_grid_network(name="Grid", randomness=0, p_anchors=None) net, p = net_gen.get_clusters(net, clusters=clusters, method="EM") node = net.nodes()[int(n / 2)] net.remove_node(node) n = len(net) net.name = "Grid Topology" + "\nN=%s, R=%s m" \ %(n, global_settings.COMM_RANGE) filename = net.name.replace("\n", "-") # saving topology as PNG image net.savefig(fname=get_path(folder, filename), title=net.name, xlabel="X-coordinate (m)", ylabel="Y-coordinate (m)", show_labels=True, format="png", label_color='yellow') net.name = filename net.save_json(get_path(folder, filename + ".json"), scale=(1, 1)) print net.__len__(), len(net) coordinator_node = net.nodes()[n - 1] coordinator_node.type = 'B' coordinator_node.compositeSensor = (NeighborsSensor, ) # (TruePosSensor,)
def gethtmlLine(x, y, fname, folder="", axis_range={}, labels=None, xlabel="X", ylabel="Y", title=None, color='r', comment=".", **kwargs): title = title or fname plot_type = 'spline' if 'plot_type' in kwargs: plot_type = kwargs.pop('plot_type', 'line') plot_options = [""] if 'plot_options' in kwargs: plot_options = kwargs.pop('plot_options') show_range = kwargs.pop('show_range', None) circle = "" if show_range: circle = "allowPointSelect:true, marker: {states: {select: {lineColor: 'red', radius: " + str(show_range) + "}}}," series_data = '' k = 0 for series in y: series_data += ''' { name: "''' + (labels[k] if k < len(labels) else "") + '''", ''' + (plot_options[k] if k < len(plot_options) else "") + ''' data: ''' + str(series) + ''', ''' + circle + ''' }, ''' k += 1 contents = '''<!DOCTYPE html> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>'''+title+'''</title> <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script> <style type='text/css'> </style> <script type='text/javascript'>//<![CDATA[ var chart; var w; $(function () { w = $('#container').width() $('#container').highcharts({ credits: { enabled: false }, exporting: { filename: "''' + fname + '''" }, legend: { margin: -10, padding: 0, y: -5, //layout: 'vertical', align: 'right', verticalAlign: 'middle', shadow: true, backgroundColor: '#FFFFFF', title: { //text: 'Farrukh Shahzad<br/>PhD, KFUPM<br/>Nov. 2015</span>', style: {fontStyle: 'italic', fontSize: '10px'} } }, chart: { zoomType: 'xy', panning: true, panKey: 'shift', type: "''' + plot_type + '''" }, title: { text: "''' + title + '''" }, subtitle: { text: "''' + comment + '''", style: {color:'black', fontSize: '18px', fontFamily: 'Times'} }, tooltip: { borderRadius: 10, crosshairs: [{width: 1, color: 'gray', dashStyle: 'shortdot'}, {width: 1, color: 'gray', dashStyle: 'shortdot'}], pointFormat: '<span style="font-weight: bold; color: {series.color}">{series.name}</span>: <b>{point.y:.1f}</b><br />', headerFormat: '<span style="font-size: 12px">''' + xlabel + ''' {point.key}</span><br />', shared: true }, xAxis: { // Primary xAxis minRange : 5, min: '''+ json.dumps(axis_range.get('xmin')) + ''', max: '''+ json.dumps(axis_range.get('xmax')) + ''', title: {text: "'''+ xlabel + '''", y: -10, style: {color:'black'}} }, yAxis: { // Primary yAxis lineWidth: 1, minPadding: 0.0, maxPadding: 0.0, min: '''+ json.dumps(axis_range.get('ymin')) + ''', max: '''+ json.dumps(axis_range.get('ymax')) + ''', title: {text: "'''+ ylabel + '''", x: 10, style: {color:'black'}} }, series: [''' + series_data + '''] }); }); //]]> </script> </head> <body> <script src="http://code.highcharts.com/highcharts.js"></script> <script src="http://code.highcharts.com/modules/data.js"></script> <script src="http://code.highcharts.com/highcharts-more.js"></script> <script src="http://code.highcharts.com/modules/exporting.js"></script> <div id="container" style="height: 600px; margin: auto; min-width: 600px; max-width: 600px"></div> </body> </html> ''' path = get_path(folder,fname) + ".html" if 'open' in kwargs: browseLocal(contents, filename=path) else: strToFile(contents, filename=path)