def is_regular_three(x, y): ''' Returns true if x, y are behind the regular (non-corner) 3-point line. ''' loc = Location(x, y, 0.0) return (min(get_distance(loc, HOOP1), get_distance(loc, HOOP2)) >= 23.75)
def test(): graph = { 'A': { 'B': 1, 'C': 2 }, 'B': { 'C': 1, 'D': 2, }, 'C': { 'D': 5 }, 'D': { 'C': 1 }, 'E': { 'F': 1 }, 'F': { 'C': 1 } } dist = 32767 ## min_path = [] for path in find_all_paths(graph, 'A', 'D'): if dist > utils.get_distance(graph, path): dist = utils.get_distance(graph, path) min_path = path print(dist) print(min_path)
def mutate(self, reference=None): # Select mutation operator. rand_mutation_probability = random.uniform(0, 1) if rand_mutation_probability >= MUTOPPROB: mutation = 1 else: mutation = 2 condition = True counter_mutations = 0 while condition: counter_mutations += 1 mutant_vector = mutation_manager.mutate(self.digit.xml_desc, mutation, counter_mutations / 20) mutant_xml_desc = vectorization_tools.create_svg_xml(mutant_vector) rasterized_digit = rasterization_tools.rasterize_in_memory( mutant_xml_desc) distance_inputs = get_distance(self.digit.purified, rasterized_digit) if distance_inputs != 0: if reference is not None: distance_inputs = get_distance(reference.purified, rasterized_digit) if distance_inputs != 0: condition = False else: condition = False self.digit.xml_desc = mutant_xml_desc self.digit.purified = rasterized_digit return distance_inputs
def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) start_sumo("cfg/freeway.sumo.cfg", False) plexe = Plexe() traci.addStepListener(plexe) step = 0 state = GOING_TO_POSITION while running(demo_mode, step, 6000): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 6000: start_sumo("cfg/freeway.sumo.cfg", True) step = 0 state = GOING_TO_POSITION random.seed(1) traci.simulationStep() if step == 0: # create vehicles and track the joiner topology = add_vehicles(plexe, N_VEHICLES, real_engine) traci.gui.trackVehicle("View #0", JOINER) traci.gui.setZoom("View #0", 20000) if step % 10 == 1: # simulate vehicle communication every 100 ms communicate(plexe, topology) if step == 100: # at 1 second, let the joiner get closer to the platoon topology = get_in_position(plexe, JOINER, FRONT_JOIN, topology) if state == GOING_TO_POSITION and step > 0: # when the distance of the joiner is small enough, let the others # open a gap to let the joiner enter the platoon if get_distance(plexe, JOINER, FRONT_JOIN) < JOIN_DISTANCE + 1: state = OPENING_GAP topology = open_gap(plexe, BEHIND_JOIN, JOINER, topology, N_VEHICLES) if state == OPENING_GAP: # when the gap is large enough, complete the maneuver if get_distance(plexe, BEHIND_JOIN, FRONT_JOIN) > \ 2 * JOIN_DISTANCE + 2: state = COMPLETED plexe.set_fixed_lane(JOINER, 0, safe=False) plexe.set_active_controller(JOINER, CACC) plexe.set_path_cacc_parameters(JOINER, distance=DISTANCE) plexe.set_active_controller(BEHIND_JOIN, CACC) plexe.set_path_cacc_parameters(BEHIND_JOIN, distance=DISTANCE) topology = reset_leader(BEHIND_JOIN, topology, N_VEHICLES) if real_engine and setter is not None: # if we are running with the dashboard, update its values tracked_id = traci.gui.getTrackedVehicle("View #0") if tracked_id != "": ed = plexe.get_engine_data(tracked_id) vd = plexe.get_vehicle_data(tracked_id) setter(ed[RPM], ed[GEAR], vd.speed, vd.acceleration) step += 1 traci.close()
def total_distance(self): distance = 0.0 for i in range(len(self.visited_cities) - 1): current_city = self.visited_cities[i] next_city = self.visited_cities[i + 1] distance += utils.get_distance(current_city, next_city) distance += utils.get_distance(self.visited_cities[-1], self.visited_cities[0]) self.distance = distance
def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) start_sumo("cfg/freeway.sumo.cfg", False) step = 0 state = GOING_TO_POSITION while running(demo_mode, step, 6000): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 6000: start_sumo("cfg/freeway.sumo.cfg", True) step = 0 state = GOING_TO_POSITION random.seed(1) traci.simulationStep() if step == 0: # create vehicles and track the joiner topology = add_vehicles(N_VEHICLES, real_engine) traci.gui.trackVehicle("View #0", JOINER) traci.gui.setZoom("View #0", 20000) if step % 10 == 1: # simulate vehicle communication every 100 ms communicate(topology) if step == 100: # at 1 second, let the joiner get closer to the platoon topology = get_in_position(JOINER, FRONT_JOIN, topology) if state == GOING_TO_POSITION: # when the distance of the joiner is small enough, let the others # open a gap to let the joiner enter the platoon if get_distance(JOINER, FRONT_JOIN) < JOIN_DISTANCE + 1: state = OPENING_GAP topology = open_gap(BEHIND_JOIN, JOINER, topology, N_VEHICLES) if state == OPENING_GAP: # when the gap is large enough, complete the maneuver if get_distance(BEHIND_JOIN, FRONT_JOIN) > 2 * JOIN_DISTANCE + 2: state = COMPLETED change_lane(JOINER, 0) set_par(JOINER, cc.PAR_ACTIVE_CONTROLLER, cc.CACC) set_par(JOINER, cc.PAR_CACC_SPACING, DISTANCE) set_par(BEHIND_JOIN, cc.PAR_ACTIVE_CONTROLLER, cc.CACC) set_par(BEHIND_JOIN, cc.PAR_CACC_SPACING, DISTANCE) topology = reset_leader(BEHIND_JOIN, topology, N_VEHICLES) if real_engine and setter is not None: # if we are running with the dashboard, update its values tracked_id = traci.gui.getTrackedVehicle("View #0") if tracked_id != "": (g, rpm) = cc.unpack(get_par(tracked_id, cc.PAR_ENGINE_DATA)) data = get_par(tracked_id, cc.PAR_SPEED_AND_ACCELERATION) (v, a, u, x, y, t) = cc.unpack(data) setter(rpm, g, v, a) step += 1 traci.close()
def __init__(self, location=None, point2=None, point3=None, border_color=None, bg_color=None): Shape.__init__(self, location, border_color, bg_color, [point2, point3]) self.radx = get_distance(self.get_location(), self.points[0]) if point3 is not None: self.rady = get_distance(self.get_location(), self.points[1])
def build_bi_rrt(self): for i in range(self.num_attempts): rand_point_goal = self._get_rand_config( ) if i % self.bias_every != 0 else self.start q_new = self.extend_rrt_bi(rand_point_goal) #find the closest point from the other tree if q_new: start_tree_near = utils.get_nearest_point( q_new, self.adj_matrix.keys()) if utils.get_distance( start_tree_near, q_new) < self.distance and not utils.line_collides( q_new, start_tree_near, self.obstacles, self.distance): self.adj_matrix[q_new] = [start_tree_near] self.adj_matrix[start_tree_near].append(q_new) self.draw_line(q_new, start_tree_near) self.adj_matrix = dict(self.adj_matrix.items() + self.adj_matrix_goal.items()) #self.adj_matrix.update(self.adj_matrix_goal) print( "Found path after generation {} random configs".format( i)) return rand_point_start = self._get_rand_config( ) if i % self.bias_every != 0 else self.goal q_new = self.extend_rrt(rand_point_start) if q_new: goal_tree_near = utils.get_nearest_point( q_new, self.adj_matrix_goal.keys()) if utils.get_distance( goal_tree_near, q_new) < self.distance and not utils.line_collides( q_new, goal_tree_near, self.obstacles, self.distance): if q_new not in self.adj_matrix: self.adj_matrix[q_new] = [] if goal_tree_near not in self.adj_matrix: self.adj_matrix[goal_tree_near] = [] self.adj_matrix[q_new] = [goal_tree_near] self.adj_matrix[goal_tree_near].append(q_new) self.draw_line(q_new, goal_tree_near) self.adj_matrix = dict(self.adj_matrix.items() + self.adj_matrix_goal.items()) print( "Found path after generation {} random configs".format( i)) return return True
def match_proposal(self,propID): """ This operation try to match the specified proposal with each request of the DB @pre : offermanager_port has been initialized and is the port of the OfferManager module propId is the id of a proposal in the database @post : DB has not been modified. for each request matching the specified proposal, a message is sent to OfferManager through its port: ('buildoffer',requestID,proposalID) with requestID, the database ID of the matching request """ infos=Proposal.objects.get(id=propID) requests=Request.objects.filter(nb_requested_seats__lte=infos.number_of_seats, status='P') for request in requests: found = False for offer in Offer.objects.filter(request=request): if Ride.objects.filter(offer=offer): found=True break if not found: route_points = RoutePoints.objects.filter(proposal=infos).order_by('order') valid_pair = list() for i in xrange(len(route_points)-1): if get_distance((request.departure_point_lat,request.departure_point_long),(route_points[i].latitude,route_points[i].longitude))<request.departure_range: for j in range(i+1,len(route_points)): if get_distance((request.arrival_point_lat,request.arrival_point_long),(route_points[j].latitude,route_points[j].longitude))<request.arrival_range: valid_pair.append((i,j)) for (i,j) in valid_pair: #delete all not in time arrival if total_seconds(abs(get_time_at_point([(r.latitude,r.longitude) for r in route_points],j,infos.departure_time,infos.arrival_time)-request.arrival_time)) < request.max_delay: self.send_to(self.offermanager_port, ('buildoffer', request.id, infos.id, ( route_points[i].latitude, route_points[i].longitude, get_time_at_point([(r.latitude,r.longitude) for r in route_points], i, infos.departure_time, infos.arrival_time), route_points[i].id ), ( route_points[j].latitude, route_points[j].longitude, get_time_at_point([(r.latitude,r.longitude) for r in route_points], j, infos.departure_time,infos.arrival_time), route_points[j].id ) ))
def update_velocity(self, best): population = self.__repository.get_population() for i in range(len(population)): for j in range(len(population[0].get_velocity())): new_velocity = self.__w * population[i].get_velocity()[j] new_velocity = new_velocity + self.__c1 * random.random( ) * get_distance(population[best[i]].get_individual()[j], population[i].get_individual()[j]) new_velocity = new_velocity + self.__c2 * random.random( ) * get_distance(population[i].get_best_particle()[j], population[i].get_individual()[j]) current = population[i].get_velocity().copy() current[j] = new_velocity population[i].set_velocity(current)
def sorted_planes(lane_vehicles, lane): """ The function takes in the lane and the vehs on the lane and returns plane class objects. to ensure that vehicles on the same lane are in the same platoon, the function checks the distance of the veh to the leader and also the route of the vehicle. This function is capable of generating primary and secondary platoons """ planes = [] primary_plane = [] secondary_plane1 = [] secondary_plane2 = [] secondary_plane3 = [] leader_route = traci.vehicle.getRoute(lane_vehicles[0]) plength = len(lane_vehicles) for vehicle in lane_vehicles: if traci.vehicle.getRoute(vehicle) == leader_route and get_distance( vehicle, lane_vehicles[0]) < (240 + 200) and batch_matcher( lane_vehicles[0], vehicle): primary_plane.append(vehicle) else: secondary_plane1.append(vehicle) for veh in secondary_plane1: if traci.vehicle.getRoute(veh) != traci.vehicle.getRoute( secondary_plane1[0]) or get_distance( veh, secondary_plane1[0] ) > (N_VEHICLES * LENGTH) + (N_VEHICLES - 1) * DISTANCE + 100: secondary_plane1.pop(secondary_plane1.index(veh)) secondary_plane2.append(veh) for veh in secondary_plane2: if traci.vehicle.getRoute(veh) != traci.vehicle.getRoute( secondary_plane2[0]) or get_distance( veh, secondary_plane2[0] ) > (N_VEHICLES * LENGTH) + (N_VEHICLES - 1) * DISTANCE + 100: secondary_plane2.pop(secondary_plane2.index(veh)) secondary_plane3.append(veh) ps_planes = [ primary_plane, secondary_plane1, secondary_plane2, secondary_plane3 ] all_planes = [] for item in ps_planes: item_planes_with_empties = [(item[plength * i:plength * i + plength]) for i in range(plength)] item_planes = [ plane for plane in item_planes_with_empties if plane != [] ] for plane in item_planes: planes.append(planers.Plane(lane, plane)) return planes
def eval_dist_individuals(ind1, ind2): a1 = utils.get_distance(ind1.member1.purified, ind2.member1.purified) a2 = utils.get_distance(ind1.member1.purified, ind2.member2.purified) b1 = utils.get_distance(ind1.member2.purified, ind2.member1.purified) b2 = utils.get_distance(ind1.member2.purified, ind2.member2.purified) a = np.minimum(a1, a2) b = np.minimum(b1, b2) c = np.minimum(a1, b1) d = np.minimum(a2, b2) dist = np.mean([a, b, c, d]) return dist
def topo_contsructor(self, removed_vehs): sortd = self.veh_pos_pairs(self._ID, removed_vehs) topology = {} for item in sortd: if item[0] in removed_vehs: continue current_veh = item[0] if current_veh == self._father_vehicle: topology.update({ current_veh: { "front": current_veh, "leader": self._father_vehicle } }) else: lane_vehicles = traci.lane.getLastStepVehicleIDs( traci.vehicle.getLaneID(current_veh))[::-1] index = lane_vehicles.index(current_veh) - 1 preceding_veh = lane_vehicles[index] if utils.get_distance(current_veh, preceding_veh) < 100: topology.update({ current_veh: { "front": preceding_veh, "leader": self._father_vehicle } }) return topology
def get_features(self, left, right): try: lt, rt = super().map_indices_to_rows(left, right) distance = utils.get_distance(lt, rt) ltName = lt.standardized_name.replace('_', ' ') rtName = rt.standardized_name.replace('_', ' ') fuzz_ratio = fuzz.ratio(ltName, rtName) fuzz_partial_ratio = fuzz.partial_ratio(ltName, rtName) fuzz_token_set_ratio = fuzz.token_set_ratio(ltName, rtName) len_ratio = abs(len(ltName) - len(rtName)) / max( len(ltName), len(rtName)) words_ratio = abs((ltName.count(' ') + 1) - (rtName.count(' ') + 1)) / max( ltName.count(' ') + 1, rtName.count(' ') + 1) entityid_same = lt.entity_id == rt.entity_id platform_same = lt.platform == rt.platform return [ distance, fuzz_ratio, fuzz_partial_ratio, fuzz_token_set_ratio, len_ratio, words_ratio, entityid_same, platform_same ] except Exception as e: print('catch: get features') print(e) print(lt.standardized_name, rt.standardized_name) raise e
def generate(self): # Select mutation operator. rand_mutation_probability = random.uniform(0, 1) if rand_mutation_probability >= MUTOPPROB: mutation = 1 else: mutation = 2 condition = True counter_mutations = 0 while condition: counter_mutations += 1 vector1, vector2 = mutation_manager.generate( self.digit.xml_desc, mutation) v1_xml_desc = vectorization_tools.create_svg_xml(vector1) rasterized_digit1 = rasterization_tools.rasterize_in_memory( v1_xml_desc) v2_xml_desc = vectorization_tools.create_svg_xml(vector2) rasterized_digit2 = rasterization_tools.rasterize_in_memory( v2_xml_desc) distance_inputs = get_distance(rasterized_digit1, rasterized_digit2) if distance_inputs != 0: condition = False first_digit = Digit(v1_xml_desc, EXPECTED_LABEL) second_digit = Digit(v2_xml_desc, EXPECTED_LABEL) first_digit.purified = rasterized_digit1 second_digit.purified = rasterized_digit2 return first_digit, second_digit, distance_inputs
def get_score_from_matif_matrix(matif_matrix): profile = form_profile(matif_matrix) most_prob_word = get_most_probable_word(profile) ans = 0 for matif in matif_matrix: ans += get_distance(matif, most_prob_word) return ans
def update_archive(self, ind): if ind not in self.archive: if len(self.archive) == 0: self.archive.append(ind) self.archived_seeds.add(ind.seed) else: # Find the member of the archive that is closest to the candidate. closest_archived = None d_min = np.inf i = 0 while i < len(self.archive): distance_archived = eval_archive_dist(ind, self.archive[i]) if distance_archived < d_min: closest_archived = self.archive[i] d_min = distance_archived i += 1 # Decide whether to add the candidate to the archive # Verify whether the candidate is close to the existing member of the archive # Note: 'close' is defined according to a user-defined threshold if d_min <= ARCHIVE_THRESHOLD: # The candidate replaces the closest archive member if its members' distance is better dist_ind = ind.distance dist_archived_ind = get_distance(closest_archived.member1.purified, closest_archived.member2.purified) if dist_ind <= dist_archived_ind: self.archive.remove(closest_archived) self.archive.append(ind) self.archived_seeds.add(ind.seed) else: # Add the candidate to the archive if it is distant from all the other archive members self.archive.append(ind) self.archived_seeds.add(ind.seed)
def run_dijkstra(maze, put_on_a_show): print('Dijkstra chosen.') queue = [] prev = {} distance = {} queue.append(maze.start) distance[maze.start] = 0 while queue: open_node = queue.pop(0) if open_node == maze.end: maze = utils.reconstruct_path(maze, prev, maze.start, maze.end) maze.report(name='Dijkstra') return maze neighbours = maze.get_neighbours(open_node) for neighbour in neighbours: distance_to_node = distance[open_node] + utils.get_distance( open_node, neighbour) if maze.layout[neighbour[1]][neighbour[0]] != 'X': if (neighbour not in distance.keys()) or (distance_to_node < distance[neighbour]): queue.append(neighbour) prev[neighbour] = open_node distance[neighbour] = distance_to_node if open_node != maze.start: maze.layout[open_node[1]][open_node[0]] = 'O' if put_on_a_show: maze.print_maze()
def get_jobs_in_range(self, pos, job_range): result = [] for job in self.jobs: d = utils.get_distance(pos, job) if d < job_range: result.append(job) return result
def hand_click(landmark, pixel): x = pixel.x y = pixel.y #print(x, y) global nowclick if get_distance(landmark[4], landmark[8]) < get_distance(landmark[4], landmark[3]) and nowclick == False: print('click') win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, int(x), int(y), 0, 0) nowclick = True elif get_distance(landmark[4], landmark[8]) > 1.5*get_distance(landmark[4], landmark[3]) and nowclick == True: print('click off') win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, int(x), int(y), 0, 0) nowclick = False
def is_speed_noise(test_location, last_location): distance = utils.get_distance(test_location, last_location) time = test_location.timestamp - last_location.timestamp if time.total_seconds() == 0: return True speed = (distance * 60 * 60) / time.total_seconds() return speed > NOISE_SPEED
def get_speed(test_location, last_location): distance = utils.get_distance(test_location, last_location) time = test_location.timestamp - last_location.timestamp if time.total_seconds() == 0: return True return (distance, time.total_seconds(), (distance * 60 * 60) / time.total_seconds())
def apply(self, items): return [ item for item in items if (get_distance(self.lng, self.lat, item.lng, item.lat) <= self.radius) ]
def _count_points(self, num): r = get_distance(self.points[0], self.get_location()) alpha = atan((self.points[0].y() - self.get_location().y()) / (self.points[0].x() - self.get_location().x())) for i in range(1, num): x = r * cos(2.0 * pi * i / num + alpha) + self.get_location().x() y = r * sin(2.0 * pi * i / num + alpha) + self.get_location().y() self.points.append(QPoint(x, y))
def list_parkings(my_location): parkings = conn.execute('SELECT * FROM parkings') for i in range(len(parkings)): p = Obj() p.__dict__ = dict(parkings[i]._asdict().items()) p.distance = utils.get_distance(my_location, (parkings[i].lat, parkings[i].lon)) parkings[i] = p return sorted(parkings, key=lambda x: x.distance)
def make_distance_table(cities): length = len(cities) table = [[ utils.get_distance((cities[i][0], cities[i][1]), (cities[j][0], cities[j][1])) for i in range(0, length) ] for j in range(0, length)] return table
def update_local_goal_aux(self): pos = self.agent.get_position()[:-1] distance = get_distance(pos, self.local_goal_aux.get_position()[:-1]) if distance < 0.5: self.local_goal_aux.set_position( self.local_goal_aux_pos_list[self.ind_local_goal_aux]) self.ind_local_goal_aux += 1 return -1 * distance**2
def mutate(self): condition = True counter_mutations = 0 while condition: # Select mutation operator. rand_mutation_probability = random.uniform(0, 1) rand_mutation_prob = random.uniform(0, 1) if rand_mutation_probability >= MUTOPPROB: if rand_mutation_prob >= MUTOFPROB: mutation = 1 else: mutation = 2 else: if rand_mutation_prob >= MUTOFPROB: mutation = 3 else: mutation = 4 counter_mutations += 1 mutant_vector = mutation_manager.mutate(self.digit.xml_desc, mutation, counter_mutations/20) mutant_xml_desc = vectorization_tools.create_svg_xml(mutant_vector) rasterized_digit = rasterization_tools.rasterize_in_memory(mutant_xml_desc) distance_inputs = get_distance(self.digit.purified, rasterized_digit) if (TSHD_TYPE == '0'): if distance_inputs != 0: condition = False elif (TSHD_TYPE == '1'): seed_image = DigitMutator.x_test[int(self.digit.seed)] xml_desc = vectorization_tools.vectorize(seed_image) seed = rasterization_tools.rasterize_in_memory(xml_desc) distance_seed = get_distance(seed, rasterized_digit) if distance_inputs != 0 and distance_seed <= DISTANCE and distance_seed != 0: condition = False elif (TSHD_TYPE == '2'): seed = reshape(DigitMutator.x_test[int(self.digit.seed)]) distance_seed = get_distance(seed, rasterized_digit) if distance_inputs != 0 and distance_seed <= DISTANCE_SEED and distance_seed != 0: condition = False self.digit.xml_desc = mutant_xml_desc self.digit.purified = rasterized_digit self.digit.predicted_label = None self.digit.confidence = None
def compute_fee(proposal, departure, arrival): dep = RoutePoints.objects.get(id=departure) arr = RoutePoints.objects.get(id=arrival) total=0. last = dep for index in range(dep.order+1, arr.order+1): tmp = RoutePoints.objects.get(order=index,proposal=proposal) total+=get_distance((last.latitude,last.longitude),(tmp.latitude,tmp.longitude)) last= tmp return total*proposal.money_per_km
def run_a_star(maze, put_on_a_show): print('A* chosen.') queue = [] closed = [] prev = {} distance = {} heapq.heappush(queue, (0, maze.start)) distance[maze.start] = 0 while queue: open_node = heapq.heappop(queue)[1] if open_node == maze.end: maze = utils.reconstruct_path(maze, prev, maze.start, maze.end) maze.report(name='A*') return maze neighbours = maze.get_neighbours(open_node) for neighbour in neighbours: if neighbour not in closed: distance_to_node = distance[open_node] + utils.get_distance( open_node, neighbour) distance_to_end = utils.get_distance(neighbour, maze.end) if maze.layout[neighbour[1]][neighbour[0]] != 'X': if (neighbour not in queue) or (distance_to_node < distance[neighbour]): prev[neighbour] = open_node distance[neighbour] = distance_to_node if neighbour not in queue: heapq.heappush(queue, (distance_to_node + distance_to_end, neighbour)) closed.append(neighbour) closed.append(open_node) if open_node != maze.start: maze.layout[open_node[1]][open_node[0]] = 'O' if put_on_a_show: maze.print_maze()
def match_request(requestID): """ This operation try to match the specified proposal with each request of the DB @pre : DB has been initialized and is the SQL database offermanager_port has been initialized and is the port of the OfferManager module requestId is the id of a request in the database @post : DB has not been modified. for each proposal matching the specified request, a message is sent to OfferManager through its port: ('buildoffer',requestID,proposalID) with proposalID, the database ID of the matching proposal """ request=Request.objects.get(id=requestID) proposals=Proposal.objects.filter(number_of_seats__gte=request.nb_requested_seats) for infos in proposals: route_points = RoutePoints.objects.filter(proposal=infos).order_by('order') valid_pair = list() for i in xrange(len(route_points)-2): if get_distance((request.departure_point.latitude,request.departure_point.longitude),(route_points[i].latitude,route_points[i].longitude))<request.departure_range: for j in range(i+1,len(route_points)): if get_distance((request.arrival_point.latitude,request.arrival_point.longitude),(route_points[j].latitude,route_points[j].longitude))<request.arrival_range: valid_pair.append((i,j)) for (i,j) in valid_pair: #delete all not in time arrival if total_seconds(abs(get_time_at_point([(r.latitude,r.longitude) for r in route_points],j,infos.departure_time,infos.arrival_time)-request.arrival_time)) < request.max_delay: build_offer(requestID, infos.id, ( route_points[i].latitude, route_points[i].longitude, get_time_at_point([(r.latitude,r.longitude) for r in route_points], i,infos.departure_time,infos.arrival_time), route_points[i].id ), ( route_points[j].latitude, route_points[j].longitude, get_time_at_point([(r.latitude,r.longitude) for r in route_points], j,infos.departure_time,infos.arrival_time), route_points[j].id ))
def is_stop_point(test_location, last_location): distance = utils.get_distance(test_location, last_location) time = test_location.timestamp - last_location.timestamp distance = distance - (test_location.accuracy + last_location.accuracy) / 1000 if time.total_seconds() == 0: return True speed = (distance * 60 * 60) / time.total_seconds() return speed < 3
def travel_speed(self, point): '''Fast calculation of travel speed to point''' if self.busy.locked(): return None time_diff = max(time() - self.last_request, config.SCAN_DELAY) if time_diff > 60: self.error_code = None distance = get_distance(self.location, point) # conversion from meters/second to miles/hour speed = (distance / time_diff) * 2.236936 return speed
def get_new_target(self): print("Getting New Target") while True: print("Trying..") rx = random.randint(20, self.game.game_area.width - 20) ry = random.randint(20, self.game.game_area.height - 20) d = utils.get_distance(self.position, (rx, ry)) if d > 30: print("Found it") return pygame.Vector2(rx, ry) else: print("Trying Again")
def eval_archive_dist(ind1, ind2): if ind1.member1.predicted_label == EXPECTED_LABEL: ind1_correct = ind1.member1.purified ind1_misclass = ind1.member2.purified else: ind1_correct = ind1.member2.purified ind1_misclass = ind1.member1.purified if ind2.member1.predicted_label == EXPECTED_LABEL: ind2_correct = ind2.member1.purified ind2_misclass = ind2.member2.purified else: ind2_correct = ind2.member2.purified ind2_misclass = ind2.member1.purified dist1 = utils.get_distance(ind1_correct, ind2_correct) dist2 = utils.get_distance(ind1_misclass, ind2_misclass) dist = np.mean([dist1, dist2]) return dist
def get_path_features(self, start_id, end_id): total_distance = 0 start_num = min(start_id, end_id) end_num = max(start_id, end_id) for cnt in range(start_num+2, end_num): x1 = self.route[cnt-2, 0] y1 = self.route[cnt-2, 1] x2 = self.route[cnt, 0] y2 = self.route[cnt, 1] distance1 = get_distance(x1, y1, x2, y2) distance1 = distance1 / 2.0 if (distance1 > 200): distance1 = 200 total_distance += distance1 return total_distance
P.itemset((i, i), 15625 * 4) i = i + 1 observation_number = 1 n = 0 for set_up_point_name in set_up_points: for observation in observations: if observation.from_point.name == set_up_point_name: row = [0, 0] + [0] * number_of_set_ups observed = None calculated = None if observation.type_ == 'direction': observed = observation.value calculated = get_direction(observation.from_point, observation.to_point) if observation.to_point.type_ == 'provisional': d = get_distance(observation.to_point, observation.from_point) y = 206264.8 * (observation.to_point.x - observation.from_point.x) / d**2 x = -206264.8 * (observation.to_point.y - observation.from_point.y) / d**2 row[0], row[1] = y, x row[1 + observation_number] = -1 A = numpy.vstack([A, row]) if observation.to_point.type_ == 'fixed': n = n + 1 row[1 + observation_number] = -1 A = numpy.vstack([A, row]) oc = (math.degrees(observed-calculated)*3600) l = numpy.vstack([l, oc]) observation_number = observation_number + 1 for observation in observations:
def check_all_rides(self): """ Check every ride in the self.rides_list which contains an object for each tracked ride For every ride in the list, process the new messages """ new_connection = True # accept new connections and ask name while new_connection: try : conn,addr = self.tcp_socket.accept() conn.setblocking(0) self.unregistered_connections.append([None,conn]) except : new_connection = False # check if there is unregistered user to register self.lock.acquire() for unreg in self.unregistered_connections: try : msgs = unreg[1].recv(1024) for msg in msgs.split('\n'): if msg.split('&')[MTYPE]=='usr!': if not User.objects.filter(username=msg.split('&')[MMESS]):#msg.split('&')[MMESS] not in self.debug_userdico: unreg[1].send('usr?&&\n') else : unreg[0]=msg.split('&')[MMESS] unreg[1].send('pwd?&&\n') elif msg.split('&')[MTYPE]=='pwd!': try: user = None if not DEBUG: user = User.objects.get(username=unreg[0]) if user.check_password(msg.split('&')[MMESS]):#self.debug_userdico[unreg[0]]==msg.split('&')[MMESS]: # if unreg[0] not in self.userdict: self.userdict[unreg[0]]=[unreg[1],list()] self.unregistered_connections.remove(unreg) else: self.userdict[unreg[0]][UCONN]=unreg[1] else : unreg[1].send('pwd?&&\n') except: unreg[1].send('usr?&&\n') except socket.error : pass self.lock.release() # check for each ride if there's something to do for ride in self.rides_list: drivername = None if DEBUG: drivername = self.debug_userlist[ride[DRIVER]] else: drivername = UserProfile.objects.get(id=ride[DRIVER]).user.username ndrivername = None if DEBUG: ndrivername = self.debug_userlist[ride[NDRIVER]] else: ndrivername = UserProfile.objects.get(id=ride[NDRIVER]).user.username if not ride[NDAWARE] and ndrivername in self.userdict: self.userdict[ndrivername][0].send('ndr!&'+str(ride[RIDEID])+'&'+str(ride[RIDETIME])+'\n') ride[NDAWARE]=True if ride[STATE]==SPENDING and (ride[RIDETIME]-datetime.datetime.now()) < datetime.timedelta(0,60*30): # the driver has to be notified self.send_to(self.usernotifier_port,('newmsg',ride[DRIVER],"Don't forget your ride from " +str(ride[RIDETIME]))) ride[STATE]=SREMINDED if (ride[STATE]==SREMINDED or ride[STATE]==SOPENCONN) and (ride[RIDETIME]-datetime.datetime.now())<datetime.timedelta(0,60*5): # the nondriver should be asked if the ride has started if ndrivername in self.userdict: self.userdict[ndrivername][UCONN].send('stt?&'+str(ride[RIDEID])+'&'+str(ride[RIDETIME])+'\n') ride[STATE]=SSTARTEDA elif ride[STATE]==SREMINDED: self.send_to(self.usernotifier_port,('newmsg',ride[NDRIVER],"Please, open your COOL's smartphone app.")) ride[STATE]=SOPENCONN if drivername in self.userdict: fill_buffer(self.userdict[drivername]) for msg in self.userdict[drivername][UBUFF]: if msg.split('&')[MTYPE]=='est!' and int(msg.split('&')[MRIDE])==ride[RIDEID]: self.userdict[drivername][UBUFF].remove(msg) if drivername not in self.userdict: self.send_to(self.usernotifier_port,('newmsg',ride[NDRIVER],"Please, open your COOL's smartphone app.")) else: self.userdict[ndrivername][UCONN].send(msg) elif msg.split('&')[MTYPE]=='pos!' and int(msg.split('&')[MRIDE])==ride[RIDEID]: self.userdict[drivername][UBUFF].remove(msg) if ndrivername not in self.userdict: self.send_to(self.usernotifier_port,('newmsg',ride[NDRIVER],"Please, open your COOL's smartphone app.")) else: dist = get_distance(map(float,msg.split('&')[MMESS].split()),(ride[PPLAT],ride[PPLON])) self.userdict[ndrivername][UCONN].send('dst!&'+msg[MRIDE]+'&'+str(dist)+' km\n') else: self.userdict[drivername][UCONN].close() self.userdict[drivername][UCONN]=None if self.userdict[drivername]==[None,list()]: # erase the connection pass if ndrivername in self.userdict: fill_buffer(self.userdict[ndrivername]) for msg in self.userdict[ndrivername][UBUFF]: if msg.split('&')[MTYPE]=='get?' and int(msg.split('&')[MRIDE])==ride[RIDEID]: self.userdict[ndrivername][UBUFF].remove(msg) if drivername not in self.userdict: self.send_to(self.usernotifier_port,('newmsg',ride[DRIVER],"Please, open your COOL's smartphone app.")) self.userdict[ndrivername][UCONN].send('dnc!&&\n') else: self.userdict[drivername][UCONN].send('get?&'+str(ride[RIDEID])+'&'+str(ride[RIDETIME])+'\n') elif msg.split('&')[MTYPE]=='stt!' and int(msg.split('&')[MRIDE])==ride[RIDEID]: self.userdict[ndrivername][UBUFF].remove(msg) threading.Thread(target=ride[CALLB_OK]).start() if drivername in self.userdict: self.userdict[drivername][UCONN].send('stt!&'+str(ride[RIDEID])+'&\n') else: self.send_to(self.usernotifier_port,('newmsg',ride[DRIVER],'Ride '+str(ride[RIDEID])+' has started.')) self.rides_list.remove(ride) elif msg.split('&')[MTYPE]=='ccl!' and int(msg.split('&')[MRIDE])==ride[RIDEID]: self.userdict[ndrivername][UBUFF].remove(msg) threading.Thread(target=ride[CALLB_KO]).start() self.rides_list.remove(ride) else: self.userdict[drivername][UCONN].close() self.userdict[ndrivername][UCONN]=None if self.userdict[ndrivername]==(None,list()): # erase the connection pass threading.Timer(5.,lambda:self.check_all_rides()).start()
def create_users(nb_users, male_first_name_list, female_first_name_list, last_name_list, server_list, pwd_list, communities_list, car_desc_list, route_points_list): counter = 1 counter2 = 0 advancement_list = ['[',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',']'] for i in xrange(nb_users): if counter > counter2 * nb_users/50: counter2 += 1 advancement_list[counter2] = '=' printlist(advancement_list) counter += 1 # Chosing all the random fields for user and profile tables gender = random.randint(0,1) == 1 if gender: f_name_ind = random.randint(0, len(male_first_name_list) - 1) first_name = male_first_name_list[f_name_ind] gender = 'M' else: f_name_ind = random.randint(0, len(female_first_name_list) - 1) first_name = female_first_name_list[f_name_ind] gender = 'F' l_name_ind = random.randint(0, len(last_name_list) - 1) last_name = last_name_list[l_name_ind] uname = first_name + '_' + last_name + str(random.randint(0,999)) server_ind = random.randint(0, len(server_list) - 1) email = first_name + '.' + last_name + '@' + server_list[server_ind] + '.com' pwd_ind = random.randint(0, len(pwd_list) - 1) password = uname #pwd_list[pwd_ind] + str(random.randint(0,999)) com_ind_list = list() for i in xrange(random.randint(1,5)): com_ind_list.append(random.randint(0, len(communities_list) - 1)) communities = '' for com_ind in list(set(com_ind_list)): communities += communities_list[com_ind] + ',' car = random.randint(0,1) == 1 if car: car_desc_ind = random.randint(0, len(car_desc_list) - 1) car_description = car_desc_list[car_desc_ind] else: car_description = None birthdate = datetime.date(random.randint(1950,1990), random.randint(1,12), random.randint(1,28)) bank_account = str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + '-' + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + '-' + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) car_id = chr(random.randint(65,90)) + chr(random.randint(65,90)) + chr(random.randint(65,90)) + '-' + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) phone_nb = '0'+ str(random.randint(0,9)) + str(random.randint(0,9)) + '/' + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) if car: nb_seats = random.randint(1,5) else: nb_seats = 0 # Creating a new user and his/her profile: user = create_user(uname, first_name, last_name, email, password) userprofile = create_profile(user, nb_seats, birthdate, random.randint(0,1) == 1, communities, random.uniform(0.01, 0.25), gender, bank_account, car_id, phone_nb, car_description) # Chosing all the random fields for request and proposal tables for j in xrange(random.randint(0,2)): dep_p_ind = random.randint(0, len(route_points_list) - 1) ar_p_ind = random.randint(0, len(route_points_list) - 1) dep_p_lat = route_points_list[dep_p_ind][0] dep_p_long = route_points_list[dep_p_ind][1] dep_ran = random.uniform(0.5, 25.0) ar_p_lat = route_points_list[ar_p_ind][0] ar_p_long = route_points_list[ar_p_ind][1] ar_ran = random.uniform(0.5, 25.0) ar_time = datetime.datetime(2010, 12, random.randint(20,31), random.randint(7,22), random.randint(0,59), 0) max_del = random.randint(300,3600) nb_seats= random.randint(1,4) cancel_margin = datetime.datetime(2010, 12, (ar_time.day-random.randint(0,1)), (ar_time.hour - random.randint(0,ar_time.hour)),ar_time.minute,ar_time.second) create_request(userprofile, dep_p_lat, dep_p_long, dep_ran, ar_p_lat, ar_p_long, ar_ran, ar_time, max_del, nb_seats, cancel_margin) if car: for k in xrange(random.randint(0,2)): car_id = userprofile.car_id car_desc = userprofile.car_description nb_seats = userprofile.number_of_seats moneyperkm = userprofile.money_per_km dep_time = datetime.datetime(2010, 12, random.randint(20,31), random.randint(7,22), random.randint(0,59), 0) rp_list = list() for rp in xrange(random.randint(2, 10)): rp_list.append(route_points_list[random.randint(0, len(route_points_list) - 1)]) route_p_list = [(-8000.0,-8000.0)] order = random.randint(0,1) for e in list(set(rp_list)): add_in_rp_list(e, route_p_list, order) route_p_list.remove((-8000.0,-8000.0)) if len(route_p_list) < 2: print "less than 2" route_p_list.insert(0,(50.885015567679545, 5.096008367836475)) dist = get_distance(route_p_list[0],route_p_list[-1]) ar_time = dep_time + datetime.timedelta(minutes=dist*100.0/60.0) create_proposal(userprofile, car_id, car_desc, nb_seats, moneyperkm, dep_time, ar_time, route_p_list)