def KMeans(items, cluster_count, init_centers=[], radius=0, max_distance=0): cents = [] if not len(init_centers) > 0: currs = random.sample(items, cluster_count) clusters = [get_cluster(i, item.pt, []) for i, item in currs] else: currs = [c for c in init_centers] clusters = [get_cluster(i, c, []) for i, c in enumerate(init_centers)] while cents != currs: cents = currs for cluster in clusters: cluster['items'] = [] for item in items: cl = min(clusters, key=lambda x: distance(item.pt, x['center'])) if radius > 0: if distance(item.pt, cl['center']) < radius: cl['items'].append(item) else: cl['items'].append(item) currs = [] for cluster in clusters: if (max_distance > 0) and (len(cluster['items']) > 0): c = mass_center(cluster['items']) if distance(c, cluster['center']) < max_distance: currs.append(c) cluster['center'] = c continue currs.append(cluster['center']) return sort_clusters(clusters)
def meanRectDistance(rect: List, start_idx: int) -> np.ndarray: idxs = [(idx, idx - 4)[idx > 3] for idx in range(start_idx, len(rect) + start_idx)] return np.mean([ distance(rect[idxs[0]], rect[idxs[1]]), distance(rect[idxs[2]], rect[idxs[3]]) ])
def execute_next_turret(self): logging.info("Turret state {}".format(self.hookup_state)) logging.info("No of ammos: {}".format(self.ammo)) if self.hookup_state == Bot.RADAR: self.radarTurret() if self.state != Bot.CIRCLE: return if self.ammo == 0: logging.info("Run out of ammo") if self.hooked_objective == None and len(field.ammo_pickups) and self.state != Bot.AMMO_PICKUP: closest_ammo = min(field.ammo_pickups, key=lambda x: distance(self.X, self.Y, x[0], x[1])) logging.info("Found this ammo: {}".format(closest_ammo)) self.hooked_objective = closest_ammo self.state = Bot.AMMO_PICKUP elif self.hooked_objective != None and self.hooked_objective not in field.ammo_pickups: logging.info("Unexisting ammo, unhooking") self.hooked_objective = None self.unhook() if self.ammo > 0: logging.info("There are {} known enemies. My hooked object is {}".format(len(field.enemies), self.hooked_objective)) if len(field.enemies): logging.info("Looking for an enemy...") closest_enemy = min(field.enemies.keys(), key=lambda x: distance(self.X, self.Y, field.enemies[x][0], field.enemies[x][1])) x_enemy, y_enemy, last_time = field.enemies[closest_enemy] if distance(self.X, self.Y, x_enemy, y_enemy): logging.info("Hooked an enemy! {}".format(closest_enemy)) self.hooked_objective = closest_enemy self.hookup_state = Bot.HOOKED_ENEMY if self.hookup_state == Bot.HOOKED_ENEMY: if self.ammo == 0: self.unhook() else: if self.hooked_objective == None or self.hooked_objective not in field.enemies: self.unhook() else: x_enemy, y_enemy, last_time = field.enemies[self.hooked_objective] if distance(self.X, self.Y, x_enemy, y_enemy) > 80: self.unhook() else: self.rotateTurretTo(x_enemy, y_enemy) self.shoot() if self.hookup_state == Bot.HOOKED_SNITCH: if field.snitch: self.hooked_objective = field.snitch x_enemy, y_enemy = field.snitch self.rotateTurretTo(x_enemy, y_enemy) else: self.radarTurret()
def __evaluate_txs(self): # check for interferences between the current transmissions nodesTxs = [] txsToCheck = [] # indices of transmissions that must be checked (the # ones that are currently been successful) # gathering information to start the evaluation i = 0 for tid, tinfo, tsuccess in self.txs: src = tinfo[0] pos = self.nodes[src].position power = tinfo[2] nodesTxs.append([src, pos, power]) if tsuccess: txsToCheck.append(i) i += 1 # checking the transmissions that have not yet failed. for i in txsToCheck: if self.verbose: print("\t- Evaluating tx {}".format(self.txs[i][0])) tinfo = self.txs[i][1] src = tinfo[0] power = tinfo[2] dst = tinfo[1].dst # from msg spos = self.nodes[src].position dpos = self.nodes[dst].position # calculating SINR dist = tools.distance(spos, dpos) sinr = power / (dist ** self.channel.alpha) # calculating interference inter = 0 for isrc, ipos, ipower in nodesTxs: if isrc != src: dist = tools.distance(ipos, dpos) if dist == 0: dist = 0.0000001 inter += ipower / (dist ** self.channel.alpha) # calculating final SINR and checking for zero division (when there # is neither interference nor noise) if (inter + self.channel.noise) == 0: sinr = float("inf") else: sinr = sinr / (self.channel.noise + inter) # sinr = 10 * math.log10(sinr) # to dB if self.verbose: print("\tSINR = {0:.2f} ({1:d}->{2:d})".format(sinr, src, dst)) # checking if the data can be decoded if sinr >= self.nodes[dst].radio.minSIR: self.txs[i][2] = True else: self.txs[i][2] = False return None
def errorfun(alpha): "Error function to minimize." s_ = compute_projection_on_picture(photographer, summits, alpha[0]) # If a summit doesn't have any projection (picture // with direction # of the summit), return max error. if None in s_: return 999999 # Compute successive normalized distance between projections left, right = extrems(photographer, s_) deltascur = [distance(left, p) / distance(left, right) for p in s_] # Compute the error: normalized sum of square of diff of the normalized distance error = sum((cur - ref)**2 for cur, ref in zip(deltascur, deltasref)) error /= len(deltasref) return error
def optimize_picture(photographer, summits, projections): """ Optimize the position of the picture for a given position of the photographer. Input: - the position of the photographer (p) - the positions of at least three summits on the map (as viewed from left to right) - the projections of the summits on the picture (from left to right) Output: - error: the error on the alignment of the summits after optimization - alpha/rho: two parameters that define the position of the picture - projections: the projections of the summits on the picture """ if photographer is None: raise RuntimeError("photographer cannot be None") # Compute successive normalized distance between real projections deltasref = [(p - projections[0]) / (projections[-1] - projections[0]) for p in projections] def errorfun(alpha): "Error function to minimize." s_ = compute_projection_on_picture(photographer, summits, alpha[0]) # If a summit doesn't have any projection (picture // with direction # of the summit), return max error. if None in s_: return 999999 # Compute successive normalized distance between projections left, right = extrems(photographer, s_) deltascur = [distance(left, p) / distance(left, right) for p in s_] # Compute the error: normalized sum of square of diff of the normalized distance error = sum((cur - ref)**2 for cur, ref in zip(deltascur, deltasref)) error /= len(deltasref) return error # find the values of alpha that minimise the distances between expected # and actual projections of the summits on the lens. res = minimize(errorfun, (0.5, ), method='SLSQP', bounds=((0, 1), )) alpha = res.x[0] error = res.fun # move picture away/closer to have respect scale s_ = compute_projection_on_picture(photographer, summits, alpha) if distance(s_[1], s_[0]) == 0: rho = None s__ = [photographer] * 5 else: rho = abs(projections[1] - projections[0]) / distance(s_[1], s_[0]) s__ = compute_projection_on_picture(photographer, summits, alpha, rho) return PicturePosition(projections=s__, alpha=alpha, rho=rho, error=error)
def select_lgs(data=None, lg_model=None, lgf=False, dist=6.0e+3): """ Pass a local group model and select lgs in a dataframe accordingly Returns a new dataframe with the selected halos """ x_col = ['Xc_LG', 'Yc_LG', 'Zc_LG'] m_min = lg_model.m_min m_max = lg_model.m_max r_min = lg_model.r_min r_max = lg_model.r_max m_ratio = lg_model.mratio_max vrad_max = lg_model.vrad_max data['ratio'] = data['M_M31'] / data['M_MW'] select = data[data['ratio'] < m_ratio] select = select[select['Vrad'] < vrad_max] select = select[select['R'] > r_min] select = select[select['R'] < r_max] select = select[select['M_M31'] < m_max] select = select[select['M_MW'] > m_min] if lgf: c = [5.0e+4 for i in range(0, 3)] c = np.array(c) select['D'] = select[x_col].apply(lambda x: t.distance(x, c), axis=1) select = select[select['D'] < dist] return select
def mapper(self, _, line): """ The mapper loads a track and yields its ramp factor """ t = track.load_track(line) segments = t['segments'] duration = t['duration'] xdata = [] ydata = [] for i in xrange(len(segments)): seg = segments[i] sloudness = seg['loudness_max'] sstart = seg['start'] + seg['loudness_max_time'] xdata.append( sstart ) ydata.append( sloudness ) if duration > 20: idata = tools.interpolate(xdata, ydata, int(duration) * 10) smooth = tools.smooth(idata, 20) samp = tools.sample(smooth, self.SIZE) ndata = tools.rnormalize(samp, -60, 0) if self.DUMP: for i, (x, y) in enumerate(zip(self.MATCH, ndata)): print i, x, y if self.VECTOR: yield (t['artist_name'], t['title'], t['track_id']), ndata else: distance = tools.distance(self.MATCH, ndata) yield (t['artist_name'], t['title'], t['track_id']), distance
def mapper(self, _, line): """ The mapper loads a track and yields its ramp factor """ t = track.load_track(line) segments = t['segments'] duration = t['duration'] xdata = [] ydata = [] for i in xrange(len(segments)): seg = segments[i] sloudness = seg['loudness_max'] sstart = seg['start'] + seg['loudness_max_time'] xdata.append(sstart) ydata.append(sloudness) if duration > 20: idata = tools.interpolate(xdata, ydata, int(duration) * 10) smooth = tools.smooth(idata, 20) samp = tools.sample(smooth, self.SIZE) ndata = tools.rnormalize(samp, -60, 0) if self.DUMP: for i, (x, y) in enumerate(zip(self.MATCH, ndata)): print i, x, y if self.VECTOR: yield (t['artist_name'], t['title'], t['track_id']), ndata else: distance = tools.distance(self.MATCH, ndata) yield (t['artist_name'], t['title'], t['track_id']), distance
def process(self): #Take into account segment for i in xrange(1, len(self.datas)): denivele = float(self.datas[i]["Altitude (m)"]) - float(self.datas[i-1]["Altitude (m)"]) if denivele > 0: self.positive_denivele += denivele else: self.negative_denivele -= denivele self.datas[i]["den"] = denivele d = distance(self.datas[i]["coordo"], self.datas[i - 1]["coordo"]) self.distance_total += d self.datas[i]["distance_total"] = self.distance_total self.datas[i]["distance_previous"] = d dur = duration(self.datas[i]["time"], self.datas[i - 1]["time"]) self.total_time += dur self.datas[i]["duration_total"] = self.total_time self.datas[i]["duration_previous"] = dur self.datas[i]['speed'] = self.datas[i]["duration_previous"] \ and self.datas[i]["distance_previous"] / self.datas[i]["duration_previous"] \ or 0 self.datas[i]['move'] = self.datas[i]['speed'] and True or False if self.datas[i]['speed'] < 0.19: #print "not moving", i self.not_moving_time += dur
def check_markers_consistency(self): index = tls.distance([self.Index7x, self.Index7y, self.Index7z], [self.Index8x, self.Index8y, self.Index8z]) thumb = tls.distance([self.Thumb9x, self.Thumb9y, self.Thumb9z], [self.Thumb10x, self.Thumb10y, self.Thumb10z]) wrist = tls.distance([self.Wrist11x, self.Wrist11y, self.Wrist11z], [self.Wrist12x, self.Wrist12y, self.Wrist12z]) eyes = tls.distance( [self.LEyeInterX, self.LEyeInterY, self.LEyeInterZ], [self.REyeInterX, self.REyeInterY, self.REyeInterZ]) return index, thumb, wrist, eyes
def _sgd_step_vsp(vsp_pairs: dict, enriched_vectors: dict, config: SettingConfig, gradient_updates: dict, update_count: dict) -> (dict, dict): for (w0, w1) in vsp_pairs: # Extra check for reduced vocabulary: if w0 not in config.vocabulary or w1 not in config.vocabulary: break original_distance = vsp_pairs[(w0, w1)] new_distance = tools.distance(enriched_vectors[w0], enriched_vectors[w1]) if original_distance <= new_distance: gradient = tools.partial_gradient(enriched_vectors[w0], enriched_vectors[w1]) gradient *= config.hyper_k3 if w0 in gradient_updates: gradient_updates[w0] -= gradient update_count[w0] += 1 else: gradient_updates[w0] = -gradient update_count[w0] = 1 return gradient_updates, update_count
def _sgd_step_ant(antonym_pairs: set, enriched_vectors: dict, config: SettingConfig, gradient_updates: dict, update_count: dict) -> (dict, dict): # For each antonym pair for (w0, w1) in antonym_pairs: # Extra check for reduced vocabulary: if w0 not in config.vocabulary or w1 not in config.vocabulary: break # Compute distance in new vector space dist = tools.distance(enriched_vectors[w0], enriched_vectors[w1]) if dist < config.delta: # Compute the partial gradient gradient = tools.partial_gradient(enriched_vectors[w0], enriched_vectors[w1]) # Weight it by K1 gradient *= config.hyper_k1 if w0 in gradient_updates: gradient_updates[w0] += gradient update_count[w0] += 1 else: gradient_updates[w0] = gradient update_count[w0] = 1 return gradient_updates, update_count
def detect_line_count(self) -> Dict: lines = {} zones_cnt = len(self.rects) current_line = 1 idx = 0 lines[current_line] = [{ 'idx': idx, 'h': distance(self.rects[idx][3], self.rects[idx][0]), 'y': self.rects[idx][0][1], 'x': self.rects[idx][0][0], 'matrix': linearLineMatrix( self.rects[idx][0], apply_new_point(self.rects[idx][0], self.dx, self.dy)) }] if zones_cnt > 1: for idx in range(1, len(self.rects)): rect = self.rects[idx - 1] rect_next = self.rects[idx] h = distance(rect[3], rect[0]) y = rect[0][1] x = rect[0][0] dy = h * self.line_dispersion matrix = linearLineMatrix( rect[0], apply_new_point(rect[0], self.dx, self.dy)) y_next = getYByMatrix(matrix, rect_next[0][0]) if y_next - dy < rect_next[0][1] < y_next + dy: pass else: current_line = current_line + 1 if current_line not in lines.keys(): lines[current_line] = [] lines[current_line].append({ 'idx': idx, 'h': h, 'y': y, 'x': x, 'matrix': matrix }) return lines
def get_best_goal(self): """ :type goals: list of Goal """ available_goals = [ g for g in self.goals if g.is_available() ] if self.last_goal in available_goals: available_goals.remove(self.last_goal) logger.log('available goals : {}'.format([g.identifier for g in available_goals])) if not available_goals : return None for goal in available_goals: pose = position.Pose(goal.x, goal.y, virtual=True) logger.log("Evaluate goal {}".format(goal.identifier)) if GOAL_EVALUATION_USES_PATHFINDING: goal.navigation_cost = self.event_loop.map.evaluate(self.event_loop.robot.pose, pose) else: goal.navigation_cost = tools.distance(self.event_loop.robot.pose.x, self.event_loop.robot.pose.y, pose.x, pose.y) if goal.navigation_cost is None: goal.navigation_cost = 999999.0 goal.score = goal.penality goal.penality = 0.0 logger.log("Scoring distance") for order, goal in enumerate(sorted(available_goals, key = lambda x : x.navigation_cost, reverse = True)): goal.score += (order + 1) * 2 logger.log("Goal {} nav cost = {}, score = {}".format(goal.identifier, goal.navigation_cost, goal.score)) logger.log("Adding weights") for goal in available_goals: goal.score += goal.weight logger.log("Goal {} score = {}".format(goal.identifier, goal.score)) logger.log("Scoring tentatives") order = 0 last_value = None for goal in sorted(available_goals, key = lambda x : x.trial_count, reverse = True): if last_value != goal.trial_count: last_value = goal.trial_count order += 1 goal.score += order logger.log("Goal {} score = {}".format(goal.identifier, goal.score)) logger.log("available_goals by score : {}".format(["{}:{}".format(g.identifier, g.score) for g in available_goals ] )) best_goal = max(available_goals, key = lambda g : g.score) logger.log("Best goal is {} with score {}".format(best_goal.identifier, best_goal.score)) self.last_goal = best_goal return best_goal
def makeRectVariants(propably_points: List, quality_profile: List = None) -> List: """ TODO: describe function """ if quality_profile is None: quality_profile = [3, 1, 0, 0] steps = quality_profile[0] steps_plus = quality_profile[1] steps_minus = quality_profile[2] step = 1 if len(quality_profile) > 3: step_adaptive = quality_profile[3] > 0 else: step_adaptive = False distanses = findDistances(propably_points) point_centre_left = [ propably_points[0][0] + (propably_points[1][0] - propably_points[0][0]) / 2, propably_points[0][1] + (propably_points[1][1] - propably_points[0][1]) / 2 ] if distanses[3]["matrix"][1] == 0: return [propably_points] point_bottom_left = [ point_centre_left[0], getYByMatrix(distanses[3]["matrix"], point_centre_left[0]) ] dx = propably_points[0][0] - point_bottom_left[0] dy = propably_points[0][1] - point_bottom_left[1] dx_step = dx / steps dy_step = dy / steps if step_adaptive: d_max = distance(point_centre_left, propably_points[0]) dd = math.sqrt(dx**2 + dy**2) steps_all = int(d_max / dd) step = int((steps_all * 2) / steps) if step < 1: step = 1 steps_minus = steps_all + steps_minus * step steps_plus = steps_all + steps_plus * step points_arr = [] for i in range(-steps_minus, steps + steps_plus + 1, step): points_arr.append( addPointOffsets(propably_points, i * dx_step, i * dy_step)) return points_arr
def make_mline_boxes_options(mline_boxes: List) -> Tuple[int, int, List[Dict]]: options = [] w_max = 0 w_max_idx = -1 for mline_idx, mline_box in enumerate(mline_boxes): w = distance(mline_box[0], mline_box[1]) if w_max < w: w_max = w w_max_idx = mline_idx angle = (fline(mline_box[0], mline_box[1]))[2] options.append({'w': w, 'angle': angle}) return w_max, w_max_idx, options
def __handle_send_event(self, event): # Check if some transmission is successful. In case of success, events # for message receptions are created. msg = event[2] isAcoustic = msg.flags & MsgFlags.ACOUSTIC destinations = [] if msg.dst == BROADCAST_ADDR: assert isAcoustic, "Optical broadcasts are not allowed" destinations = self.aneighbors[msg.src] else: destinations = [msg.dst] if isAcoustic: self.atxs += 1 else: self.otxs += 1 for dst in destinations: srcPos = self.nodesRef[msg.src].position dstPos = self.nodesRef[dst].position dist = tools.distance(srcPos, dstPos) if self.verbose: print("Message " + str(msg.src) + "->" + str(dst), end=" ") if isAcoustic: success = self.achannel.use(AM.frequency, AM.txPower, dist, \ len(msg)) if success: self.asucceedRxs += 1 propTime = self.achannel.get_propagation_time(dist) recvTime = self.clock.read() + propTime self.evMngr.insert(EG.create_recv_event(recvTime, dst, msg)) if self.verbose: print("was successfull: will arrive " + str(recvTime)) else: if self.verbose: print("failed") self.afailedRxs += 1 else: success = self.ochannel.use(OM.txPower, dist, dist, self.beta, \ len(msg)) if success: self.osucceedRxs += 1 propTime = self.ochannel.get_propagation_time(dist) recvTime = self.clock.read() + propTime self.evMngr.insert(EG.create_recv_event(recvTime, dst, msg)) if self.verbose: print("was successfull: will arrive " + str(recvTime)) else: if self.verbose: print("failed") self.ofailedRxs += 1
def normalizeRect(rect: List) -> np.ndarray or List: """ TODO: describe function """ rect = fixClockwise2(rect) minXIdx = findMinXIdx(rect) rect = reshapePoints(rect, minXIdx) coef_ccw = fline(rect[0], rect[3]) angle_ccw = round(coef_ccw[2], 2) d_bottom = distance(rect[0], rect[3]) d_left = distance(rect[0], rect[1]) k = d_bottom / d_left if round(rect[0][0], 4) == round(rect[1][0], 4): pass else: if d_bottom < d_left: k = d_left / d_bottom if k > 1.5 or angle_ccw < 0 or angle_ccw > 45: rect = reshapePoints(rect, 3) else: if k < 1.5 and (angle_ccw < 0 or angle_ccw > 45): rect = reshapePoints(rect, 3) return rect
def move_to(self, location, verbose=True): X = location.x Y = location.y self.location_obj = location dist = tools.distance(self.x, self.y, X, Y) self.distance_travelled += dist self.index_history.append(location.index) self.x = X self.y = Y # if verbose: # print("NOTE:Moved {} drone {} blocks to ({},{})".format(self.kind, dist, self.x, self.y)) self.take_action(location, verbose)
def get_score_line(cand,sumof,ovv,ovv_tag): node = tools.get_node(cand,tag=ovv_tag) freq = freq_score(int(node['freq'])) if node else 0. line = [ #cand, sumof, # weight tools.lcsr(ovv,cand), # lcsr tools.distance(ovv,cand), # distance tools.common_letter_score(ovv,cand), # shared letter 0, # 7 : is_in_slang freq, ] for ind in range(0,len(line)): line[ind] = round(line[ind],8) return line
def detectProbablyMultilineZones(self, image, craft_params=None, debug=False): """ TODO: describe method """ if craft_params is None: craft_params = {} low_text = craft_params.get('low_text', self.low_text) link_threshold = craft_params.get('link_threshold', self.link_threshold) text_threshold = craft_params.get('text_threshold', self.text_threshold) canvas_size = craft_params.get('canvas_size', self.canvas_size) mag_ratio = craft_params.get('mag_ratio', self.mag_ratio) t = time.time() bboxes, polys, score_text = test_net(self.net, image, text_threshold, link_threshold, low_text, self.is_cuda, self.is_poly, canvas_size, self.refine_net, mag_ratio) if debug: print("elapsed time : {}s".format(time.time() - t)) dimensions = [] for poly in bboxes: dimensions.append({ 'dx': distance(poly[0], poly[1]), 'dy': distance(poly[1], poly[2]) }) np_bboxes_idx, garbage_bboxes_idx = split_boxes(bboxes, dimensions) return [bboxes[i] for i in np_bboxes_idx]
def create_path(self): cost, path = self.event_loop.map.route(self.robot.pose, self.destination) if len(path) == 0 or self.offset == 0: return path else: p = self.robot.pose if len(path) == 1 else path[-2] a = tools.angle_between(p.x, p.y, self.destination.x, self.destination.y) dist = tools.distance(p.x, p.y, self.destination.x, self.destination.y) dist += self.offset last_pose = path[-1] last_pose.x = p.x + math.cos(a) * dist last_pose.y = p.y + math.sin(a) * dist return path
def scene_changed(self): robot_a = self.field_view_controller.ui.game_controller.robot_a.robot_layer.robot robot_b = self.field_view_controller.ui.game_controller.robot_b.robot_layer.robot for elt in self.fires: if not elt in robot_a.carried_elements and not elt in robot_b.carried_elements: robot = None if elt.collidesWithItem(robot_a.robot_item): robot = robot_a elif elt.collidesWithItem(robot_b.robot_item): robot = robot_b if robot != None: angle = (robot.item.rotation() / 180.0 * math.pi) % (math.pi * 2.0) ex = elt.pos().x() - robot.item.x() ey = elt.pos().y() - robot.item.y() elt_angle = math.atan2(ey, ex) % (math.pi * 2.0) ref = abs(angle - elt_angle) if ref < math.pi / 4.0 or ref >= 7.0 * math.pi / 4.0: sign = 1.0 elif ref >= math.pi / 4.0 and ref < 3.0 * math.pi / 4.0: sign = -1.0 angle += math.pi / 2.0 elif ref >= 3.0 * math.pi / 4.0 and ref < 5.0 * math.pi / 4.0: sign = -1.0 else: sign = 1.0 angle -= math.pi / 2.0 dist = 20 dx = sign * math.cos(angle) * dist dy = sign * math.sin(angle) * dist elt.setPos(elt.pos().x() + dx, elt.pos().y() + dy) for fire in self.fires: robot_a.hits_fire(fire) robot_b.hits_fire(fire) if self.main_bar.opponent_detection.isChecked(): if robot_a.item and robot_b.item : distance = tools.distance(robot_a.item.x(), robot_a.item.y(), robot_b.item.x(), robot_b.item.y()) if distance < TURRET_SHORT_DISTANCE_DETECTION_RANGE * 1000.0: self.send_turret_detect(robot_a, robot_b, 0) self.send_turret_detect(robot_b, robot_a, 0) elif distance < TURRET_LONG_DISTANCE_DETECTION_RANGE * 1000.0: self.send_turret_detect(robot_a, robot_b, 1) self.send_turret_detect(robot_b, robot_a, 1)
def get_score_line(cand,sumof,oov,oov_tag): node = tools.get_node(cand,tag=oov_tag) #node_wo_tag = tools.get_node(cand) freq = freq_score(int(node['freq'])) if node else 0. #freq_wo_tag = freq_score(int(node_wo_tag[0]['freq'])) if node_wo_tag else 0. #degree = tools.get_degree_score(cand,oov_tag) line = [ #cand, sumof, # weight tools.lcsr(oov,cand), # lcsr tools.distance(oov,cand), # distance 0, # degree, #freq_wo_tag, #tools.common_letter_score(oov,cand), # shared letter 0, # 7 : is_in_slang freq, ] for ind in range(0,len(line)): line[ind] = round(line[ind],8) return line
def get_next_goal(self): candidates = self.get_candidate_goals() for goal in candidates: goal.before_evaluation() for goal in candidates: pose = position.Pose(goal.x, goal.y, virtual=True) logger.log("Evaluate goal {}".format(goal.uid)) if GOAL_EVALUATION_USES_PATHFINDING: goal.navigation_cost = self.event_loop.map.evaluate( self.event_loop.robot.pose, pose) else: goal.navigation_cost = tools.distance( self.event_loop.robot.pose.x, self.event_loop.robot.pose.y, pose.x, pose.y) # Remove unreachable goals candidates = [ goal for goal in candidates if goal.navigation_cost is not None ] if len(candidates) == 0: return None if len(candidates) == 1: return candidates[0] candidates.sort(key=lambda goal: goal.navigation_cost) nearest_cost = candidates[0].navigation_cost farest_cost = candidates[-1].navigation_cost total_range = farest_cost - nearest_cost logger.log("Nearest cost: {} Farest cost: {} Range: {}".format( nearest_cost, farest_cost, total_range)) for goal in candidates: current = goal.navigation_cost - nearest_cost k = (total_range - current) / total_range goal.score = goal.weight * (1.0 / 3.0 + k * 2.0 / 3.0) logger.log("Goal '{}' Navigation cost: {} Score: {}".format( goal.identifier, goal.navigation_cost, goal.score)) return max(candidates, key=lambda goal: goal.score) if not funny_action_goals: return best_goal
def hop(self,tile): last=True self.parent.active=None self.parent.state="anim" self.tile.block = Air() self.parent.highlighted = [] d=distance(self.tile.pos,tile.pos) m=d/150 t=.5+.1*m i=0 z=None Animation(center_x=tile.center_x,center_y=tile.center_y+tile.blockheight,duration=t).start(self) a=Animation(ay=50+50*m,duration=t*.5,t="out_quad") b=Animation(ay=0,duration=t*.5,t="in_quad") t = "self" if not isinstance(tile.block,Air): l=lambda a: [self.hit(tile.block,self.damage), self.hop(random.choice(tile.adjacenttiles)) ] b.on_complete=l last=False z=-sum(tile.block.gpos) i=1 a.on_complete=lambda a:self.zefresh(z=z,i=i,t=t) f=a+b def dolast(_): self.parent.state="ready" if last: self.tile=tile self.tile.block=self f.on_complete=dolast f.start(self)
def set_distance_matrix(self): """ Calculate the distance matrix of between all depots and customers with current sorting. (Default: ids are increasing) """ # 1) initialize variables for solution nodes = self.depots.copy() nodes.update(self.customers) m = self.nr_depots + self.nr_customers # get number dimensionality distance_matrix = np.zeros((m, m)) # 2) calculate the distance matrix for all values for n_id1 in nodes: for n_id2 in nodes: distance_matrix[n_id1, n_id2] = distance(nodes[n_id1], nodes[n_id2]) self.distance_matrix = distance_matrix
def get_simple_next_goal(self): candidates = self.get_candidate_goals() if len(candidates) == 0: return None for goal in candidates: goal.before_evaluation() candidates.sort(key=lambda goal: goal.weight) logger.log('Candidate goals : {}'.format( ["{}({})".format(goal.uid, goal.weight) for goal in candidates])) best_weight = candidates[0].weight best_candidates = [] for goal in candidates: if goal.weight == best_weight: best_candidates.append(goal) else: break if len(best_candidates) == 1: return best_candidates[0] else: best_goal = None for goal in best_candidates: pose = position.Pose(goal.x, goal.y, virtual=True) logger.log("Evaluate goal {}".format(goal.uid)) if GoalManager.GOAL_EVALUATION_USES_PATHFINDING: goal.navigation_cost = self.event_loop.map.evaluate( self.event_loop.robot.pose, pose) else: goal.navigation_cost = tools.distance( self.event_loop.robot.pose.x, self.event_loop.robot.pose.y, pose.x, pose.y) if goal.navigation_cost and ( best_goal is None or best_goal.navigation_cost > goal.navigation_cost): best_goal = goal return best_goal
def _sgd_step_syn(synonym_pairs: set, enriched_vectors: dict, config: SettingConfig, gradient_updates: dict, update_count: dict) -> (dict, dict): for (w0, w1) in synonym_pairs: # Extra check for reduced vocabulary: if w0 not in config.vocabulary or w1 not in config.vocabulary: break dist = tools.distance(enriched_vectors[w0], enriched_vectors[w1]) if dist > config.gamma: gradient = tools.partial_gradient(enriched_vectors[w0], enriched_vectors[w1]) gradient *= config.hyper_k2 if w1 in gradient_updates: gradient_updates[w1] += gradient update_count[w1] += 1 else: gradient_updates[w1] = gradient update_count[w1] = 1 return gradient_updates, update_count
def __update_nodes_info(self): if self.verbose: print("Updating nodes information") self.numNodes = len(self.nodesRef) for addr1 in self.nodesRef.keys(): # updating tdma info self.nodesRef[addr1].update_time_slot_size(self.tdmaSlotSize) self.nodesRef[addr1].update_num_time_slots(self.numNodes) # updating neighborhood references aneighbors = [] oneighbors = [] for addr2 in self.nodesRef.keys(): if addr1 is not addr2: node1 = self.nodesRef[addr1] node2 = self.nodesRef[addr2] distance = tools.distance(node1.position, node2.position) if distance <= AM.maxRange: aneighbors.append(addr2) if distance <= OM.maxRange: oneighbors.append(addr2) self.aneighbors[addr1] = aneighbors self.oneighbors[addr1] = oneighbors
def extract_vweb(file_name=None, center=None, radius=None): ''' Assuming vweb files are all of .csv type, we want to extract (and save) a subset of the original file around a specified point in space ''' vweb = pd.read_csv(file_name) new_key = 'radius' print(vweb.head()) # Select these three columns cols = ['x', 'y', 'z'] fac = t.check_units(data=vweb, cols=cols) # Check that the units are consistent vweb[new_key] = vweb[cols].T.apply(lambda x: t.distance(x, center)) #print(vweb.head()) select_vweb = vweb[vweb[new_key] < radius] return select_vweb
def execute_next(self): message = self.readMessage() field.update(message, self.index) logging.debug("{} I am in state {}".format(self.name, self.state)) logging.info("{} Kill points: {}".format(self.name, self.kill_counter)) if self.state == Bot.CIRCLE: self.goCircle(0, -70, 30) if self.state == Bot.AMMO_PICKUP: if self.hooked_objective and type(self.hooked_objective) == type( tuple()): self.moveTo(self.hooked_objective[0], self.hooked_objective[1]) else: self.state = Bot.CIRCLE if self.kill_counter > 0: # TODO: change this self.state = Bot.BANKING if self.state == Bot.SEEK_SNITCH: self.hookup_state = Bot.HOOKED_SNITCH if field.snitch: self.moveTo(field.snitch[0], field.snitch[1]) if self.state == Bot.BANKING: goal_posts = [(0, 100), (0, -100)] closest_goal_post = min( goal_posts, key=lambda post: distance(self.X, self.Y, post[0], post[1])) self.moveTo(closest_goal_post[0], closest_goal_post[1]) if self.state == Bot.SNITCH_KILL and self.hooked_objective: self.moveTo(self.hooked_objective[0], self.hooked_objective[1], -20) self.i += 1
def get_next_goal(self): candidates = self.get_candidate_goals() for goal in candidates : goal.before_evaluation() for goal in candidates: pose = position.Pose(goal.x, goal.y, virtual = True) logger.log("Evaluate goal {}".format(goal.uid)) if GOAL_EVALUATION_USES_PATHFINDING: goal.navigation_cost = self.event_loop.map.evaluate(self.event_loop.robot.pose, pose) else: goal.navigation_cost = tools.distance(self.event_loop.robot.pose.x, self.event_loop.robot.pose.y, pose.x, pose.y) # Remove unreachable goals candidates = [ goal for goal in candidates if goal.navigation_cost is not None ] if len(candidates) == 0: return None if len(candidates) == 1: return candidates[0] candidates.sort(key = lambda goal : goal.navigation_cost) nearest_cost = candidates[0].navigation_cost farest_cost = candidates[-1].navigation_cost total_range = farest_cost - nearest_cost logger.log("Nearest cost: {} Farest cost: {} Range: {}".format(nearest_cost, farest_cost, total_range)) for goal in candidates: current = goal.navigation_cost - nearest_cost k = (total_range - current) / total_range goal.score = goal.weight * (1.0 / 3.0 + k * 2.0 / 3.0) logger.log("Goal '{}' Navigation cost: {} Score: {}".format(goal.identifier, goal.navigation_cost, goal.score)) return max(candidates, key = lambda goal : goal.score) if not funny_action_goals : return best_goal
def adjacenttiles(self): return list( filter( lambda a: distance(a.gpos, self.gpos) <= 1.5 and a is not self, self.parent.tiles))
def run(self): i = 0 while True: if i % 5 == 0: self.sendMessage(ServerMessageTypes.MOVEFORWARDDISTANCE, {'Amount': 5}) message = self.readMessage() logging.debug(message) field.update(message) if abs(self.last_X - self.X) > 1 and abs( self.last_Y - self.Y) > 1 and self.last_X != 0. and self.last_Y != 0.: print("{} {} {}".format(self.name, self.last_X, self.X)) break if i % 20 == 0: self.last_X = self.X self.last_Y = self.Y i += 1 self.sendMessage(ServerMessageTypes.STOPALL) while self.is_running: message = self.readMessage() field.update(message) logging.info(message) turret = 0 self.sendMessage(ServerMessageTypes.TOGGLETURRETRIGHT, {'Amount': turret}) turret = (turret + 60) % 360 self.last_turret_update = time.time() if self.start_rotating: new_degree = rotate_head(self.X, self.Y, 0., 0.) logging.info( "{} Getting close to the circle to degree {} ".format( self.name, new_degree)) self.rotateByDeg((-new_degree + 360 % 360), absolute=False) self.sendMessage(ServerMessageTypes.TURNTOHEADING, {'Amount': (-new_degree + 360) % 360}) self.sendMessage(ServerMessageTypes.TOGGLEFORWARD) self.start_rotating = False self.is_rotating = True if self.is_rotating: if self.X**2 + self.Y**2 <= 25**2.: self.sendMessage(ServerMessageTypes.STOPMOVE) self.rotateByDeg(90) time.sleep(1.3) self.is_rotating = False self.keep_rotating = True self.toggleForward() if self.keep_rotating: self.rotateByDeg(-10) if len(field.enemies) and self.ammo: self.hooked = random.choice(list(field.enemies.keys())) if self.hooked in field.enemies: self.stopRotationStrategy() x_enemy, y_enemy = field.enemies[self.hooked] new_degree = rotate_head(self.X, self.Y, x_enemy, y_enemy) self.sendMessage(ServerMessageTypes.TURNTURRETTOHEADING, {'Amount': (-new_degree + 360) % 360}) self.stopMoving() self.keep_rotating = False dist = distance(self.X, self.Y, x_enemy, y_enemy) dist = min(dist - 10, 0) self.moveForward(dist) if self.ammo > 0: self.shoot() # # self.toggleForward() #else: # self.hooked == False # self.start_rotating = True logging.info("My ammo {}".format(self.ammo)) if self.ammo == 0: if not self.hooked or self.hooked not in field.pickup: self.hooked = False ammo_pickups = list( filter(lambda x: x[0] == 'Ammo', field.pickup)) if len(ammo_pickups) > 0: self.stopRotationStrategy() self.hooked = min(ammo_pickups, key=lambda x: (x[1] - self.X)**2 + (x[2] - self.Y)**2) logging.info("Found available ammo: {} {}".format( self.hooked[1], self.hooked[2])) #self.rotateByDeg(hooked_deg) self.stopMoving() self.toggleForward() else: hooked_deg = rotate_head(self.X, self.Y, self.hooked[1], self.hooked[2]) self.rotateByDeg((-hooked_deg + 360) % 360, absolute=True)
############################# # Motif VS Helix Distance ############################# calculator = RMSDCalculator( calculatorType="QCP_OMP_CALCULATOR", fittingCoordsets=selections["motif_all"].getCoordsets(), calculationCoordsets=selections["motif_backbone"].getCoordsets(), ) motif_rmsd = calculator.oneVsTheOthers(conformation_number=0, get_superposed_coordinates=False) residue_distances = [] for conf in selections["arg131_leu272"].getCoordsets(): arg131 = conf[0] leu272 = conf[1] residue_distances.append(distance(arg131, leu272)) exp_motif_rmsd = [0] + list(motif_rmsd) matplotlib.pyplot.scatter(residue_distances, exp_motif_rmsd) matplotlib.pyplot.savefig(os.path.join("plots", "motif_vs_helix_dist.svg")) matplotlib.pyplot.close() ########################################### # Backbone of ser 207 rmsd Vs ser to ligand distance ########################################### calculator = RMSDCalculator( calculatorType="QCP_OMP_CALCULATOR", fittingCoordsets=selections["backbone"].getCoordsets(), calculationCoordsets=selections["ser207"].getCoordsets(), )
for order in ordersList: totalWeigth+=int(products[int(order)]) orders.append((totalWeigth,position,ordersList,value)) #utils(mapSize,drones,nrTurns,maxPayLoad,nrOfWarehouses,warehouses,nrOfOrders,orders) orders.sort(key=lambda tup: tup[0]) #dronePacking([[x] for x in range(n)]) print(orders); droneBusy = [] for i in range(int(drones) - 1): droneBusy.append((i, 0, 0)) with open('output.txt', 'w') as o: while orders: order = orders.pop(0) for p in order[2]: o.write(load(droneBusy[0][0], 0, 1, p)) for p in order[2]: o.write(deliver(droneBusy[0][0], order[3], 1, p)) distHome = tools.distance(0,0, order[1][0], order[1][1]) droneBusy[0][1] = distHome + 2*len(order[2]) droneBusy[0][2] = distHome droneBusy.sort(key=lambda tup: tup[1]) def dronePacking(checkList): if(checkList): print("hej") def totalWeigth(listOfHouses): print("H")
def __sub__(self, other): return tools.distance(self.x, self.y, other.x, other.y)