def Change(self): for x in interface.user_interface.an.aliens: if common.distance(x.pos,self.pos)<.01: x.speed=abs(gauss(.5,.3)) x.Force=abs(gauss(.5,.3)) self._out() for x in interface.user_interface.an.predators: if common.distance(x.pos,self.pos)<.01: x.speed=abs(gauss(.5,.3)) x.Forse=abs(gauss(.5,.3)) self._out()
def findClosestStop(self): return_dict = {} for dir_tag in self.bus_dir_tag_dict: #logging.info(dir_tag) stop_loc_array = [] stop_id_array = [] for stop in self.stop_dict: stop_loc_array.append([float(self.stop_dict[stop]['lat']), float(self.stop_dict[stop]['lon'])]) stop_id_array.append(str(stop)) # TODO what is this really? logging.info(self.stop_dict) logging.info(stop_loc_array) tree = KDTree(np.array(stop_loc_array)) for bus in self.bus_dir_tag_dict[dir_tag]: if len(bus_id_array) > 1: #True:#try: # TODO make this use bus heading to find the next stop, not the closest stop logging.info("CLOSEST STOP TO BUS %s") closest_bus_distance, index = tree.query(np.array([float(bus.lon), float(bus.lat)]),2) for i in range(3): closest_stop = stop_id_array[index[i]] dist = common.distance(bus.lon, bus.lat, stop_loc_array[index[i]][0], stop_loc_array[index[i]][1]) heading = common.heading_angle(bus.lon, bus.lat, stop_loc_array[index[i]][0], stop_loc_array[index[i]][1]) logging.info("STOP %s DIST %s HEADING %s" % (closest_stop, dist, heading)) bus.nextStopId = closest_stop bus.distanceNextBus = float(dist) return_dict[bus.vehicleId] = {'closest_stop' : closest_stop, 'closest_stop_distance' : dist} else:#except: return_dict[bus.vehicleId] = {'closest_stop' : None, 'closest_stop_distance' : None} return return_dict
def findBunchingInRoute(self): return_dict = {} for dir_tag in self.bus_dir_tag_dict: #logging.info(dir_tag) bus_loc_array = [] bus_id_array = [] for bus in self.bus_dir_tag_dict[dir_tag]: bus_loc_array.append([float(bus.lon), float(bus.lat)]) bus_id_array.append(str(bus.vehicleId)) # TODO what is this really? #logging.info(bus_loc_array) tree = KDTree(np.array(bus_loc_array)) for bus in self.bus_dir_tag_dict[dir_tag]: if len(bus_id_array) > 1: #True:#try: #logging.info(tree.query(np.array([float(bus.lon), float(bus.lat)]),2)) closest_bus_distance, index = tree.query(np.array([float(bus.lon), float(bus.lat)]),2) closest_bus = bus_id_array[index[1]] dist = common.distance(bus.lon, bus.lat, bus_loc_array[index[1]][0], bus_loc_array[index[1]][1]) bus.nextBusId = closest_bus bus.distanceNextBus = float(dist) return_dict[bus.vehicleId] = {'closest_bus' : closest_bus, 'closest_bus_distance' : dist} else:#except: return_dict[bus.vehicleId] = {'closest_bus' : None, 'closest_bus_distance' : None} return return_dict
def check_hit_by_bullet(self, bullets): for enemy in self.enemies: for bullet in bullets: if distance(enemy.pos, bullet.pos) < 4: enemy.hp -= bullet.damage bullet.is_alive = False self.score += 10 if enemy.hp <= 0 else 0
def check(self, fl): if self.params["arg_alerts"] is False: return # log("Check Flight ", fl.data, fl.pos) # Alert delayed waiting for position or least 16 messages if fl.data['nm'] < 16: if fl.pos['alt_ls'] == 0: return None if fl.pos['lat_ls'] == 0.0 and fl.pos['long_ls']: return None for alert in self.list: # log("Check alert",alert.message()) if fl.data['ls'] - alert.fs < alert.alert[4]: continue if ((alert.alert[1] == 'ic' and alert.alert[2] == fl.data['ic']) or (alert.alert[1] == 'sq' and alert.alert[2] == fl.data['sq']) or (alert.alert[1] == 'cs' and alert.alert[2] == fl.data['cs'])): alert.fs = fl.data['ls'] # log("Matching ", alert.message()) lat_ref = float(self.params["lat"]) long_ref = float(self.params["long"]) if fl.pos['lat_ls'] != 0.0 and fl.pos['long_ls'] != 0.0: dist = distance(fl.pos['lat_ls'], fl.pos['long_ls'], lat_ref, long_ref) bear = bearing(lat_ref, long_ref, fl.pos['lat_ls'], fl.pos['long_ls']) else: dist = bear = 0.0 alert.log(fl.data['ls'], fl.data['ic'], fl.pos['alt_ls'], dist, bear) return alert return None
def calc_basis(cls, start_at): reverse_dist = cls.calc_reverse(start_at) old_dist = cls.calc_old_dist(from_node=start_at - 1) roller = common.distance(cls.nodes[cls.solution[start_at - 1]], cls.solution_nodes[start_at - 1 + 2:]) return reverse_dist, old_dist, roller
def print(self, _file=sys.stdout): if _file == sys.stderr and (self.data['nm'] < 16 or (time() - self.data['ls']) > 120): return lat_ref = float(self.params["lat"]) long_ref = float(self.params["long"]) dist = 0.0 bear = 0.0 if self.pos['lat_ls'] != 0.0 and self.pos['long_ls'] != 0.0: dist = distance(self.pos['lat_ls'], self.pos['long_ls'], lat_ref, long_ref) bear = bearing(lat_ref, long_ref, self.pos['lat_ls'], self.pos['long_ls']) fmt = "{:s} " * 4 + "{:>8s} {:5d} {:7.1f}" + 4 * " {:5d}" + \ " {:9.5f} {:9.5f} {:5.1f} {:5.1f}° {:5.1f}°" print(fmt.format(strftime("%d %H:%M:%S", gmtime(self.data['fs'])), strftime("%d %H:%M:%S", gmtime(self.data['ls'])), self.data['ic'], str(self.data['sq']), str(self.data['cs']), self.data['nm'], self.data['ls'] - self.data['fs'], self.pos['alt_fs'], self.pos['alt_ls'], self.pos['alt_min'], self.pos['alt_max'], self.pos['lat_ls'], self.pos['long_ls'], dist, bear, self.pos['head_ls']), file=_file)
def _evaluate_grad_attractive_potential(self, q: np.ndarray) -> np.ndarray: d2goal = distance(q, self._goal) if d2goal <= self._dstar: grad_u_attr = self._zeta * (q - self._goal) else: grad_u_attr = self._dstar * self._zeta * (q - self._goal) / d2goal return grad_u_attr
def _evaluate_attractive_potential(self, q: np.ndarray) -> float: d2goal = distance(q, self._goal) if d2goal <= self._dstar: u_attr = .5 * self._zeta * d2goal**2 else: u_attr = self._dstar * self._zeta * d2goal - .5 * self._zeta * self._dstar**2 return u_attr
def _move_to(self, i, j): if self.intpos != None: self.pos = deepcopy(interface.user_interface.setka[self.intpos[0]][self.intpos[1]]) self.intpos = None self.movingto = [i, j] if self.sj: # значит х неизменный, идем по у self.pos[1] += abs(self.timer.dt() * self.speed) * self.sj elif self.si: # значит y неизменный, идем по x self.pos[0] += abs(self.timer.dt() * self.speed) * self.si l = common.distance(self.pos, interface.user_interface.setka[self.movingto[0]][self.movingto[1]]) if l > self.prev: self.intpos = deepcopy(self.movingto) self.pos = deepcopy(interface.user_interface.setka[self.intpos[0]][self.intpos[1]]) self.movingto = None self.prev = 100.0 else: self.prev = common.distance(self.pos, interface.user_interface.setka[self.movingto[0]][self.movingto[1]])
def animsearch(self): minim = [100500.0, 0, 0] i = 0 for x in interface.user_interface.an.aliens: m = common.distance(x.pos, self.pos) if m < minim[0]: minim[0] = m minim[1] = i i += 1 i = 0 if self.satiety < 0.1: for x in interface.user_interface.an.predators: m = common.distance(x.pos, self.pos) if m < minim[0] and self.i != x.i: minim[0] = m minim[1] = i minim[2] = 1 i += 1 if minim[0] == 100500.0: return (0, 0) if minim[2]: if interface.user_interface.an.predators[minim[1]].intpos != None: return ( interface.user_interface.an.predators[minim[1]].intpos[0] - self.intpos[0], interface.user_interface.an.predators[minim[1]].intpos[1] - self.intpos[1], ) else: return ( interface.user_interface.an.predators[minim[1]].movingto[0] - self.intpos[0], interface.user_interface.an.predators[minim[1]].movingto[1] - self.intpos[1], ) else: if interface.user_interface.an.aliens[minim[1]].intpos != None: return ( interface.user_interface.an.aliens[minim[1]].intpos[0] - self.intpos[0], interface.user_interface.an.aliens[minim[1]].intpos[1] - self.intpos[1], ) else: return ( interface.user_interface.an.aliens[minim[1]].movingto[0] - self.intpos[0], interface.user_interface.an.aliens[minim[1]].movingto[1] - self.intpos[1], )
def update(self): Animal.update(self) self.satiety -= 0.001 if self.satiety < 0.1: for x in interface.user_interface.an.predators: if common.distance(x.pos, self.pos) < 0.01 and self.i != x.i and self.alive: self.fight(x) for x in interface.user_interface.an.aliens: if common.distance(x.pos, self.pos) < 0.01: self.kill(x) if self.intpos != None: i, j = self.animsearch() self.si = common.sign(i) self.sj = common.sign(j) self._move(i, j) else: self._move_to(self.movingto[0], self.movingto[1])
def calculate_path(self, start: np.ndarray, max_steps: int = 1000000, epsilon: float = None) -> np.ndarray: epsilon = self._epsilon if epsilon is None else epsilon path = np.zeros((max_steps, 2)) path[0] = start step = 1 while distance(path[step - 1], self._goal) > EPS and step < max_steps: grad = self._evaluate_grad_potential(path[step - 1]) path[step] = path[step - 1] - epsilon * grad step += 1 return path[:step]
def _verify( goal: np.ndarray, workspace: Circle, k: int, default_epsilon: float) -> Tuple[np.ndarray, Circle, int, float]: assert goal.size == 2, 'Goal must be a two-dimensional point' r_goal = distance(goal, workspace.center) assert r_goal <= workspace.radius, 'Goal must be inside the workspace' assert k > 0, 'Parameter k must be a value greater than zero' assert default_epsilon > 0, 'Epsilon must be a value greater than 0' return goal.copy(), workspace, k, default_epsilon
def add_distance_to_dict(user_latitude, user_longitude, bus_stops_data): """ This method modifies the bus stop list of dictionaries and adds the distance of the bus stop from the user to each record. """ for data in bus_stops_data: if "Distance" in data: del data["Distance"] # this deletes the existing distance data for data in bus_stops_data: dist = distance(user_latitude, user_longitude, data["Latitude"], data["Longitude"]) data[ "Distance"] = dist # add all the respective distance into the data in the list of data return bus_stops_data
def calculate_path(self, start: np.ndarray, max_steps: int = 10000, epsilon: float = None, scale_magnitude: float = None) -> np.ndarray: epsilon = self._epsilon if epsilon is None else epsilon starting_distance = distance(start, self._goal) path = np.zeros((max_steps, 2)) path[0] = start step = 1 while distance(path[step - 1], self._goal) > EPS and step < max_steps: grad = self._evaluate_grad_phi(path[step - 1]) if scale_magnitude is not None: d2goal = min(distance(path[step - 1], self._goal), starting_distance) eta = (d2goal / starting_distance)**2 grad = eta * scale_magnitude * grad / np.linalg.norm(grad) path[step] = path[step - 1] - epsilon * grad step += 1 return path[:step]
def calc_connector(cls, roller, left, node_before_a, node_a): to_d = roller[:-1].copy() offset = left % 10 if node_before_a not in cls.prime_set and offset == 0: to_d *= common.penalty roller = common.distance(cls.nodes[node_a], cls.solution_nodes[left + 2:]) if node_a in cls.prime_set: return to_d, roller, roller else: start_leg = (10 - left - 2) % 10 from_a = roller.copy() from_a[start_leg::10] *= common.penalty return to_d, from_a, roller
def _evaluate_repulsive_potential(self, q: np.ndarray) -> float: u_rep = 0 d2circle = self._workspace.radius - distance(q, self._workspace.center) if d2circle < EPS: u_rep += LARGE elif abs(d2circle) <= self._workspace.safe_distance: u_rep += .5 * self._eta * ((1 / d2circle) - (1 / self._workspace.safe_distance)) ** 2 for circle in self._obstacles: d2circle = circle_distance(q, circle) if d2circle < EPS: u_rep += LARGE elif d2circle <= circle.safe_distance: u_rep += .5 * self._eta * ((1 / d2circle) - (1 / circle.safe_distance))**2 return u_rep
def test_bifurcation_angle(common_input, angle): common_input.update(dict(keep_fixed_1 = False, keep_fixed_2 = False, bif = False, lower = False, cylinder_factor = 7, angle = angle, region_of_interest = "commandline", region_points = [35.8, 59.8, 39.7, 76.8, 54.7, 53.2])) rotate_branches(**common_input) # Read in files to compute angle base_path = get_path_names(common_input["input_filepath"]) old_centerlines = read_polydata(base_path + "_centerline_par.vtp") new_centerlines = read_polydata(base_path + "_centerline_interpolated_ang.vtp") end_points = read_polydata(base_path + "_clippingpoints.vtp") # Start points start_point1 = end_points.GetPoint(1) start_point2 = end_points.GetPoint(2) # Get relevant centerlines cl_old_1 = -1 cl_old_2 = -1 cl_new_1 = -1 cl_new_2 = -1 tol = get_tolerance(old_centerlines) for i in range(old_centerlines.GetNumberOfLines()): line_old = extract_single_line(old_centerlines, i) line_new = extract_single_line(new_centerlines, i) loc_old = get_locator(line_old) loc_new = get_locator(line_new) id1_old = loc_old.FindClosestPoint(start_point1) id2_old = loc_old.FindClosestPoint(start_point2) id1_new = loc_new.FindClosestPoint(start_point1) id2_new = loc_new.FindClosestPoint(start_point2) if distance(start_point1, line_old.GetPoint(id1_old)) < tol: cl_old_1 = i cl_old_id1 = id1_old if distance(start_point2, line_old.GetPoint(id2_old)) < tol: cl_old_2 = i cl_old_id2 = id2_old if distance(start_point1, line_new.GetPoint(id1_new)) < tol: cl_new_1 = i cl_new_id1 = id1_new if distance(start_point2, line_new.GetPoint(id2_new)) < tol: cl_new_2 = i cl_new_id2 = id2_new if -1 not in [cl_old_1, cl_old_2, cl_new_1, cl_new_2]: break # Get end points end_point1_old = np.array(extract_single_line(old_centerlines, cl_old_1).GetPoint(cl_old_id1 + 20)) end_point2_old = np.array(extract_single_line(old_centerlines, cl_old_2).GetPoint(cl_old_id2 + 20)) end_point1_new = np.array(extract_single_line(new_centerlines, cl_new_1).GetPoint(cl_new_id1 + 20)) end_point2_new = np.array(extract_single_line(new_centerlines, cl_new_2).GetPoint(cl_new_id2 + 20)) # Vectors v1_old = end_point1_old - np.array(start_point1) v2_old = end_point2_old - np.array(start_point2) v1_new = end_point1_new - np.array(start_point1) v2_new = end_point2_new - np.array(start_point2) # Normalize v1_old = v1_old / np.sqrt(np.sum(v1_old**2)) v2_old = v2_old / np.sqrt(np.sum(v2_old**2)) v1_new = v1_new / np.sqrt(np.sum(v1_new**2)) v2_new = v2_new / np.sqrt(np.sum(v2_new**2)) # Angle first_daughter_branch_angle_change = np.arccos(np.dot(v1_old, v1_new)) second_daughter_branch_angle_change = np.arccos(np.dot(v2_old, v2_new)) assert abs(first_daughter_branch_angle_change + second_daughter_branch_angle_change - 2 * abs(common_input["angle"])) < 0.01
def _evaluate_grad_gamma(self, q: np.ndarray) -> np.ndarray: grad_gamma = 2 * self._k * distance(q, self._goal)**( 2 * self._k - 1) * (q - self._goal) / distance(q, self._goal) return grad_gamma
def _evaluate_beta_i(q: np.ndarray, obstacle: Circle): return distance(q, obstacle.center)**2 - obstacle.radius**2
def _evaluate_gamma(self, q: np.ndarray) -> float: gamma = distance(q, self._goal)**(2 * self._k) return gamma
def bar_code(binary, gray, min_ratio=2, min_area=80, max_area=30000): # 中值滤波 img = cv2.medianBlur(binary, 3) # 形态学处理 img = common.dilate_(img, ksize=(3, 3), iterations=4) _, contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) def max_filter(tour): area = cv2.contourArea(tour) if min_area <= area <= max_area: return True return False contours = filter(max_filter, contours) contours = sorted(contours, key=cv2.contourArea, reverse=True) contours = contours[:min(25, int(0.2 * len(contours)))] angles = {} for cnt in contours: rect = cv2.minAreaRect(cnt) box = np.int0(cv2.boxPoints(rect)) if min_ratio <= common.distance(box[0], box[1]) / common.distance( box[1], box[2]): if box[1][0] - box[0][0] == 0: angle = 90 else: angle = math.atan((box[1][1] - box[0][1]) / (box[1][0] - box[0][0])) * 180 / np.pi elif min_ratio <= common.distance(box[1], box[2]) / common.distance( box[0], box[1]): if box[1][0] - box[2][0] == 0: angle = 90 else: angle = math.atan((box[1][1] - box[2][1]) / (box[1][0] - box[2][0])) * 180 / np.pi else: continue # cv2.drawContours(gray, [box], -1, (200, 200, 200), 3) key = (angle + 75) / 30 if key < 0: key = key + 6 angle = angle + 180 key = int(key) value = angles.setdefault(key, []) value.append(angle) angles = sorted(angles.items(), key=lambda item: len(item[1]), reverse=True) key, value = angles[0] rot_angle = np.median(value) h, w = gray.shape[:2] if abs(rot_angle) > 45: side = max(w, h) center = (side / 2, side / 2) new_shape = (side, side) else: center = (w / 2, h / 2) new_shape = (w, h) M = cv2.getRotationMatrix2D(center, rot_angle, 1) gray = cv2.warpAffine(gray, M, new_shape) return gray
def check_hit_by_enemy(self, enemies): for enemy in enemies: if distance(self.player.pos, enemy.pos) < 4 and not self.player.invincible_time > 0: self.player.life -= 1 self.player.invincible_time = PLAYER_INVINCIBLE_TIME
def check_hit_by_bullet(self, bullets): for bullet in bullets: if distance(self.player.pos, bullet.pos) < 4 and not self.player.invincible_time > 0: self.player.life -= 1 self.player.invincible_time = PLAYER_INVINCIBLE_TIME bullet.is_alive = False