def visible(self, x, y, gmap): # returns if the grid-square (x, y) is visible. # Check if the point is in the field of view: xoff = x + 0.5 yoff = y + 0.5 if dist(xoff, yoff, self.location[0], self.location[1]) > self.fov_radius: return False if dist(xoff, yoff, self.location[0], self.location[1]) < 1: return True angle = self.orientation if xoff == self.location[0]: if yoff > self.location[1]: angle -= 3 * math.pi / 2 else: angle -= math.pi / 2 else: angle -= math.atan2(self.location[1] - yoff, xoff - self.location[0]) while angle > math.pi: angle -= 2 * math.pi while angle < -math.pi: angle += 2 * math.pi if math.fabs(angle) > self.fov_angle: return False # Check if there's a wall in the way: # curloc = self.location # Never mind, we'll do this later maybe. If it's a wall, though: if gmap.walls[x][y] == 1: return True return True
def obtain_sigma(self, n, k): if (self.type == Antenna.RRH_ID): #RRH macro = self.near_macro(self._grid.bs_list) dMue = util.dist(macro, self.connected_ues[n]) #distancia rrh to user dMn = 31.5 + 35.0 * math.log10(dMue) #pathloss hRnk = 1 #channel gain hMnk = 1 #channel gain Pm = self.PMmax #pmax b0 = self.B0 #bandwidth N0 = util.sinr( self.p[n][k], self.i[n][k], util.noise() ) # estimated power spectrum density of both the sum of noise and weak inter-RRH interference (in dBm/Hz) dRue = util.dist(self, self.connected_ues[n] ) #distancia rrh to user#distancia rrh to user dRn = 31.5 + 40.0 * math.log10(dRue) return (dRn * hRnk) / (Pm * dMn * hMnk + b0 * N0) else: #MACRO dMue = util.dist(self, self.connected_ues[n]) #distancia rrh to user dMn = 31.5 + 35.0 * math.log10(dMue) #pathloss hMnk = 1 #channel gain b0 = self.B0 #bandwidth N0 = util.sinr( self.p[n][k], self.i[n][k], util.noise() ) # estimated power spectrum density of both the sum of noise and weak inter-RRH interference (in dBm/Hz) #print dMn, hMnk, b0, N0 return (dMn * hMnk) / (b0 * N0)
def _move (self): # self.x = clamp(self.x + random.randint(-1, 1), 0, self.state.map.w - 1) # self.y = clamp(self.y + random.randint(-1, 1), 0, self.state.map.h - 1) step_x, step_y = self.state.heart.x, self.state.heart.y baits = [e for e in self.state.entities if isinstance(e, towers.Bait)] if baits: curr_bait = baits[0] for bait in baits: if util.dist(self.x, self.y, curr_bait.x, curr_bait.y) > util.dist(self.x, self.y, bait.x, bait.y): curr_bait = bait step_x, step_y = curr_bait.x, curr_bait.y tcod.line_init(self.x, self.y, step_x, step_y) x, y = tcod.line_step() if x is None: pass else: did_hit = False for e in self.state.entities: if e.x == x and e.y == y and isinstance(e, towers.Building): self.hit(e) did_hit = True if not did_hit: self.x = x self.y = y
def collect_data(timer): nose_avg = 0 imu_values_avg = { "accel": Vector3(), "gyro": Vector3(), "mag": Vector3(), "temp": 0 } print("collecting data ... ") for i in range(BATCH_SIZE): nose_avg += dist(mic_adc.read(), "noise") imu_values = imu_collect() imu_values_avg.update( (k, v + dist(imu_values[k], k)) for k, v in imu_values_avg.items()) nose_avg = nose_avg / BATCH_SIZE imu_values_avg.update( (k, v / BATCH_SIZE) for k, v in imu_values_avg.items()) topic = "channels/" + TS_CHANNEL_ID + "/publish/" + TS_WRITE_KEY message = "field1={}&field2={}&field3={}&field4={}&field5={}".format( nose_avg, imu_values_avg["accel"], imu_values["gyro"], imu_values["mag"], imu_values_avg["temp"]) mqtt.publish(topic, message) sleep(SEND_TIME)
def visible(self, x, y, gmap): # returns if the grid-square (x, y) is visible. # Check if the point is in the field of view: xoff = x+0.5 yoff = y+0.5 if dist(xoff, yoff, self.location[0], self.location[1]) > self.fov_radius: return False if dist(xoff, yoff, self.location[0], self.location[1]) < 1: return True angle = self.orientation if xoff == self.location[0]: if yoff > self.location[1]: angle -= 3 * math.pi / 2 else: angle -= math.pi / 2 else: angle -= math.atan2(self.location[1] - yoff, xoff - self.location[0]) while angle > math.pi: angle -= 2 * math.pi while angle < -math.pi: angle += 2 * math.pi if math.fabs(angle) > self.fov_angle: return False # Check if there's a wall in the way: # curloc = self.location # Never mind, we'll do this later maybe. If it's a wall, though: if gmap.walls[x][y] == 1: return True return True
def neighbor(neighbors): nearest = neighbors[0] dist = float("inf") for p in nodes: temp = util.dist(p.get_position(), rand) if (temp < util.dist(nearest.get_position(), rand)): nearest = p dist = temp return nearest, dist
def test(self): point1 = [980.0345696465944, 723.5366155960791] point2 = [481.2932366856792, 757.4846282210185] point3 = [9.08469719254, 37.7420706336] point4 = [17.2527181564, 43.4821910282] print(dist(point1, point3), dist(point1, point4)) point_candidate1, point_array1 = self.step_from_to(point3, point1) point_candidate2, point_array2 = self.step_from_to(point4, point1) print(self.collides(point_array1), self.collides(point_array2)) print(point_candidate1, point_candidate2)
def getBestCar(ride, cars, T): start, end = ride.from_pos, ride.to_pos distToStart = dist(start, cars[0].pos) carIndex = 0 for x in range(1, len(cars)): distToCar = dist(start, cars[x].pos) if(distToStart > distToCar): stepsToTake = distToCar + dist(start, end) if((stepsToTake + cars[x].steps) <= T): distToStart = distToCar carIndex = x return carIndex
def updatePos(self): """moves foe and makes it stop at its goal""" while dist(self.goalPos, self.rect.center) <= 1 + self.speed and self.alwaysMove: self.goalPos = (randint(20, 1200), randint(1, 450)) if dist(self.goalPos, self.rect.center) > 1 + self.speed: dx = self.goalPos[0] - self.rect.centerx dy = self.goalPos[1] - self.rect.centery mag = sqrt(dx**2 + dy**2) self.velocity = [self.speed * dx / mag, self.speed * dy / mag] util.move(self)
def move_to_target(self, target_position): dist = util.dist(target_position, self.pose) # print('random target position x:%f y:%f altitude:%f' % # (target_position[0], target_position[1], target_position[2])) # print('error:' + str(dist)) target_angle = math.atan2(target_position[0] - self.pose[0], -(target_position[1] - self.pose[1])) target_angle = math.degrees(target_angle) dist = util.dist(target_position, self.pose) x_speed = 20 if dist < 50: # iha yi yavaslat x_speed = dist * 0.25 self.send_move_cmd(x_speed, 0, target_angle, target_position[2])
def derive_dl(distances): distances = Counter(distances) X = set([0]) width = max(distances) while len(distances) > 0: y = max(distances) if contains(dist(y, X), distances): X |= frozenset([y]) distances -= dist(y, X) else: X |= frozenset([width - y]) distances -= dist(width - y, X) return sorted(X)
def is_cursor(b): max_size = h * 0.05 # cursor is teensy tiny cx, cy = b.centroid() max_dist_from_center = h * 0.2 # and close to the middle return (b.width() < max_size and b.height() < max_size and dist(cx, cy, midx, midy) < max_dist_from_center)
def arr_to_polar(arr): w, h = arr.shape cx, cy = w/2, h/2 max_r = ceil(dist(0, 0, cx, cy)) new_w = 100 new_h = 62 x_bound = new_w - 1 y_bound = new_h - 1 new_arr = np.zeros((new_w, new_h), dtype=np.bool_) it = np.nditer(arr, flags=['multi_index']) while not it.finished: x, y = it.multi_index r, t = cart_to_polar(x-cx,cy-y) # flip y new_x = x_bound - int(x_bound * (t + pi) / ( 2 * pi)) new_y = int(y_bound * r/max_r) new_arr[new_x, new_y] = it[0] it.iternext() return new_arr
def resolv_stabmoney(self): # evol stab genstab = 0 if self.policy == I('entertain'): genstab += 1 elif self.policy == I('integrism') or self.policy == I('slavery'): genstab -= 2 if self.owner.capital: d = dist(self.referer.position, self.owner.capital.referer.position) if d < len(conf.stab_dist): genstab += conf.stab_dist[d] else: genstab += conf.stab_dist[-1] else: genstab += conf.stab_nocap # todo : bonus gouv and cmd for p in self.planets.itervalues(): p.evol_stab(genstab) p.test_revolt() # money money money = 0 for p in self.planets.itervalues(): if p.revolt: continue money += p.collect() if self.policy == I('tax'): money = floor(money * 1.15) # todo : bonus gouv and cmd self.owner.set_budget(I('budget_tax'), -money)
def merge(clusts, centroids, mats, maps, i): minDist = -1 index = -1 cent = centroids[i] for j in range(0, len(centroids)): distance = u.dist(cent, centroids[j]) if (i == j): continue elif (minDist == -1) or distance < minDist: minDist = distance index = j for j in range(0, len(clusts[i])): if not isinstance(clusts[index], list): clusts[index] = clusts[index].tolist() clusts[index].append(clusts[i][j]) newMat = [] newMap = {} st.redoMatrix(clusts, index, newMat, newMap) mats[index] = np.array(newMat) maps[index] = newMap newCent = u.findCenter(mats[index]) centroids[index] = newCent maps.pop(i) mats.pop(i) centroids.pop(i) clusts.pop(i)
def loc_pairs_to_connect(pieces, resistors): """ Returns a tuple of the locations pairs to connect so that the |pieces| and |resistors| are appropriately connected. Each location pairs comes with a flag indicating whether or not to include a resistor. Each location pair also comes with the node for the pair. If there is to be a resistor between the locations, the node of the first location is given ( both nodes can be obtained from the flag, the first is given for the sake of consistency). """ # find loc pairs to connect not taking resistors into account loc_pairs = reduce(list.__add__, (loc_pairs_for_node(locs_for_node(pieces, node), node) for node in all_nodes(pieces) if node), []) # find loc pairs to connect for resistors occurences = defaultdict(int) flagged_loc_pairs = [] for loc_1, loc_2, node in loc_pairs: occurences[loc_1] += 1 occurences[loc_2] += 1 flagged_loc_pairs.append((loc_1, loc_2, None, node)) # where resistors are treated as wires, what we have here is very ad hoc! for resistor in resistors: loc_1, loc_2 = min(product(locs_for_node(pieces, resistor.n1), locs_for_node(pieces, resistor.n2)), key=lambda (loc_1, loc_2): 5 * ( occurences[loc_1] + occurences[loc_2]) + dist(loc_1, loc_2)) occurences[loc_1] += 1 occurences[loc_2] += 1 flagged_loc_pairs.append((loc_1, loc_2, resistor, resistor.n1)) return flagged_loc_pairs
def loc_pairs_for_node(node_locs, node): """ Returns a list of tuples of the form (loc_1, loc_2, node) such that the set of locations in |nodes_locs| is fully connected if all the output pairs of locations are connected. This is essentially an MST problem where the locations are the nodes and the weight of an edge between two locations is the distance (manhattan) between the two locations. We use Kruskal's greedy algorithm. |node| is the corresponding node in for the locations in the circuit. """ if node == GROUND or node == POWER: return [(loc, closest_rail_loc(loc, GROUND_RAIL if node == GROUND else POWER_RAIL), node) for loc in node_locs] # find all possible pairs of locations all_loc_pairs = [(loc_1, loc_2) for i, loc_1 in enumerate(node_locs) for loc_2 in node_locs[i + 1:]] # sort in increasing order of loc pair distance all_loc_pairs.sort(key=lambda loc_pair: dist(*loc_pair)) disjoint_loc_pair_sets = Disjoint_Set_Forest() # initialize the graph as fully disconnected for loc in node_locs: disjoint_loc_pair_sets.make_set(loc) mst_loc_pairs = [] # add edges to the graph until fully connected, but use the least expensive # edges to do so in the process for (loc_1, loc_2) in all_loc_pairs: if (disjoint_loc_pair_sets.find_set(loc_1) != disjoint_loc_pair_sets.find_set(loc_2)): disjoint_loc_pair_sets.union(loc_1, loc_2) mst_loc_pairs.append((loc_1, loc_2, node)) return mst_loc_pairs
def aStar(self): """ runs the A* algorithm returns : bool (success) """ # verifie the goal can be reached # isGoalInWall = True # for x in xrange(len(self.blockMat)) : # for y in xrange(len(self.blockMat[x])) : # if self.isGoal((x,y)) and self.blockMat[x][y] : # isGoalInWall = False # break # if isGoalInWall : # return False if self.pathEnd != None: # if starting point fulfills the goal condition return True for x0, y0 in self.lowestCell(): if self.isGoal( (x0, y0)): # the algorithm ends if the goal condition is reached self.pathEnd = (x0, y0) return True self.statusMat[x0][y0] = -1 for x1, y1 in self.neighbors(x0, y0): newGScore = self.gScoreMat[x0][y0] + util.dist((x0, y0), (x1, y1)) if self.statusMat[x1][ y1] == 1 or self.gScoreMat[x1][y1] > newGScore: self.gScoreMat[x1][y1] = newGScore self.fScoreMat[x1][ y1] = newGScore + self.heuristicEstimate((x1, y1)) self.prevMat[x1][y1] = (x0, y0) self.addToOpenSet(x1, y1) return False
def isGoal(self, point): """ point : (int,int) returns : bool (goal condition reached) the goal condition is : being in the circle of center 'self.goal' and radius 'self.goalRadius' """ # return round(util.dist(point, self.goal), 3) <= self.goalRadius return round(util.dist(point, self.goal)) <= self.goalRadius
def merge(clusts, centroids, mats, maps, i): minDist = -1 index = -1 cent = centroids[i] for j in range(0, len(centroids)): distance = u.dist(cent,centroids[j]) if (i == j): continue elif (minDist == -1) or distance < minDist: minDist = distance index = j for j in range(0, len(clusts[i])): if not isinstance(clusts[index],list): clusts[index] = clusts[index].tolist() clusts[index].append(clusts[i][j]) newMat = [] newMap = {} st.redoMatrix(clusts, index, newMat, newMap) mats[index] = np.array(newMat) maps[index] = newMap newCent = u.findCenter(mats[index]) centroids[index] = newCent maps.pop(i) mats.pop(i) centroids.pop(i) clusts.pop(i)
def _on_event(self, event): """ Pygame event handler """ if event.type == pygame.QUIT: self.is_running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_r: # Start over with a fresh Model self.model = model.Model(self.size) self.focus_agent = None elif event.key == pygame.K_1: self.fps = GraphicsApp._FPS_SLOW elif event.key == pygame.K_2: self.fps = GraphicsApp._FPS_NORMAL elif event.key == pygame.K_3: self.fps = GraphicsApp._FPS_FAST elif event.key == pygame.K_4: self.fps = GraphicsApp._FPS_REALTIME # Render the screen one more time so the user knows the FPS self._on_render() elif event.key == pygame.K_q: self.is_running = False elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == GraphicsApp._PYGAME_MOUSE_LEFT: self.focus_agent = None for agent in self.model.agents: dist = util.dist(event.pos, agent.get_pos()) if dist <= agent.radius: self.focus_agent = agent break
def run_experiment(index, dataset_name, name, constraint_getter, master_tree, X, y, out_dir, n_iters=1000, add_constraint=200, add_score=200, add_likelihood=200, should_continue=False): N, D = X.shape df = Inverse(c=1) if dataset_name == 'iris': lm = GaussianLikelihoodModel(sigma=np.eye(D) / 9.0, sigma0=np.eye(D) / 2.0, mu0=X.mean(axis=0)).compile() elif dataset_name == 'zoo': lm = GaussianLikelihoodModel(sigma=np.diag(np.diag(np.cov(X.T))) / 4.0, sigma0=np.eye(D) / 2.0, mu0=X.mean(axis=0)).compile() else: lm = GaussianLikelihoodModel(sigma=np.diag(np.diag(np.cov(X.T))) / 2.0, sigma0=np.eye(D) / 2.0, mu0=X.mean(axis=0)).compile() if should_continue: with open(out_dir / name / 'scores-%u.pkl' % index, 'r') as fp: scores = pickle.load(fp) with open(out_dir / name / 'costs-%u.pkl' % index, 'r') as fp: costs = pickle.load(fp) with open(out_dir / name / 'final-tree-%u.pkl' % index, 'r') as fp: tree = DirichletDiffusionTree(df=df, likelihood_model=lm) tree.set_state(pickle.load(fp)) sampler = MetropolisHastingsSampler(tree, X) else: scores = [] costs = [] tree = DirichletDiffusionTree(df=df, likelihood_model=lm) sampler = MetropolisHastingsSampler(tree, X) sampler.initialize_assignments() if dataset_name == 'zoo': sampler.tree = sampler.tree.induced_subtree(master_tree.points()) current_run = [] for i in tqdm(xrange(n_iters + 1)): sampler.sample() current_run.append(sampler.tree) if i % add_score == 0: scores.append(dist(master_tree, sampler.tree)) if i % add_likelihood == 0: costs.append(sampler.tree.marg_log_likelihood()) if i != 0 and i % add_constraint == 0: if constraint_getter is not None: constraint = constraint_getter.get_constraint(current_run) if constraint is not None: sampler.add_constraint(constraint) current_run = [] # plot_tree(sampler.tree, y) (out_dir / name).mkdir_p() with open(out_dir / name / 'scores-%u.pkl' % index, 'w') as fp: pickle.dump(scores, fp) print len(costs) with open(out_dir / name / 'costs-%u.pkl' % index, 'w') as fp: pickle.dump(costs, fp) # with open(out_dir / name / 'trees-%u.pkl' % index, 'r') as fp: # previous_trees = pickle.load(fp) # with open(out_dir / name / 'trees-%u.pkl' % index, 'w') as fp: # pickle.dump(previous_trees + [t.get_state() for t in trees], fp) with open(out_dir / name / 'final-tree-%u.pkl' % index, 'w') as fp: pickle.dump(sampler.tree.get_state(), fp) return costs, scores, sampler
def loc_pairs_for_node(node_locs, node): """ Returns a list of tuples of the form (loc_1, loc_2, node) such that the set of locations in |nodes_locs| is fully connected if all the output pairs of locations are connected. This is essentially an MST problem where the locations are the nodes and the weight of an edge between two locations is the distance (manhattan) between the two locations. We use Kruskal's greedy algorithm. |node| is the corresponding node in for the locations in the circuit. """ if node == GROUND or node == POWER: return [(loc, closest_rail_loc( loc, GROUND_RAIL if node == GROUND else POWER_RAIL), node) for loc in node_locs] # find all possible pairs of locations all_loc_pairs = [(loc_1, loc_2) for i, loc_1 in enumerate(node_locs) for loc_2 in node_locs[i + 1:]] # sort in increasing order of loc pair distance all_loc_pairs.sort(key=lambda loc_pair: dist(*loc_pair)) disjoint_loc_pair_sets = Disjoint_Set_Forest() # initialize the graph as fully disconnected for loc in node_locs: disjoint_loc_pair_sets.make_set(loc) mst_loc_pairs = [] # add edges to the graph until fully connected, but use the least expensive # edges to do so in the process for (loc_1, loc_2) in all_loc_pairs: if (disjoint_loc_pair_sets.find_set(loc_1) != disjoint_loc_pair_sets.find_set(loc_2)): disjoint_loc_pair_sets.union(loc_1, loc_2) mst_loc_pairs.append((loc_1, loc_2, node)) return mst_loc_pairs
def _find_wiring_per_pair(loc_pairs, start_proto_board, order, best_first, filter_wire_lengths, max_states_to_expand, verbose): """ Wiring each pair separately. """ proto_board = start_proto_board if verbose: print 'connecting %d pairs ...' % len(loc_pairs) all_num_expanded = [] sign = 1 if order is ORDER_INCREASING else -1 for i, loc_pair in enumerate( sorted(loc_pairs, key=lambda (loc_1, loc_2, resistor, node): sign * dist(loc_1, loc_2))): loc_1, loc_2, resistor, node = loc_pair if verbose: print '\t%d/%d connecting: %s -- %s' % (i + 1, len(loc_pairs), loc_1, loc_2) search_result, num_expanded = a_star( Proto_Board_Search_Node(proto_board, frozenset([loc_pair]), filter_wire_lengths=filter_wire_lengths), goal_test, heuristic, best_first=best_first, max_states_to_expand=max_states_to_expand) all_num_expanded.append(num_expanded) if search_result is not None: proto_board = search_result.state[0] if verbose: print proto_board else: if verbose: print '\tCouldn\'t do it :(' return None, all_num_expanded
def loc_pairs_to_connect(pieces, resistors): """ Returns a tuple of the locations pairs to connect so that the |pieces| and |resistors| are appropriately connected. Each location pairs comes with a flag indicating whether or not to include a resistor. Each location pair also comes with the node for the pair. If there is to be a resistor between the locations, the node of the first location is given ( both nodes can be obtained from the flag, the first is given for the sake of consistency). """ # find loc pairs to connect not taking resistors into account loc_pairs = reduce(list.__add__, (loc_pairs_for_node(locs_for_node(pieces, node), node) for node in all_nodes(pieces) if node), []) # find loc pairs to connect for resistors occurences = defaultdict(int) flagged_loc_pairs = [] for loc_1, loc_2, node in loc_pairs: occurences[loc_1] += 1 occurences[loc_2] += 1 flagged_loc_pairs.append((loc_1, loc_2, None, node)) # where resistors are treated as wires, what we have here is very ad hoc! for resistor in resistors: loc_1, loc_2 = min( product(locs_for_node(pieces, resistor.n1), locs_for_node(pieces, resistor.n2)), key=lambda (loc_1, loc_2): 5 * (occurences[loc_1] + occurences[loc_2]) + dist(loc_1, loc_2)) occurences[loc_1] += 1 occurences[loc_2] += 1 flagged_loc_pairs.append((loc_1, loc_2, resistor, resistor.n1)) return flagged_loc_pairs
def _find_wiring_per_pair(loc_pairs, start_proto_board, order, best_first, filter_wire_lengths, max_states_to_expand, verbose): """ Wiring each pair separately. """ proto_board = start_proto_board if verbose: print 'connecting %d pairs ...' % len(loc_pairs) all_num_expanded = [] sign = 1 if order is ORDER_INCREASING else -1 for i, loc_pair in enumerate(sorted(loc_pairs, key=lambda (loc_1, loc_2, resistor, node): sign * dist(loc_1, loc_2))): loc_1, loc_2, resistor, node = loc_pair if verbose: print '\t%d/%d connecting: %s -- %s' % (i + 1, len(loc_pairs), loc_1, loc_2) search_result, num_expanded = a_star(Proto_Board_Search_Node(proto_board, frozenset([loc_pair]), filter_wire_lengths=filter_wire_lengths), goal_test, heuristic, best_first=best_first, max_states_to_expand=max_states_to_expand) all_num_expanded.append(num_expanded) if search_result is not None: proto_board = search_result.state[0] if verbose: print proto_board else: if verbose: print '\tCouldn\'t do it :(' return None, all_num_expanded
def step_from_to(self, n1, n2): if n1.__class__.__name__ == "Node": p1 = n1.point else: p1 = n1 if n2.__class__.__name__ == "Node": p2 = n2.point else: p2 = n2 if dist(n1, n2) > self.EPSILON: theta = atan2(p2[1] - p1[1], p2[0] - p1[0]) p_new = [ p1[0] + self.EPSILON * cos(theta), p1[1] + self.EPSILON * sin(theta) ] else: p_new = p2 diff = int(max(abs(p1[0] - p_new[0]), abs(p1[1] - p_new[1]), 2)) point_array = zip(np.linspace(p1[0], p_new[0], diff), np.linspace(p1[1], p_new[1], diff)) return p_new, point_array
def cost((l1, l2)): wire = Wire(l1, l2, node) num_wires_crossed = sum(_wire.crosses(wire) for _wire in proto_board.get_wires()) num_pieces_crossed = sum(piece.crossed_by(wire) for piece in proto_board.get_pieces()) return 100 * (num_wires_crossed + num_pieces_crossed) + dist(l1, l2)
def timer_fired(self): """ The main game loop. """ self.robot.compute_lidar_measurement(self.obstacles) self.render() if self.path and not self.paused: i, j = self.path[0] x = j * GRID_WIDTH + GRID_WIDTH / 2 y = i * GRID_WIDTH + GRID_WIDTH / 2 if util.dist((x, y), self.robot.coord()) < MOVE_UNITS: self.path = self.path[1:] i, j = self.path[0] x = j * GRID_WIDTH + GRID_WIDTH / 2 y = i * GRID_WIDTH + GRID_WIDTH / 2 delta_theta = self.robot.turn_towards(x, y) self.robot.move(MOVE_UNITS) for p in self.particles: p.turn(delta_theta) p.move(MOVE_UNITS) if 0 < p.x < WIDTH and 0 < p.y < HEIGHT: p.compute_lidar_measurement(self.obstacles) self.particles = util.resample_particles( self.particles, self.robot.lidar_measurements) self.canvas.after(DELAY, self.timer_fired)
def main(rects, img): transformRects(rects) # rects = getGoodRects(rects,40,7) rects = hi(rects) #rects = sortRects(rects)[0:1] # rects = getSquare(rects)#[0:1] if (len(rects) == 0): raise NoRectException edges = formEdges(rects) length = mode( list(map(lambda e: dist(e[kCorners][0], e[kCorners][1]), edges))) print(length) edges = formEdges(rects, length=length, threshold=10) if (len(edges) == 0): raise NoEdgeException rects = [] # edges = filterEdgesByLength(edges) # edges = noEdge(edges) lRotation = getLocalRotation(edges) edges = filterEdgesByRotation(edges, lRotation) edges = adjustIntercept(edges) d = getLocalTranslation(edges, lRotation) print("lRot: ", lRotation, "lTra: ", d) printEdges(edges, img) # E1, E2 = partitionEdges(edges) # t1 = partitionAlignInterceptType(E1) # t2 = partitionAlignInterceptType(E2) # print(t1, t2) # [ox,oy,ix,iy,thetaIntercept] = getInterceptCommonOffsets(E1,E2, lRotation) # print(ox,oy,ix,iy,thetaIntercept,lRotation) # printIntercepts(E1, img) # printIntercepts(E2, img) # printGrid(ox,oy,ix,iy,thetaIntercept,lRotation,img,color=(255,0,255)) # printGrid(oy,ox,ix,iy,thetaIntercept,lRotation,img,color=(0,255,255)) return lRotation, d
def isGoal(self, point) : """ point : (int,int) returns : bool (goal condition reached) the goal condition is : being in the circle of center 'self.goal' and radius 'self.goalRadius' """ # return round(util.dist(point, self.goal), 3) <= self.goalRadius return round(util.dist(point, self.goal)) <= self.goalRadius
def power_calc(self, arb, user, particle, grid): antenna_index = int(arb/Antenna.TOTAL_RBS) antenna = grid.antennas[antenna_index] ue = grid.users[user] R = util.dist(ue, antenna) p = util.p_friis(antenna,self.i_particles[particle, user, arb], util.noise(), Antenna.T_GAIN, Antenna.R_GAIN, R, Antenna.WAVELENTH) #dBm return p
def aStar(self) : """ runs the A* algorithm returns : bool (success) """ # verifie the goal can be reached # isGoalInWall = True # for x in xrange(len(self.blockMat)) : # for y in xrange(len(self.blockMat[x])) : # if self.isGoal((x,y)) and self.blockMat[x][y] : # isGoalInWall = False # break # if isGoalInWall : # return False if self.pathEnd != None : # if starting point fulfills the goal condition return True for x0, y0 in self.lowestCell() : if self.isGoal((x0,y0)) : # the algorithm ends if the goal condition is reached self.pathEnd = (x0, y0) return True self.statusMat[x0][y0] = -1 for x1, y1 in self.neighbors(x0, y0) : newGScore = self.gScoreMat[x0][y0] + util.dist((x0,y0), (x1,y1)) if self.statusMat[x1][y1] == 1 or self.gScoreMat[x1][y1] > newGScore : self.gScoreMat[x1][y1] = newGScore self.fScoreMat[x1][y1] = newGScore + self.heuristicEstimate((x1,y1)) self.prevMat[x1][y1] = (x0,y0) self.addToOpenSet(x1,y1) return False
def heuristic(state): """ Returns an estimate of the distance between the given Proto_Board_Search_Node |state| and a goal state. """ proto_board, loc_pairs = state return sum(min(dist(loc_1, loc) for loc in proto_board.locs_connected_to( loc_2)) for loc_1, loc_2, resistor, node in loc_pairs)
def nuclear_energy(self,mol): Z = {'h':1,'he':2,'o':8,'c':6} N = mol.n_atoms E=0 for A in xrange(N): for B in xrange(A+1,N): E+=Z[mol.atoms[A].name]*Z[mol.atoms[B].name]/(dist(mol.atoms[A].xyz,mol.atoms[B].xyz)) return E
def num_neighbors(coin, all_coins, dist): ret = 0 nbrs = [] for c in all_coins: if c != coin and util.dist(c, coin) <= dist: ret = ret + 1 nbrs += [c] return ret, nbrs
def _distance_cost(placement): """ Placement cost based on total distance to connect. """ return sum( dist(loc_1, loc_2) for loc_1, loc_2, resistor_flag, node in loc_pairs_to_connect( placement, []))
def cost((l1, l2)): wire = Wire(l1, l2, node) num_wires_crossed = sum( _wire.crosses(wire) for _wire in proto_board.get_wires()) num_pieces_crossed = sum( piece.crossed_by(wire) for piece in proto_board.get_pieces()) return 100 * (num_wires_crossed + num_pieces_crossed) + dist( l1, l2)
def update(self,game): if(self.remaining == 1): for i in copy(game.bloons): if(dist(self.x,self.y,i.x,i.y) < self.range + 10): i.damage(game) self.valid = False game.add_effect(ColorFadeCircle(self.x+self.dx,self.y+self.dy,(255,0,0),self.range,100,20)) return super().update(game)
def get_start(parsed_frame): w, h = parsed_frame.img.size() rw, rh = parsed_frame.rot_arr.shape max_r = ceil(dist(0, 0, w/2, h/2)) cursor_x = int(float(rw) * parsed_frame.cursor_angle / 360) cursor_y = int(rh * parsed_frame.cursor_r/max_r) return cursor_x, cursor_y
def heuristic(state): """ Returns an estimate of the distance between the given Proto_Board_Search_Node |state| and a goal state. """ proto_board, loc_pairs = state return sum( min(dist(loc_1, loc) for loc in proto_board.locs_connected_to(loc_2)) for loc_1, loc_2, resistor, node in loc_pairs)
def transmission_power(antenna, user, interferece): R = util.dist(user, antenna) if (antenna.type == antenna.BS_ID): p = p_friis(antenna, interferece, util.noise(), threeGPP.HPN_T_GAIN, threeGPP.UE_R_GAIN, R, threeGPP.WAVELENTH) #dBm else: p = p_friis(antenna, interferece, util.noise(), threeGPP.LPN_T_GAIN, threeGPP.UE_R_GAIN, R, threeGPP.WAVELENTH) #dBm return p
def click_control(self, mouse_pos, button): removed = False wp = self.t.inv_transform_coord(mouse_pos) for waypoint in self.server_commander.waypoints: if dist(waypoint[0], waypoint[1], wp[0], wp[1]) < 0.25: self.server_commander.rmwp(waypoint[0], waypoint[1]) removed = True break if not removed: self.server_commander.addwp(wp[0], wp[1])
def reach_to_target(self): if self.target_position is None: return True thresh = 3.0 # bu degerden daha yakinsak vardik sayiyoruz dist = util.dist(self.target_position, self.pose) if dist < thresh: return True else: return False
def update(self, win): self.pos += (self.speed_x, -self.speed_y) self.speed_x += self.conf['wind_force']*self.world.wind self.speed_y -= self.conf['gravity'] * 0.001 h, w = win.getmaxyx() if (self.age > self.conf['shot_age'] or self.world.check_collision(self.pos) or min([dist(self.pos, p.pos) for p in self.world.players]) < 2): self.explode() return self.age += 1
def probHitEnemy(self, state, action): facedEnemies = self.enemiesFaced(state) prob = 0.0 for enemy in facedEnemies: dist = util.dist(state.player, enemy) if dist is not None: prob += 120 / dist # prob += 480/abs(enemy.rect.centerx - state.player.rect.centerx) # prob += 416/abs(enemy.rect.centery - state.player.rect.centery) return prob
def getBestRide(c, rides, T, B): index = {} for i in range(len(rides)): points = 0 steps = dist(c.pos, rides[i].from_pos) if (steps + c.steps) < rides[i].start: steps = rides[i].start - c.steps points = B elif (steps + c.steps) == rides[i].start: points = B tot_steps = steps + c.steps + dist(rides[i].from_pos, rides[i].to_pos) if tot_steps > T or tot_steps > rides[i].finish: continue else: points += dist(rides[i].from_pos, rides[i].to_pos) index[i] = steps # Different values: steps, points, points - steps if len(index) == 0: return None return min(index, key=index.get) #Change this to min or max
def combined_solve_layout(circuit, verbose=True): """ Creates a layout for the given |circuit| by using a combination of methods. Returns None on failure. """ partially_solved = [] for cost_type in (COST_TYPE_BLOCKING, COST_TYPE_DISTANCE): if verbose: print 'Cost type: %s' % cost_type placement, resistor_node_pairs = get_piece_placement(circuit, resistors_as_components=True, cost_type=cost_type, verbose=verbose) if placement is None: if verbose: print '\tToo many components.' continue for order_sign in (-1, 1): proto_board, nodes, loc_pairs = _setup(placement, resistor_node_pairs) if verbose: print proto_board loc_pairs.sort(key=lambda (loc_1, loc_2, resistor, node): order_sign * dist(loc_1, loc_2)) if verbose: print 'Order: %d' % order_sign failed_loc_pairs = [] for loc_pair in loc_pairs: loc_1, loc_2, resistor, node = loc_pair if verbose: print 'Connecting %s -- %s' % (loc_1, loc_2) wired_proto_board = _wire_loc_pair(loc_pair, proto_board) if wired_proto_board: proto_board = wired_proto_board if verbose: print proto_board print 'Success' else: failed_loc_pairs.append(loc_pair) if verbose: print 'Fail' if not failed_loc_pairs: return proto_board.prettified() else: partially_solved.append((proto_board, failed_loc_pairs)) if not partially_solved: return None def cost((proto_board, failed_loc_pairs)): return sum(dist(loc_1, loc_2) ** 2 for loc_1, loc_2, resistor, node in failed_loc_pairs) proto_board, failed_loc_pairs = min(partially_solved, key=cost) if verbose: print 'Using terrible wirer for: %s' % [(loc_1, loc_2) for (loc_1, loc_2, resistor, node) in failed_loc_pairs] terrible_proto_board = find_terrible_wiring(failed_loc_pairs, proto_board) if terrible_proto_board is not None: return terrible_proto_board.prettified() return None
def getPathLength(self) : """ returns : float sums the length of each segment of 'self.path' """ lastPoint = None length = 0 for x,y in self.path : if lastPoint != None : length += util.dist(lastPoint, (x,y)) lastPoint = (x,y) return length
def __init__(self, pos, angle, power, owner, conf): Shot.__init__(self, pos, angle, power, owner, conf) self.laser_points = [] for i in range(100): self.pos += (cos(angle), -sin(angle)) newpoint = self.pos.int() if(self.world.check_collision(newpoint)): break self.laser_points += [newpoint] for p in self.world.players: if(dist(newpoint, p.pos) < 2): p.health = max(0, p.health - (8 - int(i/20)))
def neighboringCentroid(cluster, index): amin = len(customerPoint(cluster[0])) neighborIndex = -.1 for i in range(0,len(centroids)): if i == index: continue dist = u.dist(centroids[i], centroids[index]) if dist < amin: amin = dist neighborIndex = i neighbor = centroids[neighborIndex] return neighbor
def _update_food(self, world_food): """ Allow Agents to eat Food objects """ # Eat any piece of Food that the Agent has collided with for food in world_food: this_dist = util.dist(self.get_pos(), food.get_pos()) max_dist = self.radius + food.radius if this_dist <= max_dist and food.is_alive(): self.health += food.eat() return # If no food was eaten the Agent is hungry self.health -= (self.forward_force * Agent._HUNGER_MOVEMENT_RATIO + Agent._HUNGER_PER_TICK)
def update(self, win): if(self.age >= self.radius): for p in self.world.players: d = max(dist(self.pos, p.pos) - 2, 0) if (d < self.radius): damage = self.damage * (self.radius - d)/self.radius p.health = max(0, int(p.health - damage)) self.world.gameobjects.remove(self) self.owner.isdone = True del(self) return else: self.age += 1
def getPath(self, position, pm): goal = self.goal + (self.distance + 2,) pm.findPath(position, goal) path = pm.path endPoint = path[len(path) - 1] f = lambda a, b: b + (a - b) * self.distance / util.dist(endPoint, self.goal) endX = round(f(endPoint[0], self.goal[0]), 3) endY = round(f(endPoint[1], self.goal[1]), 3) path.append((endX, endY)) dist = pm.getPathLength() return dist, path
def connect(self, ue): """ Called by ue when user connects @param ue UE connecting """ if ue not in self._ues and util.dist(ue, self) < self.radius: self._ues.append(ue) self._bbu.event(controller.UE_CONNECT, self, ue) return True elif ue in self._ues: # already connected, nothing to do return True else: return False
def nearby(): estimate = hulop.localize_image( request.files['image'], request.form['user'], request.form['map'] ) if estimate: loc = estimate['t'] results = [] radius = request.form['radius'] for h in database.query('select * from hotspots'): h_loc = (h['x'],h['y'],h['z']) if util.dist(loc[:2], h_loc[:2]) < radius: direction = util.clockwise(estimate['t'], estimate['R'], h_loc) results.append({'description': h['category'], 'direction': direction}) return json.dumps({'location':estimate, 'nearby':results}) else: return json.dumps({'error': 'could not localize'}), 400
def __init__(self, img, bimg, arr, rot_arr, rot_img, cursor_r, cursor_angle): w,h = img.size() self.img = img self.center_point = (w/2, h/2) self.bimg = bimg self.arr = arr self.rot_arr = rot_arr self.rot_img = rot_img self.cursor_r = cursor_r self.cursor_angle = cursor_angle rw, rh = self.rot_img.size() max_r = ceil(dist(0, 0, w/2, h/2)) cursor_y = rh - int(rh * cursor_r/max_r) cursor_x = int(float(rw) * self.cursor_angle / 360) self.rot_img.dl().circle((cursor_x, cursor_y), 3, color=Color.RED, filled=True)
def aStar(self) : """ runs the A* algorithm returns : bool (success) """ if self.pathEnd != None : # if starting point fulfills the goal condition return True for x0, y0 in self.lowestCell() : if self.isGoal((x0,y0)) : # the algorithm ends if the goal condition is reached self.pathEnd = (x0, y0) return True self.statusMat[x0][y0] = -1 for x1, y1 in self.neighbors(x0, y0) : newGScore = self.gScoreMat[x0][y0] + util.dist((x0,y0), (x1,y1)) if self.statusMat[x1][y1] == 1 or self.gScoreMat[x1][y1] > newGScore : self.gScoreMat[x1][y1] = newGScore self.fScoreMat[x1][y1] = newGScore + self.heuristicEstimate((x1,y1)) self.prevMat[x1][y1] = (x0,y0) self.addToOpenSet(x1,y1) return False