Beispiel #1
0
def knn_classify(data_file, K=5):
    # f_train, f_test, l_train, l_test = get_data(data_file)
    f_train, f_test, l_train, l_test = get_data_optimized(data_file)

    l_predict = []
    for t in range(f_test.shape[0]):
        N = []
        l = 0
        for d in range(f_train.shape[0]):
            if len(N) <= K:
                N.append(d)
            else:
                for u in N:
                    if dist(f_test[t], f_train[d]) < dist(f_test[t], f_train[u]):
                        N.remove(u)
                        N.append(d)
                        break
        for n in N:
            if l_train[n] == 'A':
                l += 1
            else:
                l -= 1
        if l >= 0:
            l_predict.append('A')
        else:
            l_predict.append('B')
    acc = (float(sum(l_predict == l_test))/len(l_predict))
    plot(f_train, l_train, f_test, l_test, l_predict, acc)
Beispiel #2
0
def get_data_optimized(data_file, test_size=0.9):
    data = pd.read_csv(data_file)
    data = np.array(data)
    train_data = []
    seed_point = random.randint(0, data.shape[0] - 1)
    train_data.append(data[seed_point])
    test_data = np.delete(data, seed_point, axis=0)

    while len(train_data) <= (int((1 - test_size) * data.shape[0])):
        dist_buf = []
        for i in range(test_data.shape[0]):
            min_dist = float('inf')
            for j in range(len(train_data)):
                d = dist(train_data[j], test_data[i])
                if d < min_dist:
                    min_dist = d
            dist_buf.append(min_dist)
        max_point = dist_buf.index(max(dist_buf))
        train_data.append(test_data[max_point])
        test_data = np.delete(test_data, max_point, axis=0)

    train_data = np.array(train_data)
    f_train = train_data[:, :-1]
    l_train = train_data[:, -1]
    f_test = test_data[:, :-1]
    l_test = test_data[:, -1]
    return f_train, f_test, l_train, l_test
Beispiel #3
0
	def eval_routing_table(self) :
		sensor_range = sqrt(5) * self.yard.grid_size

		# evaluating all the alive neighbours in the communication range
		for node in self.yard.nodes :
			self.neighbours[node.id] = []
			for adj_node in self.yard.nodes :
				if adj_node.id != node.id and adj_node.energy > 0 and dist(node.x, node.y, adj_node.x, adj_node.y) <= sensor_range :
					self.neighbours[node.id].append(adj_node)
Beispiel #4
0
	def send_data_non_ch(self, energy, packet):
		d0 = sqrt(energy.free_space / energy.multi_path)
		
		# distance of sensor to its CH
		d = dist(self.x, self.y, self.cell.head.x, self.cell.head.y)

		if d > d0 :
			self.energy = self.energy - (packet.ctr_packet_length*energy.trans + energy.multi_path*packet.packet_length*(d ** 4)) 
		else :
			self.energy = self.energy - (packet.ctr_packet_length*energy.trans + energy.free_space*packet.packet_length*(d ** 2)) 				
Beispiel #5
0
	def sense(self, sensors, panda_x, panda_y):
		sensor_range = sqrt(5)*self.yard.grid_size
		
		for sensor_node in self.yard.nodes:
			if (sensor_node.energy > 0
				and dist(sensor_node.x, sensor_node.y, panda_x, panda_y) <= sensor_range
				):
				
				sensors.append(sensor_node)

		print "len", len(sensors)
		return len(sensors) > 0
Beispiel #6
0
def do_compute_path(r, cx, cy, tx, ty, n, stack, visited, escape_center,
                    escape):
    if n > 700:
        return False

#	print "A"
    stack.append((cx, cy))
    #	print "AA", len(r), cy
    #	print "AA", len(r[cy]), cx
    #	if cy < r[cy][cx] == 'T':
    #		print "AAA"
    #		return True
    #	print "B"

    candidates = []
    for y in [-1, 0, 1]:
        for x in [-1, 0, 1]:
            if x != 0 or y != 0:
                if big_enough(r, cx + x, cy + y, escape_center, escape):
                    candidates.append((dist(cx + x, cy + y, tx,
                                            ty), cx + x, cy + y))
#	print "C"

    for d, x, y in sorted(candidates):
        if (x, y) not in visited:
            visited.add((x, y))
            if r[y][x] == 'T':
                stack.append((x, y))
                return True
            if do_compute_path(r, x, y, tx, ty, n + 1, stack, visited,
                               escape_center, escape):
                return True


#	print "D"
    stack.pop()
    #	print "E"
    return False
Beispiel #7
0
def do_compute_path(r, cx, cy, tx, ty, n, stack, visited, escape_center, escape):
    # stop if recursion depth exceeds 700
    if n > 700:
        return False

    stack.append((cx, cy))

    candidates = []
    for y in [-1, 0, 1]:
        for x in [-1, 0, 1]:
            if x != 0 or y != 0:
                if big_enough(r, cx + x, cy + y, escape_center, escape):
                    candidates.append((dist(cx + x, cy + y, tx, ty), cx + x, cy + y))

    for d, x, y in sorted(candidates):
        if (x, y) not in visited:
            visited.add((x, y))
            if r[y][x] == 'T':
                stack.append((x, y))
                return True
            if do_compute_path(r, x, y, tx, ty, n + 1, stack, visited, escape_center, escape):
                return True
    stack.pop()
    return False
Beispiel #8
0
	def execute(self, rings, event_rings, packet) :
		boundary_nodes = []
		outer_ring = len(rings) - 1
		
		# identifying the outermost nodes
		for counter in rings :
			if len(rings[outer_ring]) > 0 :
				for node in rings[outer_ring] :
					boundary_nodes.append(node.head)
				break
			else :
				outer_ring -= 1

		print len(boundary_nodes),"boundary_nodes"

		starting_node = None

		# randomly picking up the outermost node to initiate the protocol
		while starting_node == None :
			node_id = random.randint(0,len(boundary_nodes) - 1)
			if boundary_nodes[node_id].energy > 0 :
				starting_node = boundary_nodes[node_id]

		print "Starting Greedy Node : ",starting_node

		interference_node = None
		maxd = dist(0, 0, self.yard.l, self.yard.b)


		# executing the protocol until the greedy path intersects the cyclic path
		while interference_node == None :
			min_dist = maxd
			nearest_node = None

			if len(self.neighbours[starting_node.id]) > 0 :
				
				# energy dissipitated while transmiting
				starting_node.send_data_non_ch(self.yard.energy, packet)
				print "transmiting",starting_node

				# identifying which alive neighbour in the communication range is closest to sink 
				for node in self.neighbours[starting_node.id] :
					if node.energy > 0 :
						distance_sink = dist(node.x, node.y, self.yard.sink.x, self.yard.sink.y)
						if min_dist < distance_sink :
							min_dist = distance_sink
							nearest_node = node
						if node.cell.head.ring in event_rings :
							interference_node = node 	
							nearest_node = interference_node
							print "ring number", node.cell.head.ring	
							print "interference_node",interference_node			
							break

				if nearest_node is not None :
					# energy dissipitated while receiving
					nearest_node.receive_data(self.yard.energy, packet)
					print "receiving",nearest_node.id
				starting_node = nearest_node
			else :
				# all nodes in the communication range are Dead
				break
Beispiel #9
0
	def execute(self, panda_x, panda_y):
		packet = Packet()
		self.eval_rings()
		
		sensors = []

		fig = plt.figure()
		plt.ion()
		plt.show()
		# plt.legend()
		plt_node_ch = fig.add_subplot(211)
		plt_energy = fig.add_subplot(212)

		# initialising the GreedyRouting Protocol
		greedyRouting = GreedyRouting(self.yard)
		

		while self.sense(sensors, panda_x, panda_y):
			self.plot_nodes_ch(plt_node_ch, panda_x, panda_y)
			self.plot_energy(plt_energy)

			plt.pause(1e-50)
			# time.sleep(0.1)

			CyclicRouting.iteration += 1

			# constructing the greedy routing table
			greedyRouting.eval_routing_table()

			cluster_heads = []
			for node in sensors:
				# A cluster head maintains cache, therefore a cluster would trigger the ring only once
				if node.cell.head not in cluster_heads:
					cluster_heads.append(node.cell.head)


				if node.is_cluster_head:
					continue
				

				node.send_data_non_ch(self.yard.energy, packet)

			rings = []
			for head in cluster_heads:
				# Panda detected from different cluster, can belong to same ring or other
				rings.append(head.ring)

			# executing the Greedy Routing
			greedyRouting.execute(self.rings, rings, packet)

			for ring in rings:
				for cell in self.rings[ring]:
					maxd = dist(0, 0, self.yard.l, self.yard.b)

					d_nodes = {
						 1: [maxd, None], # clockwise
						-1: [maxd, None]  # anti-clockwise
					}

					for node in self.rings[ring] :

						try: 
							val = ((node.head.x - self.yard.sink.x) / (self.yard.sink.x - cell.head.x) 
							- (node.head.y - self.yard.sink.y) / (self.yard.sink.y - cell.head.y))
						except:
							continue

						if val is 0:
							val = 1

						sign = val/abs(val)

						d = dist(node.head.x, node.head.y, cell.head.x, cell.head.y)
						if d < d_nodes[sign][0]:
							d_nodes[sign][0] = d
							d_nodes[sign][1] = node

					if d_nodes[1][1] is not None:
						cell.head.send_data_ch(self.yard.energy, packet, d_nodes[1][0])
						cell.head.receive_data(self.yard.energy, packet)

					if d_nodes[-1][1] is not None:
						cell.head.send_data_ch(self.yard.energy, packet, d_nodes[-1][0])
						cell.head.receive_data(self.yard.energy, packet)

					#only one node remains in the ring || should be thought of
					if d_nodes[1][1] is None and d_nodes[-1][1] is None:
						cell.head.energy = 0

			self.yard.clusterize()
			self.eval_rings()

			sensors = []

		print "iterations done: ", CyclicRouting.iteration
		plt.show()
		plt.pause(10)
Beispiel #10
0
 def fitness(self):
     if self.atgoal:
         return 2 + 1 / (self.brain.step**2)
     else:
         return 1 / (dist(self._pos, self._goal.pos)**2)
Beispiel #11
0
 def _ingoal(self):
     return dist(self._pos, self._goal.pos) < 10
Beispiel #12
0
                                              cv2.CHAIN_APPROX_SIMPLE)

    #get rid of outliers that are far away
    centLst = []
    avgArea = 0
    for cont in contours:
        M = cv2.moments(cont)
        cX = int(M["m10"] / (M["m00"] + 0.00000001))
        cY = int(M["m01"] / (M["m00"] + 0.00000001))
        avgArea += cv2.contourArea(cont)
        centLst.append((cX, cY))
    combs = combinations(centLst, 2)
    avgDist = 0
    tot = 0
    for combo in combs:
        avgDist += h.dist(combo[0], combo[1])
        tot += 1
    avgDist /= tot + 0.00000000000001
    avgArea /= tot + 0.00000000000001

    contImg = img.copy()
    for i in range(0, len(contours) - 1):
        if avgDist * avgArea > cv2.contourArea(contours[i]) * h.dist(
                centLst[i], h.shortest_dist(centLst[i], centLst)):
            contImg = cv2.drawContours(contImg, contours, i, (0, 0, 255))
        else:
            contImg = cv2.drawContours(contImg, contours, i, (0, 255, 0))

    cv2.imshow('thresh', contImg)
    key = cv2.waitKey(1) & 0xFF
    if key == ord('q'):