def move(self): if self.speed == 0: #si l'avion est à l'arrêt (2x le même point) if self.type == 'egts': #si c'est un egts, l'avion redémarre immédiatement après le pushback self.stop_counter = PAS while self.path_to_visit[1] == self.current_aim: self.path_to_visit.pop(0) else: #sinon, on attend PAS tours (ie PAS sec) avant de supprimer le point self.stop_counter += 1 distance_to_aim = distance(self.current_aim, self.pos) if distance_to_aim < self.speed or self.stop_counter >= PAS: #si on arrive au point suivant (on compare à la vitesse car la position évolue avec speed * dir et ||dir|| = 1 ) if len(self.path_to_visit) == 1: #si on est arrivé au bout du chemin, on supprime l'avion self.is_on_map = False self.is_arrived = True return 0 self.stop_counter = 0 self.max_speed = distance(self.path_to_visit[0], self.path_to_visit[1]) / PAS self.path_to_visit.pop(0) self.current_aim = self.path_to_visit[0] self.dir = np.array(self.current_aim) - np.array(self.pos) #on calcule le vecteur directeur self.dir = self.dir / np.linalg.norm(self.dir) #que l'on rend unitaire self.pos = self.pos + self.speed * self.dir
def waitprocess(request): jobid = request.session['SMOOTHENJOB_ID'] job = queue.fetch_job(jobid) if job.result == None: time.sleep(3) return HttpResponseRedirect('/waitprocess/') smoothened_data, lat, lon, ele, latsmooth, lonsmooth, elesmooth = job.result smoothen.writeoutput( '{}_smooth.gpx'.format(request.session['ACTIVITY_ID']), smoothened_data) request.session['DISTANCE_OLD'] = functions.distance(lat, lon, ele) request.session['DISTANCE_NEW'] = functions.distance( latsmooth, lonsmooth, elesmooth) args = ( '{}.png'.format(request.session['ACTIVITY_ID']), lat, lon, latsmooth, lonsmooth, ) functions.runplot(args) return HttpResponseRedirect('/overview/')
def move_to_target_unit(self, game): unit = game.unit_by_name(self.target_unit) if not unit: self.target_unit = None self.reset(game) return False self.point_at(unit) if obstacle(game, (self.x + self.dx, self.y + self.dy)): if (unit.x, unit.y) == (self.x + self.dx, self.y + self.dy): if unit.hostile != self.hostile: self.refresh_activity(game, 'attacking') elif obstacle_unit(game, (self.x + self.dx, self.y + self.dy)): unit_2 = obstacle_unit(game, (self.x + self.dx, self.y + self.dy)) if unit_2.hostile != self.hostile: self.target_unit = unit_2.name self.refresh_activity(game, 'attacking') else: self.sidestep(game) else: self.sidestep(game) else: if random.random() < self.move_frequency_2: if random.random() < self.lurch_frequency and distance( (self.x, self.y), (unit.x, unit.y)) >= 3: self.refresh_activity(game, 'lurching') else: self.refresh_activity(game, 'walking') self.reset_ticks()
def runSim(self, printMovement=False): fitness = 0 survivorLoc = [nn.XSIZE // 2, nn.YSIZE // 2] foodLoc = func.generateFood(survivorLoc) health = nn.INITIALFOOD while health >= 0: move = self.forwardpass(survivorLoc, foodLoc) if move == 0: # RIGHT survivorLoc[0] = (survivorLoc[0] + 1) % nn.XSIZE elif move == 1: # LEFT survivorLoc[0] = (survivorLoc[0] - 1) % nn.XSIZE elif move == 2: # UP survivorLoc[1] = (survivorLoc[1] + 1) % nn.YSIZE elif move == 3: # DOWN survivorLoc[1] = (survivorLoc[1] - 1) % nn.YSIZE if survivorLoc == foodLoc: # found some food! health += nn.FOODBONUS foodLoc = func.generateFood(survivorLoc) fitness += 1 health -= 1 if printMovement: # option to print the locations of everything print("Survivor: " + str(survivorLoc) + " Food: " + str(foodLoc)) # fitness = number of food + 1-(distance to next food)/((X+Y)/2) return fitness + (1 - func.distance(survivorLoc, foodLoc) / ((nn.XSIZE + nn.YSIZE) / 2))
def check_goban_moved(prev_corners, current_corners): """Comprobamos si es posible el movimiento de tablero detectado. :Param prev_corners: corners detectados anteriormente :Type prev_corners: list :Param current_corners: corners detectados actualmente :Type current_corners: list :Return: True si el tablero se ha movido :Rtype: bool """ if not prev_corners or not current_corners: return True # dist_min_of_movement = get_max_edge(prev_corners)/(2*GOBAN_SIZE) " Comprobamos primero si existe mucho movimiento. " dist = [] directions = [] for i in xrange(NUM_EDGES): dist.append(abs(distance(prev_corners[i], current_corners[i]))) directions.append(direction(prev_corners[i], current_corners[i])) f = lambda x: x>1 dist_list = filter(f, dist) if len(dist_list) > 2: # min_mov=1/3 square TODO check impossible movement (Direcction) min_mov = get_max_edge(prev_corners)/((GOBAN_SIZE-1)*3.0) dist_list.sort() if (dist_list[-1] - dist_list[0]) < min_mov: return check_directions(directions) elif (dist_list[-1] - dist_list[-3]) < min_mov: return check_directions(directions) else: return False else: return False
def get_umatrix(mymap, radius=1): umatrix = empty_list(mymap.size, 1) xmax = mymap.size[1] ymax = mymap.size[0] rad = range(-radius, radius + 1) # print rad for neuron in flatten(mymap.neurons): weight = neuron.weight position = neuron.position x = position[0] y = position[1] xrange = [] yrange = [] for i in rad: xrange.append(int((x + i) % xmax)) yrange.append(int((y + i) % ymax)) average_dist = 0 for x in xrange: for y in yrange: neighbour_weight = mymap.neurons[x][y].weight d = fn.distance(neighbour_weight, weight) average_dist += d umatrix[x][y] = average_dist return umatrix
def draw_neuron_activation(mymap, named=True, symbols=False): # iterates through EACH neuron and finds closest vector words = distances = empty_list(mymap.size, 1) if named: vectors = mymap.vectors keys = mymap.keys else: vectors = [] keys = [] idea_names = mymap.space.idea_names for item in mymap.space.table: keys.append(idea_names[item]) vectors.append(mymap.space.table[item]) if symbols: s = mymap.space.symbol_vectors keys = [] vectors = [] for item in s: keys.append(mymap.space.idea_names[item]) vectors.append(s[item]) for neuron in flatten(mymap.neurons): weight = neuron.weight match = fn.find_best_match(weight, vectors) distance = fn.distance(weight, vectors[match]) x = neuron.position x = fn.to_int(x) words[x[0]][x[1]] = keys[match] # distances[x[0]][x[1]] = distance word_plot(words) return words
def dijkstra(nodes, edges, source): print("\nDijkstra : %d nodes, %d edges, %s" % (len(nodes), len(edges), source)) inf = float("inf") distances = {node : inf for node in nodes} previous = {node : None for node in nodes} distances[source] = 0 while 0 < len(nodes): dists = [(distances[node], node) for node in nodes] node = min(dists, key = lambda x : x[0])[1] # print(" node=%s" % node, "distance=%0.2f" % distances[node]) if distances[node] == inf: print(" No possible path from source to all destinations") return previous nodes.remove(node) # For each neighbour v of u neighbours = [edge for edge in edges if node in edge] for neighbour in neighbours: # Get other end of edge other = neighbour[1] if neighbour[0] == node else neighbour[0] alt = distances[node] + distance(node, other) if alt < distances[other]: distances[other] = alt previous[other] = node # print(" ->", other, "= %0.2f" % distances[other]) return previous ################################################
def check_goban_moved(prev_corners, current_corners): """Comprobamos si es posible el movimiento de tablero detectado. :Param prev_corners: corners detectados anteriormente :Type prev_corners: list :Param current_corners: corners detectados actualmente :Type current_corners: list :Return: True si el tablero se ha movido :Rtype: bool """ if not prev_corners or not current_corners: return True dist_min_of_movement = get_max_edge(prev_corners) / (2 * GOBAN_SIZE) " Comprobamos primero si existe mucho movimiento. " dist = [] directions = [] for i in xrange(NUM_EDGES): dist.append(abs(distance(prev_corners[i], current_corners[i]))) directions.append(direction(prev_corners[i], current_corners[i])) f = lambda x: x > 1 dist_list = filter(f, dist) if len(dist_list) > 2: # min_mov=1/3 square TODO check impossible movement (Direcction) min_mov = get_max_edge(prev_corners) / ((GOBAN_SIZE - 1) * 3.0) dist_list.sort() if (dist_list[-1] - dist_list[0]) < min_mov: return check_directions(directions) elif (dist_list[-1] - dist_list[-3]) < min_mov: return check_directions(directions) else: return False else: return False
def cluster_distance(cluster1, cluster2, distance_agg=max): """compute all the pairwise distances between cluster1 and cluster2 and appl distance_agg to the resulting list""" return distance_agg([ fnc.distance(input1, input2) for input1 in get_values(cluster1) for input2 in get_values(cluster2) ])
def get_action(self, game): self.target_unit = None for unit in game.units: if unit.hostile != self.hostile: if self.target_unit: target_unit = game.unit_by_name(self.target_unit) if distance((self.x, self.y), (unit.x, unit.y)) < distance( (self.x, self.y), (target_unit.x, target_unit.y)): self.target_unit = unit.name else: if distance((self.x, self.y), (unit.x, unit.y)) <= 5: self.target_unit = unit.name if self.target_unit: target_unit = game.unit_by_name(self.target_unit) if not unit: self.target_unit = None self.reset(game) return False self.point_at(target_unit) (self.dx, self.dy) = (-self.dx, -self.dy) if obstacle(game, (self.x + self.dx, self.y + self.dy)): self.sidestep(game) else: if (self.x - self.dx, self.y - self.dy) == (target_unit.x, target_unit.y): (self.dx, self.dy) = (-self.dx, -self.dy) self.refresh_activity(game, 'attacking') else: if random.random() > 0.50: self.refresh_activity(game, 'walking') self.reset_ticks() else: #face nearest player unit min_distance = 100 self.target_unit = None for unit in game.units: if distance((self.x, self.y), (unit.x, unit.y)) < min_distance: self.target_unit = unit.name self.point_at(unit) min_distance = distance((self.x, self.y), (unit.x, unit.y)) if self.target_unit: if obstacle(game, (self.x + self.dx, self.y + self.dy)): pass else: pass #self.refresh_activity(game, 'walking') self.reset_ticks()
def calc_dist(df, reference_postcode): df2 = df.loc[df['postcode'] == reference_postcode] x1, y1, z1 = df2[['x', 'y', 'z']].values.flatten().tolist() df['distance'] = df.apply( lambda row: distance(x1, y1, z1, row.x, row.y, row.z), axis=1) df = df.sort_values(by='distance') df = df[df.distance == df.distance.max()] print(df.address, df.admin_name3, df.postcode)
def pop_density_rand(self): ''' Returns a location tuple for a new person in the city Samples randomly based on population density Currently: normal distribution in both X and Y directions ''' loc = (self.size + 1, 0) while f.distance(loc, (0, 0)) > self.size: loc = (norm(scale=self.size).rvs(), norm(scale=self.size).rvs()) return loc
def distances(car, track, nb_angles=8, debugging=False): if debugging and world is not None: world.delete('debug') dists = [] for i in range(nb_angles): theta = -180 + i*360/(nb_angles) x, y = closest_point(car, track, theta) dists.append(distance(car.x, car.y, x, y)) if debugging and world is not None: world.create_line(car.x, car.y, x, y, fill='green', tag='debug') return dists
def test_functions(self): # distance point0 = np.array([0, 0, 0]) point1 = np.array([1, 1, 1]) np.testing.assert_allclose(np.sqrt(3), distance(point0, point1), atol=0.00001) # angle difference self.assertEqual(-20, angle_difference(10, 350)) self.assertEqual(20.0, angle_difference(350, 10))
def find_eigenvector(A, tolerance=0.00001): guess = [random.random() for __ in A] while True: result = matrix_operate(A, guess) length = magnitude(result) next_guess = scalar_multiply(1 / length, result) if distance(guess, next_guess) < tolerance: return next_guess, length #eigenvector, eigenvalue guess = next_guess
def closest_point(car, track, angle): """return the approximate coordinates of the closest point to the car along the direction given by theta (relative to the car's heading)""" x_inf, y_inf = car.x, car.y if not is_out(track, car): t = 100 x, y = rotate(car.x + t, car.y, car.heading + angle, car.x, car.y) while not is_out(track, x=x, y=y): t *= 2 x, y = rotate(car.x + t, car.y, car.heading + angle, car.x, car.y) epsilon = 10 while epsilon > 5: x_tmp, y_tmp = (x + x_inf) / 2, (y + y_inf) / 2 if not is_out(track, x=x_tmp, y=y_tmp): x_inf, y_inf = x_tmp, y_tmp else: x, y = x_tmp, y_tmp epsilon = distance(x, y, x_inf, y_inf) else: t = 5 x, y = rotate(car.x + t, car.y, car.heading + angle, car.x, car.y) while is_out(track, x=x, y=y) and t < 300: t += 25 x, y = rotate(car.x + t, car.y, car.heading + angle, car.x, car.y) epsilon = 10 while epsilon > 5: x_tmp, y_tmp = (x + x_inf) / 2, (y + y_inf) / 2 if is_out(track, x=x_tmp, y=y_tmp): x_inf, y_inf = x_tmp, y_tmp else: x, y = x_tmp, y_tmp epsilon = distance(x, y, x_inf, y_inf) return x, y
def knn_classify(k, labeled_points, new_point): """each labeled point should be a pair (point, label)""" #order the labeled points from nearest to farthest by_distance = sorted(labeled_points, key=lambda (point, _): fnc.distance(point, new_point)) #find labels for the k closest k_nearest_labels = [label for _, label in by_distance[:k]] #and let them vote return majority_vote(k_nearest_labels)
def fulfill(self): ''' Tries to fulfill needs at nearby businesses. Currently chooses randomly from businesses inside the demand radius. ''' for need, amt in self.needs.iteritems(): r = self.city.dtypes[need].demand_radius(amt) pos_biz = [] # potential businesses for b in self.city.businesses: if f.distance(b.location, self.location) < r: pos_biz.append(b) if len(pos_biz) > 0: # choose a random business to win self.give_biz(need, choice(pos_biz))
def stop(self): if distance(self.initial, self.position) >= self.range: self.timer.stop() self.image.hide() elif not check_inbound(self.position, self.ventana): self.timer.stop() self.image.hide() else: for zombie in self.ventana.zombies: if collision(self, zombie): zombie.die() self.timer.stop() self.image.hide() self.ventana.zombies.remove(zombie)
def createAirportGraph(self): G = nx.DiGraph() for ligne in self.Lignes: Pts = ligne.pts G.add_nodes_from(nx.Graph(Pts)) for i in range(0, len(Pts) - 1): P1, P2 = Pts[i], Pts[i+1] d = distance(P1, P2) G.add_edge(P1, P2, distance = d) if ligne.sens == 'D': G.add_edge(P2, P1, distance = d) for piste in self.Pistes: Pts = piste[-2:] G.add_nodes_from(nx.Graph(Pts)) for i in range(0, len(Pts) - 1): P1, P2 = Pts[i], Pts[i+1] d = distance(P1, P2) G.add_edge(P1, P2, distance = d) return G
def __init__(self, v1, v2, v3): self.v1 = v1 self.v2 = v2 self.v3 = v3 self.corners = [v1, v2, v3] self.vertices = [(v1, v2), (v2, v3), (v3, v1)] a, b, c = lineFromPoints(v1, v2) e, f, g = lineFromPoints(v2, v3) a, b, c = perpendicularBisectorFromLine(v1, v2, a, b, c) e, f, g = perpendicularBisectorFromLine(v2, v3, e, f, g) self.C = lineLineIntersection(a, b, c, e, f, g) self.R = distance(v1, self.C) if self.C != None else None
def get_distances_to_nearest(mymap): distances = empty_list(mymap.size, 1) vectors = mymap.vectors matches = [] for neuron in flatten(mymap.neurons): weight = neuron.weight match = fn.find_best_match(weight, vectors) matches.append(match) distance = fn.distance(weight, vectors[match]) x = neuron.position x = fn.to_int(x) distances[x[0]][x[1]] = distance c = Counter(matches) print c print "items mapped : " + str(len(sorted(c))) return distances
def inertia_(lable, last_centroids, data_norm): """ Нахождение критерия суммарной квадратичности внутри кластеров :param lable: массив меток :param last_centroids: массив координат итоговых центроидов :param data_norm: матрица данных :return: значение инерции """ value = 0 i = 0 for elem in lable: # пробег по каждой метке dist = distance(data_norm[i], last_centroids[elem] ) # вычисление расстояния от точки до ее центроида value += dist # прибавление расстояния к значению инерции i += 1 # счетчик точек return value
def calculate_and_set_single_tortuosity(st1: Station, st2: Station): """ Compute and return tortuosity from station 1 to station 2 Station 2 has a higher MD compared to Station 1 :param st1: :param st2: :return: individual/single TI """ if st2.md < st1.md: raise ValueError(f"MD of the station 2 ({st2.md}) should be larger than station 1 ({st1.md}).") ti = np.abs((st2.md - st1.md) / (distance(st2.p, st1.p))) - 1 if ti < 0: ti = 0 st2.ti = ti return ti
def bowyerWatson(points): # https://en.wikipedia.org/wiki/Bowyer%E2%80%93Watson_algorithm # print("Running bowyerWatson on %d points" % len(points)) triangulation = [] # must be large enough to completely contain all the points in pointList P1 = Vec(-1e15, -1e15) P2 = Vec(1e15, -1e15) P3 = Vec(0, 1e15) megaTriangle = Triangle(P1, P2, P3) triangulation.append(megaTriangle) # add all the points one at a time to the triangulation for iP, P in enumerate(points): badTriangles = [] # first find all the triangles that are no longer valid due to the insertion for iT, T in enumerate(triangulation): if distance(P, T.C) < T.R: # If point inside triangle circumcircle badTriangles.append(T) # Triangle is bad # find the boundary of the polygonal hole polygon = [] for T in badTriangles: for V in T.vertices: # for each edge in triangle # if edge is not shared by any other triangles in badTriangles if not any([_T.hasVertex(V) for _T in badTriangles if T != _T]): polygon.append(V) for T in badTriangles: triangulation.remove(T) # re-triangulate the polygonal hole for v1, v2 in polygon: triangulation.append(Triangle(P, v1, v2)) # if triangle contains a vertex from original super-triangle triangulation = [ T for T in triangulation if not T.sharesCornerWith(megaTriangle) ] return triangulation #######################################
def main(self): if self.snake.life == 1: return self._game_over() self.snake.move() for enemy in self.enemies: enemy.move() turner_off = self._is_game_over() if turner_off == True: return self._game_over() snake_head = self.frame._canvas.coords( self.snake.segments[-1].instance) x1, y1, x2, y2 = snake_head if x1 > WIDTH or x2 > WIDTH: self.level = 2 self.frame._canvas.destroy() self.second_lvl() else: # Check for collision with enemies for enemy in self.enemies: if fu.distance(self.snake, enemy, self.frame._canvas) < SEG_SIZE: self.snake.delete_seg() enemy.add_enemy_segment() # Eating apples if abs(x1 - self.block.x) <= SEG_SIZE and abs( y1 - self.block.y) <= SEG_SIZE: self.snake.add_segment(self.frame._canvas) self.frame._canvas.delete(self.block.instance) self.block.create_block() self.score += 1 self.frame._canvas.create_rectangle(75, 50, 150, 80, outline='peach puff', fill="peach puff") self.frame._canvas.create_text(100, 50, anchor=N, font="Courier", text="Score {}".format( self.score)) self.frame._root.after(100, self.main)
def reached(self, car): x_milieu = (self.xg + self.xd) / 2 y_milieu = (self.yg + self.yd) / 2 width = distance(self.xg, self.yg, self.xd, self.yd) angle = np.arccos((self.xd - self.xg)/width) if self.yd < self.yg: angle = -angle ax, ay, bx, by, cx, cy, dx, dy = rectangle_vertices(x_milieu, y_milieu, width=car.length, length=width + car.width, angle=360 * angle / (2 * np.pi)) if is_right_of_line(car.x, car.y, bx, by, ax, ay) and is_right_of_line(car.x, car.y, cx, cy, bx, by) and \ is_right_of_line(car.x, car.y, dx, dy, cx, cy) and is_right_of_line(car.x, car.y, ax, ay, dx, dy): return True else: return False
def get_action(self, game): if random.random() < 0.25: self.reset(game) return else: enemy_units = [u for u in game.units if u.hostile != self.hostile] closest_enemy = None min_distance = 8 for u in enemy_units: if distance((self.x, self.y), (u.x, u.y)) < min_distance: if game.LOS((self.x, self.y), (u.x, u.y)): if closest_enemy == None: closest_enemy = u else: if distance( (self.x, self.y), (u.x, u.y)) < distance( (self.x, self.y), (closest_enemy.x, closest_enemy.y)): closest_enemy = u if closest_enemy: if distance((self.x, self.y), (closest_enemy.x, closest_enemy.y)) <= 4: self.point_at(closest_enemy) (self.dx, self.dy) = (-self.dx, -self.dy) self.refresh_activity(game, 'walking') self.reset_ticks() return else: if self.waypoints: if distance((self.x, self.y), self.waypoints[0]) <= 3: self.waypoints.pop(0) if self.waypoints: friendly_units = [u for u in game.units if u.playable] for u in friendly_units: if distance((self.x, self.y), (u.x, u.y)) <= 8: (x, y) = self.waypoints[0] (dx, dy) = (x - self.x, y - self.y) m = (dx**2 + dy**2)**0.5 if m != 0: (self.dx, self.dy) = (round(dx / m), round(dy / m)) self.refresh_activity(game, 'walking') self.reset_ticks() return self.reset(game)
def __init__(self, callsign, parking, h_debut, masse, type_moteur, path_to_visit): """Un avion est caratérisé par son nom, son parking, l'heure de départ, son poids, son moteur ('egts' ou 'classique'), et le chemin qu'il doit parcourir""" self.id = Aircraft.aircrafts_nbr Aircraft.aircrafts_nbr += 1 self.callsign = callsign self.parking = parking self.h_start = h_debut self.pos = path_to_visit[0] self.is_on_map = False self.is_arrived = False self.type = type_moteur self.max_speed = distance(path_to_visit[0], path_to_visit[1]) / PAS self.speed = self.max_speed self.mass = masse self.stop_counter = 0 #compteur de secondes passées à l'arrêt (PAS secondes entre chaque point) self.h_end = 0 self.path_to_visit = path_to_visit #liste des points à visiter (on retire les points au fur et à mesure) self.current_aim = self.path_to_visit.pop(0) self.dir = np.array(self.current_aim) - np.array(self.pos) #on calcule le vecteur directeur
def random_distances(dim, num_pairs): return [ fnc.distance(random_point(dim), random_point(dim)) for _ in range(num_pairs) ]
#Apply CAMShift retval, track_window = cv2.CamShift(back_projection, track_window, term_crit) (c,r,w,h) = track_window #Get area and center of ROI current_area = w*h current_center = (c+w/2,r+h/2) #print '**********' #print current_area #print current_center #print '**********' #ROI lost if if c<=0 or r<=0 or w<=0 or h<=0 or abs(current_area-prev_area) > MAX_AREA_SHIFT or functions.distance(current_center,prev_center) > MAX_CENTER_SHIFT: isLost = True print 'lost center or area' else: ''' #Reinitialize ROI histogram after each 50 frames if total_frames % 500 == 0: if h > 50 and w>50: hsv_roi = hsv_frame[r+15:r+h-15, c+15:c+w-15] mask_roi = mask_frame[r+15:r+h-15, c+15:c+w-15] else: hsv_roi = hsv_frame[r-10:r+40, c-10:c+40] mask_roi = mask_frame[r-10:r+40, c-10:c+40] hist_roi = cv2.calcHist([hsv_roi],[0,1],mask_roi,[16,20],[0,180,0,256])
from functions import distance print(distance(10,20,10,10))
previous_region.g_line)) add_region = False if add_region: current_frame.append( Box(regions_coordinates[region_counter][0], regions_coordinates[region_counter][1], False, False)) for current_region in current_frame: if current_region.c_x - 2 <= regions_coordinates[region_counter][ 0] <= current_region.c_x + 2 and current_region.c_y - 2 <= regions_coordinates[ region_counter][1] <= current_region.c_y + 2: center = region_center(regions_coordinates[region_counter]) if not current_region.b_line: # check if number crossed blue line distance_from_blue = distance(center, blue_line[0], blue_line[1]) if x_blue_min <= center[ 0] <= x_blue_max and distance_from_blue < 10 and center[ 1] > blue_line[0] * center[0] + blue_line[ 1]: current_region.b_line = True sum += predict_number(model, region) if not current_region.g_line: # check if number crossed green line distance_from_green = distance(center, green_line[0], green_line[1]) if x_green_min <= center[ 0] <= x_green_max and distance_from_green < 10 and center[ 1] > green_line[0] * center[ 0] + green_line[1]:
derivative2 = 0 btn = ev3.Button() #Initialise gyro sensor gyro_sensor = ev3.GyroSensor(ev3.INPUT_1) gyro_sensor.mode = 'GYRO-G&A' gyro_sensor.mode = 'GYRO-ANG' while ((not btn.backspace)): color = functions.senseColor() while (color <= 87): functions.pid_left_internal(offset, error, lastError, color, kp, ki, kd, tp, integral, derivative) color = functions.senseColor() dist = functions.distance() if (dist <= 70): functions.stop() ev3.Sound.speak('There is an obstacle').wait() #turn right using gyro sensor degrees = gyro_sensor.value() #turn right while ((gyro_sensor.value() - degrees) < 95): functions.inverseRight() functions.stop() functions.servoSensor() ev3.Sound.speak('I turned right to avoid it').wait() color = functions.senseColor() dist = functions.distance() while (color >= 55):
# Select every n'th image (http://stackoverflow.com/a/1404229/323100) Files = [Files[i] for i in xrange(0, len(Files), 12)] print 'Reading', len(Files), 'images in', \ os.path.dirname(os.path.commonprefix(Files)) # Extract data from the images ExperimentID = [os.path.split(i)[1].split('.')[0] for i in Files] ExperimentFolder = [os.path.join(os.path.dirname(i), os.path.basename(i).split('.')[0]) for i in Files] Folder = [os.path.dirname(i) for i in Files] Images = [plt.imread(i) for i in Files] Mean = [np.mean(i) * 255 for i in Images] STD = [np.std(i) * 255 for i in Images] ScintillatorDistance = [distance(i, ) for i in ExperimentFolder] # Weed out the ones images we cannot read... # for c, i in enumerate(Files): # print 'rm', os.path.join(Folder[c], '*.png') # estimate_noise(plt.imread(i)) Noise = [estimate_image_noise(i) * 255 for i in Images] # Give out info # for c, item in enumerate(ExperimentID): # print str(c).rjust(2), 'of', len(ExperimentID), '| Mean:', \ # str(round(Mean[c], 1)).rjust(5), '| STD:', \ # str(round(STD[c], 1)).rjust(4), '|', \ # os.path.join(Folder[c], # ExperimentID[c] + '.image.corrected.stretched.png') # Sort according to something
def average_distance_to_bmu0(self): dd = 0.0 for vector in self.vectors: bmu = self.find_bmu0(vector) dd += fn.distance(self.weights[bmu], vector) return dd / len(self.vectors)
def average_distance_to_bmu(self): dd = 0.0 for item in self.space.table: bmu = self.find_bmu(item) dd += fn.distance(bmu.weight , self.space.table[item]) return dd / len(self.space.table)
rws_data = rws_data.loc[rws_data.name != "Eisden Mazenhove", :] rws_data['value'] = rws_data['value'] / 100 # convert to [m] rws_stations = rws_data.drop_duplicates(subset="name") rws_stations.loc[:, 'x'] = rws_stations.x.apply( lambda x: float(x.replace(",", "."))) rws_stations.loc[:, 'y'] = rws_stations.y.apply( lambda x: float(x.replace(",", "."))) rws_stations.loc[:, 'geometry'] = rws_stations.apply(lambda x: Point(x.x, x.y), axis=1) rws_stations = gpd.GeoDataFrame(rws_stations) rws_stations.crs = {'init': 'epsg:25831'} rws_stations = rws_stations.to_crs({'init': 'epsg:4326'}) rws_stations = rws_stations.loc[:, ['name', 'geometry']] rws_stations.loc[:, 'maas'] = rws_stations.geometry.apply( lambda x: distance(x, closest_point(x, Maas)) < 3) rws_stations.loc[:, 'waal'] = rws_stations.geometry.apply( lambda x: distance(x, closest_point(x, Waal)) < 3) rws_stations.loc[rws_stations.name == 'Sint Andries Waal', 'maas'] = False rws_stations.loc[:, 'x_maas'] = rws_stations.apply( lambda x: Maas.project(x.geometry) if x.maas else np.nan, axis=1) rws_stations.loc[:, 'x_waal'] = rws_stations.apply( lambda x: Waal.project(x.geometry) if x.waal else np.nan, axis=1) rws_stations = rws_stations.loc[ np.logical_or(rws_stations.maas, rws_stations.waal), ['name', 'geometry', 'x_maas', 'x_waal']] rws_stations.columns = ["id", "geometry", "x_maas", "x_waal"] rws_stations.to_file("data/shapefiles/rws_locations/rws_locations.shp") rws_data = rws_data.groupby(['name', 'date', 'time']).mean().reset_index() rws_data = rws_data.groupby(['name', 'date']).mean().reset_index()
#plt.show() plt.savefig(figpath+saveas,bbox_inches='tight') #--------------------------------------------------------- # For each WSL site, identify the tree closest Meteoswiss stations #--------------------------------------------------------- # Loop over all WSL sites nearest = [] distances = [] closest_stations = [] for i in range(0,len(treenetcoords_lat)): # Calculate distance to all meteoswiss stations for each WSL site distance_to_meteo = [] for j in range(0,len(stationnames_new)): distance_to_meteo.append(distance((treenetcoords_lat[i],treenetcoords_lon[i]),(stationcoords_lat[j],stationcoords_lon[j]))) # Find indices of the three nearest stations # method using np.argpartition distance_to_meteo = np.array(distance_to_meteo) k = 3 idx = np.argpartition(distance_to_meteo,k) nearest.append(idx[:k]) # Save distance of three nearest stations distances.append(distance_to_meteo[idx[:k]]) # Print out result for manual check print('The 3 nearest stations for '+treenetstationnames[i]+' are ' +stationnames_new[idx[0]]+', '+stationnames_new[idx[1]]+' and '+stationnames_new[idx[2]])