Ejemplo n.º 1
0
def create_sample(idx, points, reference_points):
    radius = points[idx, 3]
    point = points[idx, :3]
    directions_label = np.zeros(D, dtype="float32")

    for i in range(50, 201):
        assert idx + i < points.shape[0] - 1
        distance = calculate_distance(point, points[idx + i, :3])
        if distance > radius:
            print("forward: %.5f" % distance)
            forward_idx = idx + i
            break
    forward_d = find_direction_cat(point, points[forward_idx, :3],
                                   reference_points)
    directions_label[forward_d] = 0.5

    for i in range(50, 201):
        assert idx - i > 0
        distance = calculate_distance(point, points[idx - i, :3])
        if distance > radius:
            print("backward: %.5f" % distance)
            backward_idx = idx - i
            break
    backward_d = find_direction_cat(point, points[backward_idx, :3],
                                    reference_points)
    directions_label[backward_d] = 0.5

    return radius, directions_label
Ejemplo n.º 2
0
    def test_calculate_distance(self):
        point1 = [0, 0]
        point2 = [2, 2]
        exp_dist = 2.82

        distance = utils.calculate_distance(point1, point2)
        self.assertAlmostEqual(distance, exp_dist, places=1)

        point1 = [10, 10]
        point2 = [0, 6]
        exp_dist = 10.77

        distance = utils.calculate_distance(point1, point2)
        self.assertAlmostEqual(distance, exp_dist, places=1)
Ejemplo n.º 3
0
def main(file, note_arr=None, plot_starts=False, plot_fft_indices=[]):
    actual_notes = []

    if note_arr:
        actual_notes = note_arr

    song = AudioSegment.from_file(file)
    #song = song.high_pass_filter(80, order=4)

    starts = predict_note_starts(song, plot_starts)

    predicted_notes = predict_notes(song, starts, plot_fft_indices)

    print("")
    if actual_notes:
        print("Actual Notes")
        print(actual_notes)
    print("Predicted Notes")
    print(predicted_notes)

    if actual_notes:
        lev_distance = calculate_distance(predicted_notes, actual_notes)
        score = abs(len(actual_notes) - lev_distance) / len(actual_notes)
        print("Levenshtein distance: {}/{}".format(lev_distance,
                                                   len(actual_notes)))
        return score
Ejemplo n.º 4
0
 def random_search():
     truck_x, truck_y = self.depo_coords
     if self.greedy:
         self.customer_info.sort(key=lambda x: x[1])
     else:
         random.shuffle(self.customer_info)
     visited = set()
     total_distance_traveled = 0
     all_truck_paths = []
     for i in range(self.num_vehicles):
         capacity = self.vehicle_capacity
         truck_path = [0]
         for customer_idx, customer_demand, customer_x, customer_y in self.customer_info:
             if customer_idx in visited:
                 continue
             if capacity - customer_demand < 0:
                 continue
             visited.add(customer_idx)
             capacity -= customer_demand
             truck_path.append(customer_idx)
             total_distance_traveled += calculate_distance(
                 truck_x, truck_y, customer_x, customer_y)
             truck_x = customer_x
             truck_y = customer_y
             if capacity == 0: break
         truck_path.append(0)  #goes back to depot
         all_truck_paths.append(truck_path)
     return all_truck_paths, total_distance_traveled
Ejemplo n.º 5
0
 def calculate_priority(self, is_current_state: bool) -> None:
     if not self.status.snitch_available:
         return 0
     self.snitch = self.status.find_snitch()
     if self.snitch == None:
         return 0
     distance = calculate_distance(self.status.position, self.snitch.position)
     return (0.5 - distance/200) + (3 * 0.125)
Ejemplo n.º 6
0
    def width(self):
        """ 
        Calculate the width, in statue miles.

        @return: width, in statute miles
        @rtype: C{float}
        """
        return calculate_distance(self.min_lat, self.min_lon, 
                                  self.min_lat, self.max_lon)
Ejemplo n.º 7
0
    def height(self):
        """ 
        Calculate the height, in statue miles.

        @return: height, in statute miles
        @rtype: C{float}
        """
        return calculate_distance(self.min_lat, self.min_lon,
                                  self.max_lat, self.min_lon)
Ejemplo n.º 8
0
def main(file,
         note_file=None,
         note_starts_file=None,
         plot_starts=False,
         plot_fft_indices=[]):
    # If a note file and/or actual start times are supplied read them in
    actual_starts = []
    if note_starts_file:
        with open(note_starts_file) as f:
            for line in f:
                actual_starts.append(float(line.strip()))

    actual_notes = []
    if note_file:
        with open(note_file) as f:
            for line in f:
                actual_notes.append(line.strip())

    song = AudioSegment.from_file(file)
    song = song.high_pass_filter(80, order=4)

    starts, ends, volumes = predict_note_starts(song, plot_starts,
                                                actual_starts)

    predicted_notes = predict_notes(song, starts, actual_notes,
                                    plot_fft_indices)

    track = 0
    channel = 0
    time = 0  # In beats
    duration = 0.3  # In beats
    tempo = 60  # In BPM
    volume = 100  # 0-127, as per the MIDI standard

    MyMIDI = MIDIFile(
        1)  # One track, defaults to format 1 (tempo track is created
    # automatically)
    MyMIDI.addTempo(track, time, tempo)
    # TODO(elliear): Modify duration to match start and end, and volume, and pitch
    for i, pitch in enumerate(degrees):
        MyMIDI.addNote(track, channel, pitch, time + i * 0.3, duration, volume)

    with open("major-scale.mid", "wb") as output_file:
        MyMIDI.writeFile(output_file)

    print("")
    if actual_notes:
        print("Actual Notes")
        print(actual_notes)
    print("Predicted Notes")
    print(predicted_notes)

    if actual_notes:
        lev_distance = calculate_distance(predicted_notes, actual_notes)
        print("Levenshtein distance: {}/{}".format(lev_distance,
                                                   len(actual_notes)))
Ejemplo n.º 9
0
    def calculate_total_distance(self, solution):
        total_distance_traveled = 0
        for truck_locations in solution:
            for start, end in zip(truck_locations[:-1], truck_locations[1:]):
                _, _, start_x, start_y = self.customer_info[start]
                _, _, end_x, end_y = self.customer_info[end]

                total_distance_traveled += calculate_distance(
                    start_x, start_y, end_x, end_y)
        return total_distance_traveled
 def calculate_priority(self, is_current_state: bool):
     baby_pos = self.status.position
     seentanks = self.status.recently_seen_tanks(2)
     for tank in seentanks:
         in_danger = all((tank.is_aiming_at(baby_pos), tank.has_ammo(),
                          calculate_distance(self.status.position,
                                             tank.current_pos()) < 35))
         if in_danger:
             self.tank = tank
             return 0.75
     return 0
Ejemplo n.º 11
0
def extract_distance_from_avg_vector(df):
    neg_posts = utils.get_abusive_df(df)['text'].tolist()
    pos_posts = utils.get_no_abusive_df(df)['text'].tolist()
    m_wiki = w2v.get_model(ROOT / "Embedding/wiki.he.word2vec.model")
    m_our = w2v.get_model(ROOT / "Embedding/our.corpus.word2vec.model")
    neg_matrix = helpers.create_vectors_array(neg_posts, m_our, m_wiki)
    pos_matrix = helpers.create_vectors_array(pos_posts, m_our, m_wiki)
    neg_avg_vec = np.mean(neg_matrix)
    pos_avg_vec = np.mean(pos_matrix)
    distance_type = 'euclidean'
    df_offensive_distance = pd.DataFrame(
        columns=['id', 'dist_avg_neg', 'dist_avg_pos'])
    df_offensive_distance['id'] = df['id'].tolist()
    df_offensive_distance['dist_avg_neg'] = df['text'].apply(
        lambda x: utils.calculate_distance(
            w2v.get_post_vector(m_our, m_wiki, x), neg_avg_vec, distance_type))
    df_offensive_distance['dist_avg_pos'] = df['text'].apply(
        lambda x: utils.calculate_distance(
            w2v.get_post_vector(m_our, m_wiki, x), pos_avg_vec, distance_type))
    return df_offensive_distance
Ejemplo n.º 12
0
def get_distance_df(df, column_name, sentence, distance_type='euclidean'):
    df_offensive_distance = pd.DataFrame(columns=['id', column_name])
    df_offensive_distance['id'] = df['id'].tolist()

    m_wiki = w2v.get_model(ROOT + "/Embedding/wiki.he.word2vec.model")
    m_our = w2v.get_model(ROOT + "/Embedding/our.corpus.word2vec.model")

    df_offensive_distance[column_name] = df['text'].apply(
        lambda x:
        utils.calculate_distance(w2v.get_post_vector(m_our, m_wiki, x),
                                 w2v.get_post_vector(m_our, m_wiki, sentence), distance_type))
    return df_offensive_distance
Ejemplo n.º 13
0
def calculate_distance_mode(pairs, df, ref, mode, measure, ref2=[]):
    """
    From a set of pairs, calculate the distance of the offset of the 
    pair in relation to the global offset.

    Parameters:
    -----------
    pairs: list
        list containing tuples of IDs of norms [(id1,id2),(id3,id4)...]
    df: pandas.dataframe
        dataframe containing ids and embeddings of sentences
    ref: np.array
        vector containing the reference to measure the distance
    mode: string
        how vectors are combined (offset, concat or mean)
    measure: string
        measure to calculate the distance (euc or cos)
    ref2: np.array
        calculate the distance to a second reference

    Return:
    -------
        list containing the distance and ids in the form 
        [(dist, id1, id2), (dist, id2, id3),...]
    """
    vdist = []
    pb = progressbar.ProgressBar(len(pairs))
    for i, pair in enumerate(pairs):
        id1, id2 = pair
        combined = utils.combine(pair, df, mode=mode)
        dist = utils.calculate_distance(combined, ref, measure=measure)
        if len(ref2) > 0:
            dist2 = utils.calculate_distance(combined, ref2, measure=measure)
            vdist.append((dist, dist2, id1, id2))
        else:
            vdist.append((dist, id1, id2))
        pb.update()
        #if i == 1000: break
    return vdist
Ejemplo n.º 14
0
def remove_clipping(xyz):
    index = []
    for pts in range(0, len(xyz)):
        # calculate x index
        x = xyz[pts][0]
        y = xyz[pts][1]
        z = xyz[pts][2]
        # 0,-0.39098,0.13889
        if calculate_distance(x, y, z, 0, -0.5910,
                              0.7389) > 1.5 or x > 0.5 or y > 0.5:
            index.append(pts)
    xyz = np.delete(xyz, index, axis=0)
    return xyz
Ejemplo n.º 15
0
def get_nearby_customers(customers, max_distance):
    '''
    Get a list of customers inside radius provided from Dublin Office
    '''

    nearby_customers = []

    for customer in customers:
        current_coord = (customer['latitude'], customer['longitude'])
        if calculate_distance(current_coord, OFFICE_COORD) <= max_distance:
            nearby_customers.append(customer)

    return nearby_customers
Ejemplo n.º 16
0
    def calculate_distance(self, point):
        """ 
        Calculate the distance from this point to the given point,
        in statue miles. 

        @param point: point to calculate distance to
        @type point: L{Point}

        @return: distance in statute miles
        @rtype: C{float}
        """
        if point is self:
            return 0.0

        return calculate_distance(self.lat, self.lon, point.lat, point.lon)
Ejemplo n.º 17
0
    def insert(self, osm_object):
        center_x = self.center_point[0]
        center_y = self.center_point[1]

        angle_1, angle_2 = calculate_border_angles_to_object_and_point(
            center_x, center_y, osm_object, self.img_shape)

        ### почему???
        #         angle_1, angle_2 = calculate_border_angles_to_object_and_point(center_y, center_x, osm_object, self.img_shape)
        object_x, object_y = calculate_osm_object_center(osm_object)

        distance = calculate_distance((center_x, center_y),
                                      (object_x, object_y))
        ### почему???
        #         distance = calculate_distance((center_x, center_y), (object_y, object_x))

        diff_between_angles = abs(angle_2 - angle_1)
        # Перехода через 0 нет
        start_angle = min(angle_1, angle_2)
        end_angle = max(angle_1, angle_2)

        if diff_between_angles >= 180:  # Есть переход через 0
            start_angle = max(angle_1, angle_2)
            end_angle = min(angle_1, angle_2)

        sector_start_idx = int(start_angle / self.step_grad)
        sector_end_idx = int(end_angle / self.step_grad)

        if self.with_angle_penalty:
            sectors_count = abs(sector_start_idx - sector_end_idx) + 1
            sector_penalty = 1 / sectors_count

        if diff_between_angles < 180:
            for sector_idx in range(sector_start_idx, sector_end_idx + 1):
                if not self.with_angle_penalty:
                    self.sectors[sector_idx].append((distance, osm_object.tag))
                else:
                    self.sectors[sector_idx].append(
                        (distance, osm_object.tag, sector_penalty))
        else:
            for sector_idx in list(range(sector_start_idx,
                                         self.sectors_count)) + list(
                                             range(0, sector_end_idx)):
                if not self.with_angle_penalty:
                    self.sectors[sector_idx].append((distance, osm_object.tag))
                else:
                    self.sectors[sector_idx].append(
                        (distance, osm_object.tag, sector_penalty))
Ejemplo n.º 18
0
    def perform(self):
        enemy = self.target if self.target else self.status.find_best_enemy_target(
        )
        position = self.status.position

        next_heading = heading_from_to(position, enemy.current_pos())
        # self.turret_controls.aim_left()
        self.turret_controls.aim_at_heading(next_heading)

        heading = self.status.turret_heading

        distance = calculate_distance(position, enemy.current_pos())
        angle_allowed = (105 - distance) / 5

        if within_degrees(angle_allowed, heading, next_heading):
            self.turret_controls.fire()
        def bfs_search():
            truck_x, truck_y = self.depo_coords
            visited = set()
            for i in range(self.num_vehicles):
                truck_visit = set()
                capacity, distance, truck_path = self.vehicle_map[i]
                while len(truck_visit) < self.num_customers:
                    next_customer_distance = float("inf")
                    next_customer_index = None

                    for i in range(self.num_customers):
                        customer_idx, customer_demand, customer_x, customer_y = self.customer_info[
                            i]
                        if i in truck_visit or i in visited: continue
                        if capacity - customer_demand < 0:
                            truck_visit.add(customer_idx)
                            continue

                        customer_distance = calculate_distance(
                            truck_x, truck_y, customer_x, customer_y)
                        if customer_distance < next_customer_distance:  #try reversing the order as well
                            next_customer_index = customer_idx
                            next_customer_distance = distance

                    if not next_customer_index or capacity == 0:
                        self.vehicle_map[i] = capacity, distance, truck_path
                        break

                    capacity -= customer_demand
                    distance += customer_distance
                    truck_path.add(next_customer_index)
                    visited.add(next_customer_index)
                    truck_visit.add(next_customer_index)
                    truck_x = customer_x
                    truck_y = customer_y
            return visited

            visited = bfs_search()
            if len(visited) < self.num_customers:
                return False
            all_truck_paths = [[] for x in self.num_vehicles]
            total_distance_traveled = 0
            for vehicle_idx, _, distance, truck_path in self.vehicle_map.items(
            ):
                all_truck_paths[vehicle_idx] = truck_path
                total_distance_traveled += distance
            return all_truck_paths, total_distance_traveled
Ejemplo n.º 20
0
def print_kpt_L2_distance(model, dataloader, kpt_keys, study_name, evaluate_mode, input_size):
    kpt_distances = []
    if evaluate_mode:
        validation_textfile = open('logs/rektnet_validation.txt', 'a')

    for x_batch, y_hm_batch, y_point_batch, _, image_shape in dataloader:
        x_batch = x_batch.to(device)
        y_hm_batch = y_hm_batch.to(device)
        y_point_batch = y_point_batch.to(device)

        output = model(x_batch)

        pred_points = output[1]*x_batch.shape[1]
        pred_points = pred_points.data.cpu().numpy()
        pred_points *= input_size
        target_points = y_point_batch*x_batch.shape[1]
        target_points = target_points.data.cpu().numpy()
        target_points *= input_size

        kpt_dis = calculate_distance(target_points, pred_points)

        ##### for validation knowledge of avg kpt mse vs BB size distribution #####
        if evaluate_mode:
            height,width,_ = image_shape
            print(width.numpy()[0],height.numpy()[0])
            print(kpt_dis)

            single_img_kpt_dis_sum = sum(kpt_dis) 
            validation_textfile.write(f"{[width.numpy()[0],height.numpy()[0]]}:{single_img_kpt_dis_sum}\n")
        ###########################################################################

        kpt_distances.append(kpt_dis)
    if evaluate_mode:
        validation_textfile.close()
    final_stats, total_dist, final_stats_std = calculate_mean_distance(kpt_distances)
    print(f'Mean distance error of each keypoint is:')
    for i, kpt_key in enumerate(kpt_keys):
        print(f'\t{kpt_key}: {final_stats[i]}')
    print(f'Standard deviation of each keypoint is:')
    for i, kpt_key in enumerate(kpt_keys):
        print(f'\t{kpt_key}: {final_stats_std[i]}')
    print(f'Total distance error is: {total_dist}')
    ##### updating best result for optuna study #####
    result = open("logs/" + study_name + ".txt", "w" )
    result.write(str(total_dist))
    result.close() 
    ###########################################
Ejemplo n.º 21
0
	def calculate_total_distance(self,solution_flat):
		total_distance_traveled = 0

		_,_,start_x,start_y = self.customer_info[0]

		for l in solution_flat:
			if l == -1:
				_,_,end_x,end_y = self.customer_info[0]
			else:
				_,_,end_x,end_y = self.customer_info[l]

			total_distance_traveled += calculate_distance(start_x, start_y, end_x, end_y)

			start_x = end_x
			start_y = end_y

		return total_distance_traveled
Ejemplo n.º 22
0
def create_csv_network_with_word2vec(file_name, users_df):
    with open(file_name, 'w') as file:
        csv_writer = csv.writer(file)
        word2vec_our_model = word2vec.get_model(
            str(SOURCE / 'Embedding/our.corpus.word2vec.model'))
        word2vec_wiki_model = word2vec.get_model(
            str(SOURCE / 'Embedding/wiki.he.word2vec.model'))
        csv_writer.writerow(['Node A', 'Node B', 'Weight'])
        writers_list = users_df['writer'].tolist()
        for i, writer_1 in enumerate(writers_list):
            for j in range(i + 1, len(writers_list)):
                writer_2 = writers_list[j]
                writer_1_vector = word2vec.get_post_vector(
                    word2vec_our_model, word2vec_wiki_model, users_df.loc[
                        users_df['writer'] == writer_1]['text'].item())
                writer_2_vector = word2vec.get_post_vector(
                    word2vec_our_model, word2vec_wiki_model, users_df.loc[
                        users_df['writer'] == writer_2]['text'].item())
                csv_writer.writerow([
                    writer_1, writer_2,
                    utils.calculate_distance(writer_1_vector, writer_2_vector)
                ])
Ejemplo n.º 23
0
def main(file,
         note_file=None,
         note_starts_file=None,
         plot_starts=False,
         plot_fft_indices=[]):
    # If a note file and/or actual start times are supplied read them in
    actual_starts = []
    if note_starts_file:
        with open(note_starts_file) as f:
            for line in f:
                actual_starts.append(float(line.strip()))

    actual_notes = []
    if note_file:
        with open(note_file) as f:
            for line in f:
                actual_notes.append(line.strip())

    song = AudioSegment.from_file(file)
    song = song.high_pass_filter(80, order=4)

    starts = predict_note_starts(song, plot_starts, actual_starts)

    predicted_notes = predict_notes(song, starts, actual_notes,
                                    plot_fft_indices)

    print("")
    if actual_notes:
        print("Actual Notes")
        print(actual_notes)
    print("Predicted Notes")
    print(predicted_notes)

    if actual_notes:
        lev_distance = calculate_distance(predicted_notes, actual_notes)
        print("Levenshtein distance: {}/{}".format(lev_distance,
                                                   len(actual_notes)))
Ejemplo n.º 24
0
def applyAugmentedComponents(homography, image_base_display,
                             image_test_display):

    if DEBUG: print("Loading Points of Interest from Database")
    points_of_interest = db.load_db(DB_POI)

    if DEBUG: print("Calculating inverse homography")
    inverse = np.linalg.inv(homography)

    if DEBUG: print("Calculating important")
    heigth, width = image_test_display.shape[:2]
    xCenter = int(round(width / 2.0))
    yCenter = int(round(heigth / 2.0))

    if DEBUG: print("Placing center")
    disp.place_center(image_test_display, xCenter, yCenter)

    if DEBUG: print("Mapping center to original image")
    xOriginal, yOriginal = utils.map_coordinates(inverse, xCenter, yCenter)

    closest_point = {
        'name': None,
        'distance': 9999,
        'x': 0,
        'y': 0,
        'originX': 0,
        'originY': 0
    }

    if DEBUG: print("Finding closest interest point")
    for name, point in points_of_interest.items():
        dist = utils.calculate_distance(xOriginal, yOriginal, point['x'],
                                        point['y'])
        pX, pY = utils.map_coordinates(homography, point['x'], point['y'])

        print(dist, pX, pY, name, width, heigth)

        if (dist < closest_point['distance'] and pX >= 0 and pX < width
                and pY >= 0 and pY < heigth):
            closest_point['name'] = name
            closest_point['distance'] = dist
            closest_point['x'] = pX
            closest_point['y'] = pY
            closest_point['originX'] = point['x']
            closest_point['originY'] = point['y']

    if DEBUG: print("Calculationg real distance")
    if (closest_point['name'] is not None):
        distance_km = 290 * closest_point['distance'] / 57

    if DEBUG: print("Placing closest point")
    if (closest_point['name'] is not None):
        if CIRCLE:
            disp.place_intereset_point(image_test_display, closest_point)
        else:
            pyr.calculate_pyramid(homography, image_test_display,
                                  closest_point['x'], closest_point['y'])
        disp.place_distance_and_name(
            image_test_display,
            closest_point,
            distance_km,
        )

    if DEBUG: print("Placing compass")
    disp.place_compass(inverse, image_test_display, xCenter, yCenter,
                       closest_point['x'], closest_point['y'])

    if DEBUG: print("Getting images of point")
    if (closest_point['name'] is not None):
        disp.create_slideshow(closest_point['name'], distance_km, IMAGE_FOLDER)

    cv.imshow("Augmented", image_test_display)
    cv.waitKey(0)
Ejemplo n.º 25
0
def search_operation(form, db, session):
        subject = form["subject"]
        day = form["0-day"]

        print form
        print session

        tutor_list = db.tutors.find({"%s"%subject:True, "%s"%day:True})

        tutor_ret = [] # list of tutors to be returned

        #for each tutor on the new list, give them a score based on secondary features
        for tutor in tutor_list:
                print tutor
                if tutor["complete"] == 1:
                        match_score = 0.0
                        email = tutor['email']
                        addresses = []
                        #find the days for which addresses work
                        try:
                                tutee_loc = form["0-address"]
                                
                                print tutor
                        
                                tutee_address = session[tutee_loc.capitalize() + "_Address"]
                                print tutee_address
                                        
                                tutee_start = float(form["0-start_hour"]) + (float(form["0-start_minute"]) * .01)
                                if form["0-start_type"] == "PM":
                                        tutee_start += 12

                                        

                                tutee_end = float(form["0-end_hour"]) + (float(form["0-end_minute"]) * .01)
                                if form["0-end_type"] == "PM":
                                        tutee_end += 12
                                               
                                       
                                best_time = -99999
                                for d in tutor['days'][day]:
                                        distances = []
                                        print d['addresses']
                                        for a in d['addresses']:
                                                tutor_address = tutor[a.capitalize() + "_Address"]
                                                print tutor_address
                                                dist = 0.0
                                                if (tutor_address["zipcode"] == tutee_address["zipcode"]):
                                                        dist += 4.0
                                                distance = calculate_distance(tutor_address, tutee_address)
                                                dist += float(3 - distance)
                                                distances.append(dist)
                                        print distances
                                        score = max(distances)
                                        

                                        tutor_start = float(d["start_hour"]) + (float(d["start_min"]) *.01)
                                        if d["start_type"] == "PM":
                                                tutor_start += 12
                                        
                                        tutor_end = float(d["end_hour"]) + (float(d["end_min"]) *.01)
                                        if d["end_type"] == "PM":
                                                tutor_end += 12 

                                        if (tutee_end > tutor_start):
                                                score += float(tutee_end - tutor_start) * 5
                                        if (tutee_end > tutor_end):
                                                score -= float(tutee_end - tutor_end) * 5
                                        if (tutee_start > tutor_start):
                                                score -= float(tutee_start - tutor_start) * 5
                                        if (score > best_time):
                                                best_time = score
                                match_score += best_time
                        except:
                                pass
                        
                        if tutor['school'] == session['school']:
                                match_score += 1.0 # one point for going to the same school
                        match_score += float(int(tutor['grade']) - int(session['grade']))/4 #An older tutor is preferable
                        update_tutor(tutor['email'], {'match_score':match_score}, db)

        tutors = db.tutors.find({"match_score": {"$exists":True, "$nin":[0.0]}})
        tutors.sort("match_score")
        tutor_ret = []
        for t in tutors:
                tutor_ret.append(t)
                update_tutor(t['email'], {'match_score':0.0}, db) #clear the match scores of all
        return tutor_ret
def shortest_path_a_star(start_node, end_node, input_data_path, output_file):
    """Main function for A* shortest path
        
        `start_node` and `end_node` are ('key', 'value') format.
        `input_data_path` is a path to directory with nodes and edges layer.
        `output_file` is a path to the output shape file.
    """
    # Read graph
    G = nx.Graph(nx.read_shp(input_data_path, strict=False, geom_attrs=True)) # Read and convert to Graph
    graph_summary(G)

    # Get start and end node
    start = get_nodes(G, start_node[0], start_node[1])[0]
    end = get_nodes(G, end_node[0], end_node[1])[0]
    print("Start node:")
    print_node(G, start)
    print("End node:")
    print_node(G, end)

    # Get landmark node
    landmark_nodes = get_nodes(G, 'landmark', 1)
    # for landmark_node in landmark_nodes:
    #     print(G.node[landmark_node]['nodeID'], G.node[landmark_node]['landmark'])

    # Remove landmark that has bigger distance than the starting point to end
    #TODO: ????

    # Get transit node
    current_node = start
    unvisited_landmarks = deepcopy(landmark_nodes)
    path = [start]
    finish = False
    while not finish:
        current_distance_to_end = calculate_distance(current_node, end)

        # order distance
        # get distance for all unvisited landmarks from the current node
        # landmark_distance_dict = {node: calculate_distance(current_node, node) for node in unvisited_landmarks}
        landmark_distance_dict = {node: calculate_distance(current_node, node) + calculate_distance(node, end) for node in unvisited_landmarks}
        # sort the distance
        sorted_landmark_distance_dict = sorted(landmark_distance_dict.items(), key=operator.itemgetter(1))
        # No more landmarks, it means finish
        if len(sorted_landmark_distance_dict) == 0:
            finish = True
        for landmark_distance in sorted_landmark_distance_dict:
            # get landmark to end distance
            landmark_end_distance = calculate_distance(landmark_distance[0], end)
            # compare the `current_node to end distance` with the `landmark to end distance`
            # TODO: ????
            if current_distance_to_end < landmark_end_distance or calculate_distance(current_node, landmark_distance[0]) > current_distance_to_end:
                # the current node distance 
                finish = True
                continue
            else:
                path.append(landmark_distance[0])
                current_node = landmark_distance[0]
                unvisited_landmarks.remove(current_node)
                finish = False
                break
    print('Path')
    path.append(end)
    for landmark_node in path:
        print(G.node[landmark_node]['nodeID'], G.node[landmark_node]['landmark'], landmark_node)
    
    # Build full path from the path using A*
    full_path = []
    i = 0
    for i in range(len(path) - 1):
        shortest_landmark_path = nx.astar_path(G, path[i], path[i+1], heuristic=calculate_distance, weight='length')
        full_path.extend(shortest_landmark_path[:-1])

    # Adding end node
    full_path.append(end)
    # print('Full path')
    # for node in full_path:
    #     print(G.node[node]['nodeID'], G.node[node]['landmark'], node)

    # Clean path from duplicated node, this algorithm work since the path is continue
    if len(full_path) != len(set(full_path)):
        unduplicate_path = []
        skip = False
        current_node = None
        for node in full_path:
            if not skip:
                if full_path.count(node) == 1:
                    # Always add node with single occurence
                    unduplicate_path.append(node)
                else:
                    # Add the first node that has more than one occurence
                    unduplicate_path.append(node)
                    # Mark skip as true for the next nodes
                    skip = True
                    # Store the first duplicate node
                    current_node = node
            else:
                if node == current_node:
                    # Found another current_node
                    # Remove the skip flag
                    skip = False
                    current_node = None
                else:
                    # Always skip until found another current_node
                    pass

        full_path = unduplicate_path

    return full_path
Ejemplo n.º 27
0
 def score(enemy):
     dist_score = calculate_distance(self.position,
                                     enemy.current_pos()) / 100
     hp_score = enemy.health * 0.1
     return dist_score * hp_score
Ejemplo n.º 28
0
m_earth = 5.972 * 10**24
M_0 = 1.989 * 10**30
astronomical_unit = 1.496 * 10**11
v0 = 3.0 * 10**4
G = 6.67408 * 10**(-11)
step = 1.0
mass_coords = (0.0, 0.0)

# starting conditions, x-y plane
# start at "12 o'clock"
x0 = 0.0
y0 = 1.0 * astronomical_unit
vx0 = v0
vy0 = 0.0

r0 = calculate_distance((x0, y0), mass_coords)
print(r0)
# starting conditions
x_starting_conds = np.array([x0, vx0])
y_starting_conds = np.array([y0, vy0])
print("x0:", x_starting_conds)
print("y0:", y_starting_conds)

# first step
x_change = runkut_step(r0, vx0, M=M_0, h=step)
y_change = runkut_step(r0, vy0, M=M_0, h=step)
x_new_conds = x_starting_conds + x_change
y_new_conds = y_starting_conds + y_change
print("x1:", x_new_conds)
print("y1:", y_new_conds)