Пример #1
0
def all_distance(SavedList):
    for s_path in SavedList:
        path = upper_path + '/DataBase/' + s_path
        [stj, fname0, fname1] = s_path.split('/')
        acts = Load.fname2act(fname0)
        hou_dict = Load.load_se_map(stj, fname0, fname1)
        rooms, T_Bs, furnitures, doors, walls, lims = Load.dic2house(hou_dict)
        T_B_in, T_B_walls = Dis.T_B2obj_W(T_Bs, rooms)
        Dis.mod_walls(walls, T_B_walls)
        discom = Dis.cal_dis_val(rooms, furnitures, walls, lims, t_b_in=T_B_in)
        X0, Y0 = lims[0][0] - edge, lims[1][0] - edge
        destinations = Dest.cal_destinations(rooms, furnitures, doors, discom,
                                             X0, Y0)
        max_diss_d = {}
        connectflag = 0
        for act in acts:
            s_nodes = destinations[act]
            topo = Dist.topology(discom)
            distance, max_dis = Dist.weighted_dijistra(s_nodes, topo, discom)
            if connectflag == 0:
                che_con, e_act = Dist.connect_check(distance, max_dis,
                                                    destinations)
                if che_con: connectflag = 1
                else: return False, e_act, s_path
            max_diss_d[act] = max_dis
            f_name = act + '_distance'
            HSa.save_filed(f_name, path, '%7.2f', distance)
        HSa.save_filed('Discomfortable_value', path, '%5.2f', discom)
        HSa.save_normaljson(path, destinations, 'Destinations')
        HSa.save_normaljson(path, max_diss_d, 'Max_Distances')
    return True, None, None
Пример #2
0
    def buttonClick(self):
        # grab the input
        value = float(self.ent_input.get())
        lbl = self.inp_unit

        # create a distance object
        distance = Distance(value, lbl)

        # convert it
        lbl = self.outp_unit
        converted = distance.convert(lbl)

        # display to output
        self.lbl_results.config(text=str(converted))
Пример #3
0
def main():
    """Our main function as user interface, you just need to run this function
    to get all the result from our function"""
    while True:
        Input = input(
            "Hi Dear User, You have already choosed the datafile and now \
which Features do you want to know?\n\n \t1.\tRoute of your journey\n \t2.\tBumps in your journey\n \
\t3.\tDelay of your journey\n \t4.\tDistance your journey covered\n \t5.\tAverage speed of your journey\n \t6.\t\
Sound Intensity Heatmap\n \t7.\tDevice taken out of the pocket\n \t8.\tMeans of transpotations in your journey \n \
\t9.\tHow many stops you have in your journey\n \t10.\tYou don not want more informations\n"
        )
        if int(Input) == 1:
            gmplot_show.main()
            continue
        if int(Input) == 2:
            bumps.main()
            continue
        if int(Input) == 3:
            Delays.main()
            continue
        if int(Input) == 4:
            Distance.main()
            continue
        if int(Input) == 5:
            Average_speed.main()
            continue
        if int(Input) == 6:
            time, sound = app_func.get_sound(data_import.TIME,
                                             data_import.SOUND_LEVEL)
            sound_f = app_func.filt_data(sound)
            app_func.plot_heatmap(data_import.LATITUDES, data_import.LONGITUDES,\
                                  sound_f, 'gm_sound_levels.html')
            print("Wow, quite loud! Better bring some earplugs!")
            continue
        if int(Input) == 7:
            indexes = app_func.device_out(data_import.LIGHT)
            app_func.plot_maploc(data_import.LATITUDES.iloc[indexes], \
                                 data_import.LONGITUDES.iloc[indexes],\
                    'gm_phone_out.html')
            print("Device taken out of the pocket at these locations.")
            continue
        if int(Input) == 8:
            means_of_transport.main()
            continue
        if int(Input) == 9:
            no_stops_function.main()
            continue
        if int(Input) == 10:
            print("Thanks so much for using our app, Bye Bye")
            break
Пример #4
0
def calc_distance(row, columns, results, start_index, end_index, graph):
    x = 0
    Distance.generate_globals(graph)
    while (start_index < end_index):
        if ((start_index % 100) == 0):
            print("Completed: ", start_index, "/", end_index)
        line, start, dest = Input.read_line_given(columns, row[x].split(','))
        #dist = Distance.shortest_path(start,dest,graph)

        dist = Distance.shortest_path_osmnx(start, dest, graph)
        if (type(dist) is float):
            results[start_index] = dist
        start_index = start_index + 1
        x = x + 1
    print("Completed: ", start_index, "/", end_index)
Пример #5
0
def fcfs_nearest_idle(av_fleet, customers, t):
    idle_avs = list(j_veh for j_veh in av_fleet
                    if j_veh.status in ("idle", "relocating"))
    unassign_cust = list(i_cust for i_cust in customers
                         if i_cust.status == "unassigned")

    used_vehicles = []
    count_p = -1
    for i_cust in unassign_cust:
        count_p += 1
        min_dist = Set.inf
        win_veh_index = -1
        veh_index = -1
        for j_av in idle_avs:
            veh_index += 1
            dist = Distance.dist_manhat_pick(i_cust, j_av)
            # make sure that two persons aren't assigned to same vehicle
            if dist < min_dist and not (j_av.vehicle_id in used_vehicles):
                win_veh_index = veh_index
                min_dist = dist
        if win_veh_index >= 0:
            win_vehicle = idle_avs[win_veh_index]
            used_vehicles.append(win_vehicle.vehicle_id)

            temp_veh_status = "base_assign"
            Vehicle.update_vehicle(t, i_cust, win_vehicle, Regions.SubArea,
                                   temp_veh_status)
            Person.update_person(t, i_cust, win_vehicle)
    return
def dist_avg(ptdata,Ci, Cj):
    # print('Ci',Ci)
    # print('Cj',Cj)
    if Ci==Cj:
        return 0
    n=len(ptdata)
    ptsInClusti=[]
    ptsInClustj=[]
    for i in range(n):
        if Ci==ptdata[i].clusterMark:
            ptsInClusti.append(ptdata[i])
        if Cj==ptdata[i].clusterMark:
            ptsInClustj.append(ptdata[i])
    # print('ptsInClusti',ptsInClusti)
    # print('ptsInClustj',ptsInClustj)
    leni=len(ptsInClusti)
    lenj=len(ptsInClustj)
    maxlen=max(leni,lenj)
    sumij=0
    for i in range(leni):
        for j in range(lenj):
            distij=Distance(ptsInClusti[i],ptsInClustj[j]).dis
            sumij+=distij
    avgdist=sumij/maxlen
    # print('Ci,Cj簇间平均距离',avgdist)
    return avgdist
Пример #7
0
def _rr_row_rep(s, size, vd, e, crp_tmp, curRange):
    dist_m = np.zeros((size, size))

    for i in curRange:
        row_rep_T = pd.concat([s.iloc[i, :]] * size, axis=1, ignore_index=True)
        row_rep = row_rep_T.transpose()

        dist = Distance.Minkowski(row_rep, s, vd)
        dist_m[i, :] = dist.T

    dist_m_f = dist_m.flatten()
    dist_m_f.sort()

    s_x = dist_m_f[np.int(e * len(dist_m_f))]

    for i in curRange:
        diff_threshold_norm = s_x - dist_m[i, :].T

        diff_threshold_norm = np.ma.MaskedArray(diff_threshold_norm < 0).data
        #diff_threshold_norm[diff_threshold_norm >= 0] = 0
        #diff_threshold_norm[diff_threshold_norm < 0] = 1

        crp_tmp[size - 1 - i, :] = diff_threshold_norm.T

    return np.fliplr(crp_tmp.T)
Пример #8
0
def spoken_term_detection_truncated(keywords, utterances, left_encode_num,
                                    right_encode_num, distance_type,
                                    output_dir):
    for i in range(len(keywords)):
        keyword_sampling_feature = keywords[i].sampling_feature
        keyword_phone_num = keyword_sampling_feature.shape[0]
        (left_position,
         right_position) = get_truncated_position(keyword_phone_num,
                                                  left_encode_num,
                                                  right_encode_num)
        keyword_indexes_selected = get_real_indexes(range(keyword_phone_num),
                                                    left_encode_num,
                                                    right_encode_num)
        keyword_sampling_feature_selected = keyword_sampling_feature[
            keyword_indexes_selected, :]
        output_file = output_dir + keywords[i].getFileId() + ".result"
        fid = open(output_file, "w")
        for j in range(len(utterances)):
            utterance_sampling_feature = utterances[j].sampling_feature
            utterance_phone_num = utterance_sampling_feature.shape[0]
            utterance_indexes_selected = get_real_indexes(
                range(utterance_phone_num), left_encode_num, right_encode_num)
            utterance_sampling_feature_selected = utterance_sampling_feature[
                utterance_indexes_selected, :]
            distance = Distance.distance(
                keyword_sampling_feature_selected[:, left_position:
                                                  right_position],
                utterance_sampling_feature_selected[:, left_position:
                                                    right_position],
                distance_type,
                sub_num=PHONE_LEN)
            fid.writelines(str(-distance.min()) + "\n")
        fid.close()
        log.Log("finished the std for keyword " + str(keywords[i].getFileId()))\
Пример #9
0
def main():
    LATITUDE = data_import.LATITUDES
    LONGITUDE = data_import.LONGITUDES
    All_Distance = Distance.distance_calculation(LATITUDE, LONGITUDE)
    averagespeed = average_speed(All_Distance, data_import.TOTAL_TIME / 60000)

    print("The average speed of your journey is %f km/h" % (averagespeed * 60))
Пример #10
0
 def __init__(self, csv_list):
     # the node are addresses
     self.nodes = []
     # edge two addresses in the distance between them
     self.edges = []
     location1 = 0
     location2 = 0
     for row in csv_list:
         name = row[0]
         street = row[1]
         city = row[2]
         state = row[3]
         zip = row[4]
         address = Address(street, city, state, zip)
         self.nodes.append(address)
         location2 = 0
         # distances in the csv file begin here
         for column in row[5:]:
             try:
                 edge = Distance(column, self.nodes[location1], self.nodes[location2])
                 self.edges.append(edge)
                 location2 = location2 + 1
             except IndexError:
                 pass
             continue
         location1 = location1 + 1
Пример #11
0
def divide_score(class_1_data, class_1_label, class_2_data, class_2_label, K=None, score=mean_center_distance_score):
    """
    use the above methods to evaluate the score of a certain partition
    :param class_1_data:
    :param class_1_label:
    :param class_2_data:
    :param class_2_label:
    :param K:
    :param score:
    :return:
    """
    if K is None:
        K = len(np.unique(class_1_label)) + len(np.unique(class_2_label))
    if 1 < len(np.unique(class_1_label)) < K - 1:
        class_1_s = score(class_1_data, class_1_label)
    else:
        class_1_s = 0
    if 1 < len(np.unique(class_2_label)) < K - 1:
        class_2_s = score(class_2_data, class_2_label)
    else:
        class_2_s = 0
    class_1_center = np.average(class_1_data, axis=0)
    class_2_center = np.average(class_2_data, axis=0)
    class_1_2_s = Distance.euclidean_distance(class_1_center, class_2_center)
    if 1 < len(np.unique(class_1_label)) < K - 1:
        confidence_score = class_1_2_s / (class_1_s + class_2_s)
    else:
        confidence_score = 0
    return confidence_score
Пример #12
0
def follow_distance(debug=False):
    DistanceLeft = Distance.measure_distance(config.US_LEFT, False)
    DistanceMid = Distance.measure_distance(config.US_CENTER, False)
    DistanceRight = Distance.measure_distance(config.US_RIGHT, False)

    if DistanceRight <= config.Distance_MinValue:
        config.dist_error = -4
        if debug:
            print("DistRight too small, go left")
    elif DistanceLeft <= config.Distance_MinValue:
        config.dist_error = 4
        if debug:
            print("DistLeft too small, go right")
    elif DistanceRight > DistanceMid and DistanceRight > DistanceLeft:
        config.dist_error = 3
        if debug:
            print("DistRight big, go right")
    elif DistanceMid > DistanceRight and DistanceMid > DistanceLeft:
        config.dist_error = 0
        if debug:
            print("Distmid big, go FW")
    elif DistanceLeft > DistanceMid and DistanceLeft > DistanceRight:
        config.dist_error = -3
        if debug:
            print("DistLeft big, go left")

    P = config.dist_error
    config.dist_integrative = config.dist_integrative + config.dist_error
    D = config.dist_error - config.dist_previous_error
    PIDvalue = (config.dist_kp * P) + (config.dist_ki * config.dist_integrative) + (config.dist_kd * D)

    if config.dist_left_speed - PIDvalue > 100:
        config.walk_speed_left = 100
    elif config.dist_left_speed - PIDvalue < config.min_left_speed:
        config.walk_speed_left = 0
    else:
        config.walk_speed_left = config.dist_left_speed - PIDvalue

    if config.dist_right_speed + PIDvalue > 100:
        config.walk_speed_right = 100
    elif config.dist_right_speed + PIDvalue < config.min_right_speed:
        config.walk_speed_right = 0
    else:
        config.walk_speed_right = config.dist_right_speed + PIDvalue

    config.dist_previous_error = config.dist_error
Пример #13
0
    def Candidate(self, target, top=3, threshold=2):
        candidate_list = []  #node string edit_dis

        recoder_list = []
        recoder_list.append([self.m_root, self.m_root.m_key])

        while True:
            if len(recoder_list) == 0:
                break

            [cur_node, str] = recoder_list.pop()

            cut_off_distance_list = []  #distance, string
            for child in cur_node.m_child:
                str_temp = str + child.m_key
                cut_off_distance = Distance.CutOffDistance(
                    target, str_temp, threshold)
                if cut_off_distance <= threshold:
                    cut_off_distance_list.append([cut_off_distance, str_temp])
                    recoder_list.append([child, str_temp])

                if child.m_end_flag:
                    edit_distance = Distance.EditDistance(target, str_temp)
                    candidate_list.append([child, str_temp, edit_distance])

        #sort
        candidate_list.sort(key=lambda d: d[2])

        for candidate in candidate_list:
            if candidate[2] > threshold:
                candidate_list.remove(candidate)

        rtn_len = 0
        if len(candidate_list) > top:
            rtn_len = top
        else:
            rtn_len = len(candidate_list)

        rtn_list = []
        for idx in range(0, rtn_len):
            if candidate_list[idx][2] < threshold:
                #print(candidate_list[idx])
                rtn_list.append(
                    [candidate_list[idx][1], candidate_list[idx][2]])

        return rtn_list
Пример #14
0
 def test_meatureDistance(self):
     print("detect start")
     ne = NobyEyes.NobyEyes()
     dis = ne.meatureDistance()
     # 腕からの距離計算する
     dist = Distance.Distance()
     dist.calcDistanceBetween(dis)
     self.assertEqual("foo".upper(), "FOO")
Пример #15
0
def has_distance(text):
    if Distance.isOpen:
        Distance.isOpen = False
        return "你距离我 %s" % Distance.distance("上海市长宁区凯利大厦", text)
    elif text in ['你在哪', '离我多远', '距离']:
        Distance.isOpen = True
        return Distance.HELP_MSG
    else:
        return has_weather(text)
Пример #16
0
def search(img_path):
    cf = CaculateColorVector.get_color_feature(img_path)
    cfs = File_Operation.read_list_from_file('/Users/ligang/Documents/cfs.txt')
    distances = []
    for cf_tuple in cfs:
        d = Distance.distance(cf, cf_tuple[1])
        distances.append((cf_tuple[0], d))
    top_distances = heapq.nsmallest(10, distances, key=lambda x: x[1])
    print top_distances
Пример #17
0
def fcfs_smart_nn(av_fleet, customers, t):
    idle_avs = list(j_veh for j_veh in av_fleet
                    if j_veh.status in ("idle", "relocating"))
    len_avs = len(idle_avs)
    unassign_cust = list(i_cust for i_cust in customers
                         if i_cust.status == "unassigned")
    len_custs = len(unassign_cust)

    if len_avs >= len_custs:
        used_vehicles = []
        for i_cust in unassign_cust:
            win_vehicle = Vehicle.Vehicle
            min_dist = Set.inf
            for j_av in idle_avs:
                dist = Distance.dist_manhat_pick(i_cust, j_av)
                # make sure that two persons aren't assigned to same vehicle
                if dist < min_dist and j_av not in used_vehicles:
                    win_vehicle = j_av
                    min_dist = dist
            if win_vehicle.vehicle_id >= 0:
                used_vehicles.append(win_vehicle)

                temp_veh_status = "base_assign"
                Vehicle.update_vehicle(t, i_cust, win_vehicle, Regions.SubArea,
                                       temp_veh_status)
                Person.update_person(t, i_cust, win_vehicle)
    else:
        win_cust_list = []
        for j_av in idle_avs:
            min_dist = Set.inf
            win_cust = Person.Person
            for i_cust in unassign_cust:
                dist = Distance.dist_manhat_pick(i_cust, j_av)
                if dist < min_dist and i_cust not in win_cust_list:
                    win_cust = i_cust
                    min_dist = dist
            if win_cust.person_id >= 0:
                win_cust_list.append(win_cust)

                temp_veh_status = "base_assign"
                Vehicle.update_vehicle(t, win_cust, j_av, Regions.SubArea,
                                       temp_veh_status)
                Person.update_person(t, win_cust, j_av)
    return
Пример #18
0
    def restart(self):

        a = Distance.GridentDescent(center_vectors, Polygons,
                                    self.learning_rate, self.function_value,
                                    Groups)
        self.canvas.update()
        self.function_value = a
        print 'final', center_vectors, '\n' * 3, 'value', self.function_value, '\t', 'rate', self.learning_rate, '\n' * 3,

        return a
Пример #19
0
def AIC(X,Y,dtype="default"):
	YC=set(Y)
	K=len(YC)
	S=0
	for i in YC:
		CI=[X[j] for j in range(len(Y)) if Y[j]==i]
		mui=getAvgEx(CI)
		for j in CI:
			if dtype=="default":
				di=Distance(j,mui)
				dij=di.euclidean_distance()
			else:
				dij=eval(dtype)(j,mui)
			S+=dij
	FT=S
	R=len(X)
	D=len(X[0])
	AC=FT+4*K*D
	AC=math.log(AC)
	return AC	
Пример #20
0
def _row_rep(s, size, i, vd, e, crp_tmp):
    row_rep_T = pd.concat([s.iloc[i, :]] * size, axis=1, ignore_index=True)
    row_rep = row_rep_T.transpose()

    diff_threshold_norm = e - Distance.Minkowski(row_rep, s, vd)

    diff_threshold_norm = np.ma.MaskedArray(diff_threshold_norm < 0).data
    #diff_threshold_norm[diff_threshold_norm >= 0] = 0
    #diff_threshold_norm[diff_threshold_norm < 0] = 1

    crp_tmp[size - 1 - i, :] = diff_threshold_norm.T
    return np.fliplr(crp_tmp.T)
Пример #21
0
def mean_distance_score(class_data, class_label):
    """
    calculate mean distance between different samples
    :param class_data:
    :param class_label:
    :return:
    """
    center = np.mean(class_data, axis=0)
    distance_sum = 0
    for i in range(len(class_label)):
        distance_sum = distance_sum + Distance.euclidean_distance(center, class_data[i])
    return distance_sum / len(class_label)
Пример #22
0
	def getNodeNChildNodeDistance(self, neighbors, neighborsList, location, n):
		if (n.visited):
			return neighborsList
		else:

			distance = Distance.distance_on_unit_sphere(float(location[0]), float(location[1]), float(n.location[0]), float(n.location[1]))  * 3960
			n.visited = True
			
			if len(neighborsList) < neighbors:
				neighborsList[n.locationid] = distance
			else:
				neighborsList = self.getNearestNeighbors( neighborsList, distance, n)
			return neighborsList
Пример #23
0
def search(img_path):
    ulbp_f = ulbp.ulbp(img_path)
    ulbps = File_Operation.read_list_from_file('/Users/ligang/Documents/ulbp.txt')
    distances = []
    for ulbp_tuple in ulbps:
        d = Distance.distance(ulbp_f, ulbp_tuple[1])
        distances.append((ulbp_tuple[0], d))
    top_distances = heapq.nsmallest(20, distances, key=lambda x: x[1])
    dstDir = '/Users/ligang/Documents/Emilie/lbp_search_result'
    img_set_dir = '/Users/ligang/Documents/Emilie/dress'
    for top in top_distances:
        shutil.copy2(os.path.join(img_set_dir, top[0]), os.path.join(dstDir, top[0]))
    print top_distances
Пример #24
0
def menu():
    ''' Printing out the menu on the screen'''

    choice = None
    while choice != "0":
        print \
        ("""
        --------------- MENU ---------------
                
        0 - Exit
        1 - Insert/change flight data
        2 - Show current flight data
        3 - Find IATA code of your airport
        4 - Check the nearest airports 
        5 - Search one-way tickets!
        6 - Search two-way tickets!
        
        """)

        choice = input("Choose: ")
        print()

        if choice == "0":
            print("Bye bye!")
        elif choice == "1":
            Ryanair.change_parameters()
        elif choice == "2":
            Ryanair.show_parameters()
        elif choice == "3":
            Airports.airport_menu()
        elif choice == '4':
            Distance.nearby_airports()
        elif choice == "5":
            Ryanair.n_way(ways=1)
        elif choice == "6":
            Ryanair.n_way(ways=2)
        else:
            print(" !!!!!!!!! Wrong option !!!!!!!!! ")
Пример #25
0
def max_distance_score(class_data, class_label):
    """
    calculate max distance between different samples
    :param class_data:
    :param class_label:
    :return:
    """
    max_distance = -np.inf
    center = np.mean(class_data, axis=0)
    for i in range(len(class_label)):
        distance = Distance.euclidean_distance(center, class_data[i])
        if distance > max_distance:
            max_distance = distance
    return max_distance
Пример #26
0
def parse_input_file(cities_list, distance_lookup):
    f = open('distance.csv')
    input_file = csv.reader(f)
    for row in input_file:
        columns_parsed = 0
        city1 = ''
        city2 = ''
        distance = ''
        #print row
        if len(row) > 0:

            for column in row:
                #print column
                if columns_parsed == 3:
                    break
                elif len(column) > 0:
                    if (column.lower()
                            not in cities_list) and (not num_exist(column)):
                        cities_list.append(column.lower())
                    if columns_parsed == 0:
                        city1 = column.lower()
                    elif columns_parsed == 1:
                        city2 = column.lower()
                    elif columns_parsed == 2:
                        distance = column
                    columns_parsed += 1

            distance_obj = Distance(city1, city2, distance)

            if len(city1) > 0 and len(city2) > 0 and len(distance) > 0:
                #print distance_obj
                if not city1 in distance_lookup:
                    distance_lookup[city1] = [distance_obj]
                else:
                    #print 'city1-'+city1
                    #print distance_lookup[city1]
                    distance_lookup[city1].append(distance_obj)
                    #print distance_lookup[city1]
                if not city2 in distance_lookup:
                    distance_lookup[city2] = [distance_obj]
                else:
                    #print 'city2'+city2
                    #print distance_lookup[city2]
                    distance_lookup[city2].append(distance_obj)

    #print distance_lookup
    #print cities_list
    #print len(cities_list)
    return distance_lookup
def search(img_path):
    cf = CaculateColorVector.get_color_feature(img_path)
    unlbp_feature = Uniform_LBP.ulbp(img_path)

    cfs = File_Operation.read_list_from_file('/Users/ligang/Documents/cfs.txt')
    ulbps = File_Operation.read_list_from_file('/Users/ligang/Documents/ulbp.txt')

    distances = []

    for cf_tuple, ulbp_tuple in zip(cfs, ulbps):
        assert cf_tuple[0] == ulbp_tuple[0]

        d_color = Distance.distance(cf, cf_tuple[1])
        d_ulbp = Distance.distance(unlbp_feature, ulbp_tuple[1])
        d = d_color + d_ulbp

        distances.append((cf_tuple[0], d))

    top_distances = heapq.nsmallest(20, distances, key=lambda x: x[1])
    dstDir = '/Users/ligang/Documents/Emilie/colorlbp_search_result'
    img_set_dir = '/Users/ligang/Documents/Emilie/dress'
    for top in top_distances:
        shutil.copy2(os.path.join(img_set_dir, top[0]), os.path.join(dstDir, top[0]))
    print top_distances
Пример #28
0
def agg_score(class_1_data, class_1_label, class_2_data, class_2_label, score=mean_distance_score):
    """
    use the above methods to evaluate the score of a certain agglomeration
    :param class_1_data:
    :param class_1_label:
    :param class_2_data:
    :param class_2_label:
    :param score:
    :return:
    """
    class_1_distance = score(class_1_data, class_1_label)
    class_2_distance = score(class_2_data, class_2_label)
    class_1_center = np.mean(class_1_data, axis=0)
    class_2_center = np.mean(class_2_data, axis=0)
    distance_between_two_class = Distance.euclidean_distance(class_1_center, class_2_center)
    return 2 * distance_between_two_class / (class_1_distance + class_2_distance)
Пример #29
0
def normalize(referenceMapToDistVectors, verbose):
	#find the min and max value of each component
	if verbose:
		print()
		print()
	maxVector = None
	minVector = None
	for referencePath in referenceMapToDistVectors.keys():
		vector = referenceMapToDistVectors[referencePath][0]
		if(maxVector is None):
			maxVector = np.copy(vector)
		if(minVector is None):
			minVector = np.copy(vector)
		for i in range(len(vector)):
			maxVector[i] = max(vector[i], maxVector[i])
			minVector[i] = min(vector[i], minVector[i])
	
	if(verbose):
		print("Min Vector: " + str(minVector))
		print("Max Vector: " + str(maxVector))

	for referencePath in referenceMapToDistVectors.keys():
		#actually do the normalizing
		vector, spot2 = referenceMapToDistVectors[referencePath]
		for i in range(len(vector)):
			top = (float(vector[i]) - float(minVector[i]))
			bottom = (float(maxVector[i]) - float(minVector[i]))
			if(bottom == 0):
				vector[i] = 0
				if(verbose):
					print("Bottom of fraction was zero while normalizing! Top was: " + str(top))
				continue
			vector[i] = (top / bottom) * 100 #normalized between 0 and 1
		
		referenceMapToDistVectors[referencePath] = (vector, spot2)

	#now convert the distance vectors to a single number (magnitude), also insert the weights
	for referencePath in referenceMapToDistVectors.keys():
		vector, spot2 = referenceMapToDistVectors[referencePath]
		weights = Distance.getWeights()
		if verbose:
			print("Vector: " + str(vector))
			print("Vector Weighted: " + str(vector*weights))
		referenceMapToDistVectors[referencePath] = (util.getMagnitude(vector*weights), spot2)

	return referenceMapToDistVectors
Пример #30
0
def min_center_distance_score(class_data, class_label):
    """
    calculate min distance between different centers
    :param class_data:
    :param class_label:
    :return:
    """
    min_distance = np.inf
    class_center = []
    for label in np.unique(class_label):
        class_center.append(np.average([class_data[i] for i in range(len(class_label)) if class_label[i] == label], axis=0))
    for i in range(len(class_label)):
        for j in range(i+1, len(class_center)):
            distance = Distance.euclidean_distance(class_center[i], class_center[j])
            if distance < min_distance:
                min_distance = distance
    return min_distance
Пример #31
0
def moveDist(address, addressPharm):     # function to send the drone the distance it needs to fly
                    # also used for return trips

    deliveryLat = Distance.latitude(address)  # converts an address to its latitude equivalent
    deliveryLong = Distance.longtitude(address)   # converts an address to its longitude equivalent
    pharmcacyLat = Distance.latitude(addressPharm)
    pharmacyLong = Distance.longitude(addressPharm)
    flyDist = Distance.conversion(deliveryLat, deliveryLong, pharmcacyLat, pharmacyLong)
    # conversion finds the distance in miles between two longitudes and latitudes

    drone.moveForward()
    time.sleep(Distance.findtime(flyDist, speedofdrone))  # receives the time the drone must move for
def closest_cross_pair(xlist, ylist, delta):
    distObj = Distance.Distance()
    length = int(len(xlist))
    mid = xlist[length // 2][0]

    # strip is a list of y sorted points built by finding all x-coords that exist
    # within the boundries of the strip, ie mid - delta and mid + delta
    strip = [x for x in ylist if mid - delta <= x[0] <= mid + delta]

    index = 0
    # constant 7*n time
    for point in strip:
        for i in range(1, 8):
            if index + i < len(strip):
                distObj.safeAddPoints(point, strip[index + i])
        index += 1

    return distObj
Пример #33
0
def main():
    filename = sys.argv[1]
    distObj = Distance.Distance()
    plist = []

    # make a list of tuples, where each entry in the list is a (x, y) tuple
    with open(filename, 'r') as file:
        for point in file:
            p1 = int(point.strip().split(' ')[0])
            p2 = int(point.strip().split(' ')[1])
            plist.append((p1, p2))

    # closest-pair returns a distance object, class def. found in Distance.py
    final = closest_pair(plist, distObj)

    print final.getDistance()
    for i in final.getPoints():
        print(i)
    return
Пример #34
0
def find_shortest(target_poi, time, sum_time):
    j = 0
    sign_list = dict()  # poi-序号映射表
    for i in target_poi:
        sign_list[j] = i
        j += 1
    m = 0
    n = 0
    dis = []
    for m in range(0, j):
        dis.append([])
        for n in range(0, j):
            if m == n:
                continue
            else:
                # m->n 的距离
                temp = Distance.haversine(target_poi[m].get_coordinate(), target_poi[n].get_coordinate())
                # print(temp)
                dis[m].append([n, temp])
    router = list()
    all_dis = 0  # 总路径长度
    all_router_time = 0 # 总路程时间

    go_list = []
    k = 0
    for i in range(0, j-1):
        start = k
        k, t, shortest_dis = tsp(go_list, dis, k)
        all_dis += shortest_dis/1000  # 公里
        # 按平均60KM/H计算时间
        all_router_time += (shortest_dis/1000)/60  # 小时
        router.append([start, k, round(shortest_dis/1000, 2), round((shortest_dis/1000)/60, 2)])  # [0,1,dis,time]
    # print(all_dis)
    # print(all_router_time)
    # print(router)
    if all_router_time+sum_time > time:
        s = target_poi.pop()
        for i in target_poi:
            print(i.show_info())
        return find_shortest(target_poi, time, sum_time-int(s.get_play_time()))
    else:
        return router, sign_list, all_dis, all_router_time+sum_time
Пример #35
0
def separate_path(all_orders, path, condition, params):
    """
    将一个序列分离为满足条件的车辆路径
    :type all_orders: list
    :type path: list
    :type condition: dict
    :type params: dict
    """
    assert len(all_orders) - 1 == len(path)
    separate_number_list = []

    start = all_orders[0]  # 起点
    v = params['velocity']  # 速度
    stay_time = params['stay_time']  # 停留时间

    path_time = 0  # 记录每车的总时间
    path_len = len(path)  # 路径长度,不包括起点
    i = 0  # 路径中 node 的指针
    pre = start
    total_distance = 0
    while i < path_len:
        curr_node = all_orders[path[i]]
        distance = Distance.get_distance(pre['lat'], pre['lng'], curr_node['lat'], curr_node['lng'])
        time = distance / v
        if path_time + time > condition["time"]:
            # 重置迭代变量
            if pre == start:
                raise RuntimeError("经纬度{}离原点{}太远".format(curr_node, pre))
            path_time = 0
            pre = start
            separate_number_list.append(i)
        else:
            pre = curr_node
            path_time += time + stay_time
            total_distance += distance
            i += 1

    separate_number_list.append(i)
    return {"separate_number_list": separate_number_list, "distance": total_distance}
def main(argv):
	if len(argv) != 5:
		print('USAGE: <native pdb file> <pdb file> <model limit> <output file prefix> <lrmsd criteria>')
		sys.exit(2)
	try: #TODO: add better checking here
		native_in = str(argv[0])
		file_in = str(argv[1])
		nr_models = int(argv[2])
		output_prefix = str(argv[3])
		lrmsd_criteria = int(argv[4])
	except:
		print('USAGE: <native pdb file> <pdb file> <model limit> <output file prefix> <lrmsd criteria>')
		sys.exit(2)
	#Create lists of conformations	
	labels, nativeconformation, conformations = Parser.PDB(native_in, file_in, nr_models)
	#Sort into positive and negative sets using lRMSD 
	withinlRMSD, morethanlRMSD = Distance.sortBylRMSDs(nativeconformation, conformations, lrmsd_criteria)
	
	#output image of native graph
	#nativeGraph = nx.Graph()
	#curr_conf = nativeconformation[0]
	#for j in range(len(curr_conf)-RES_DISTANCE):
	#	for k in range(j+RES_DISTANCE, len(curr_conf)):
	#		atom1 = curr_conf[j]
	#		atom2 = curr_conf[k]
	#		#add nodes to graph with labels
	#		nativeGraph.add_node(j)
	#		nativeGraph.node[j]['aminoAcid'] = labels[j]
	#		nativeGraph.add_node(k)
	#		nativeGraph.node[k]['aminoAcid'] = labels[k]
	#		#find euclidean distance between atoms
	#		d = Distance.euclideanDistance(atom1, atom2)
	#		#if less than BIN_CRITERIA, add edge
	#		if(d <= BIN_CRITERIA):
	#			nativeGraph.add_edge(j, k, distance=d)
	#printGraph(nativeGraph, 'Output/PosGraphs/native')
	
	#output graph attributes for each data set
	#Note: removed newline='' from open() for linux
	dt = time.strftime("_%Y%m%d-%H%M%S")
	with open('Output/'+output_prefix+dt+'.csv', 'w') as csvfile:
		writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
		writer.writerow(['num_edges', 'density','avg_degree','percent_endpoints','energy', 'second_eigen', 'unique_eigen', 'spectral_rad', 'inverse_product',
			'link_impurity', 'neighborhood_impurity', 'avg_closeness', 'avg_clustering', 'small_worldness','eccentricity','diameter',
			'radius','%central_nodes', '%Hydrophobic_center', 'near_native'])
		#Positive Data Set
		for i in range(len(withinlRMSD)):
			graph = nx.Graph()
			curr_conf = withinlRMSD[i]
			for j in range(len(curr_conf)-RES_DISTANCE):
				for k in range(j+RES_DISTANCE, len(curr_conf)):
					atom1 = curr_conf[j]
					atom2 = curr_conf[k]
					#add nodes to graph with labels
					graph.add_node(j)
					graph.node[j]['aminoAcid'] = labels[j]
					if(labels[j] in HPHOBIC):
						graph.node[j]['hydro'] = 'phobic'
					else:
						graph.node[j]['hydro'] = 'philic'
					graph.add_node(k)
					graph.node[k]['aminoAcid'] = labels[k]
					if(labels[k] in HPHOBIC):
						graph.node[k]['hydro'] = 'phobic'
					else:
						graph.node[k]['hydro'] = 'philic'
					#find euclidean distance between atoms
					d = Distance.euclideanDistance(atom1, atom2)
					#if less than BIN_CRITERIA, add edge
					if(d <= BIN_CRITERIA):
						graph.add_edge(j, k, distance=d)
			##FOR TESTING ONLY
			#printGraph(graph, 'Output/PosGraphs/pos_'+str(i))
			#################
			#once graph is done, create attribute vector
			attributes = graphAttributes(graph)
			##FOR TESTING##
			#attributes = []
			#if(not nx.is_connected(graph)):
			#	print("Graph " + i + "from within is not connected")
			#	sys.exit(2)
			#else:
			#	attributes.append(nx.is_connected(graph))
			#add 1 to the end since near native
			attributes.append(1)
			#and output to file as row
			writer.writerow(attributes)
		#Negative Data Set
		for i in range(len(morethanlRMSD)):
			graph = nx.Graph()
			curr_conf = morethanlRMSD[i]
			for j in range(len(curr_conf)-RES_DISTANCE):
				for k in range(j+RES_DISTANCE, len(curr_conf)):
					atom1 = curr_conf[j]
					atom2 = curr_conf[k]
					#add nodes to graph with labels
					graph.add_node(j)
					graph.node[j]['aminoAcid'] = labels[j]
					if(labels[j] in HPHOBIC):
						graph.node[j]['hydro'] = 'phobic'
					else:
						graph.node[j]['hydro'] = 'philic'
					graph.add_node(k)
					graph.node[k]['aminoAcid'] = labels[k]
					if(labels[k] in HPHOBIC):
						graph.node[k]['hydro'] = 'phobic'
					else:
						graph.node[k]['hydro'] = 'philic'
					#find euclidean distance between atoms
					d = Distance.euclideanDistance(atom1, atom2)
					#if less than BIN_CRITERIA, add edge
					if(d <= BIN_CRITERIA):
						graph.add_edge(j, k, distance=d)
			##FOR TESTING ONLY
			#printGraph(graph, 'Output/NegGraphs/neg_'+str(i))
			#################
			#once graph is done, create attribute vector
			attributes = graphAttributes(graph)
			##FOR TESTING ONLY##
			#if(not nx.is_connected(graph)):
			#	print("Graph " + i + "from morethan is not connected")
			#	sys.exit(2)
			#else:
			#	attributes.append(nx.is_connected(graph))
			#add 0 to the end since decoy
			attributes.append(0)
			#and output to file as row
			writer.writerow(attributes)
		print("ATTRIBUTES HAVE BEEN OUTPUTTED")
Пример #37
0
def getRandom() :
	return randint(0,15)
	
startValue = 0.0
data = 'false'
orderflag = 0

while True :
	data = serverflag.parseHtml()
	print data
	if data == 'true' :

		#distance = getRandom();
		
		distance = sensor.getDistance()
		print distance

		if initialvalue.isIntialNotSet():
		#if startValue == 0:
			startValue =  distance
			
			#startValue = 15.0
			initialvalue.setInitialValue(startValue)

		else:
			startValue = initialvalue.getInitialValue()

		percnt = ((startValue-distance)/startValue)*100
		print percnt
		file2_contents = file2.read().split('\n')
		f2contents = file2_contents[1].split(',') # index 0 contains feature headers

		data1 = []
		data2 = []
		for k in range(0, len(f1contents)):
			try:
				f1contents[k] = float(f1contents[k])
				data1.append(f1contents[k])
			except:
				pass
		for k in range(0, len(f2contents)):
			try:
				f2contents[k] = float(f2contents[k])
				data2.append(f2contents[k])
			except:
				pass

		indices = Distance.prune(data1, data2)
		#print("Euclidean: " + str(Distance.euclidean_distance(data1, data2, indices)))
		output.write(files[i] + "," + files[j] + "," + "euclidean" + "," + str(Distance.euclidean_distance(data1, data2, indices)) + "\n")
		#print("City: " + str(Distance.city_distance(data1, data2)))
		output.write(files[i] + "," + files[j] + "," + "city" + "," + str(Distance.city_distance(data1, data2)) + "\n")
		#print("Chebychev: " + str(Distance.chebychev_distance(data1, data2)))
		output.write(files[i] + "," + files[j] + "," + "chebychev" + "," + str(Distance.chebychev_distance(data1, data2)) + "\n")
		#print("Cosine: " + str(Distance.cosine_difference(data1, data2)))
		output.write(files[i] + "," + files[j] + "," + "cosine" + "," + str(Distance.cosine_difference(data1, data2)) + "\n")
		#print("Correlation: " + str(Distance.correlation_distance(data1, data2)))
		output.write(files[i] + "," + files[j] + "," + "correlation" + "," + str(Distance.correlation_distance(data1, data2)) + "\n")

def main(argv):
	if len(argv) != 3:
		print("Usage: <native.pdb> <decoys.pdb> <output.csv>")
		sys.exit(2)
	try:
		native_in = argv[0]
		file_in = argv[1]
		#nr_models = m
		output_file = argv[2]
	except:
		print("Usage: <native.pdb> <decoys.pdb> <output.csv>")
		sys.exit(2)
	#Count atoms and calculate LCS if needed
	native_atoms = Parser.countResidues(native_in)
	decoy_atoms = Parser.countResidues(file_in)
	if len(native_atoms) != len(decoy_atoms):
		print("Unequal, find longest common sequence")
		native_result, decoy_result = Parser.lcs(native_atoms, decoy_atoms)
		print("New length: " + str(len(native_result)))		
	else:
		native_result = []
		decoy_result = []	
	#Read and store native conformation
	nativelabels, nativeconformation = Parser.readConformations(str(native_in), 1, native_result)
	#Read decoys and store how many are within distance, morethan distance
	#using criteria{2,4}
	criteria = [2.0000000,4.0000000]
	models = 0
	atoms = []
	output_data = []
	currConf = []
	within2 = 0
	morethan2 = 0
	within4= 0
	morethan4 = 0
	with open(file_in, 'r') as f:
		for line in f:
		#while models < nr_models:
			#line = f_read.readline()
			splt = line.split()
			if splt[0] == 'MODEL':
				atoms = []
				currConf = []
				alpha_carbons = 1
			elif splt[0] == 'ATOM':
				if(splt[2] == 'CA'):
					if(len(decoy_result) == 0 or (str(splt[3]), int(splt[5])) in decoy_result):
						atoms.append((float(splt[6]), float(splt[7]), float(splt[8])))
			elif splt[0] == 'TER':
				if(len(atoms) > 0):
					currConf.append(atoms)
					models += 1
					distance = Distance.lrmsd(nativeconformation[0], currConf[0])
					#output_data.append([distance])
					if distance <= criteria[0]:
						within2 += 1
						within4 += 1
					else:
						morethan2 += 1
						if distance <= criteria[1]:
							within4 +=1 
						else: 
							morethan4 += 1
		#Output results in table with protein name, lcs length, number within/morethan for each criteria
		output_data.append(native_in[5:-4])
		output_data.append(len(nativeconformation[0]))
		output_data.append(within2+morethan2)
		output_data.append(within2)
		output_data.append(morethan2)
		output_data.append(within4)
		output_data.append(morethan4)
	with open(output_file, 'a+') as csvfile:
		writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
		if(csvfile.readline() == ""):
			writer.writerow(["Protein", "Num CA", "Num Confs", "Within 2", "Morethan 2", "Within 4", "Morethan 4"])
		writer.writerow(output_data)
		#for d in output_data:	
		#	writer.writerow(d)
	print("Completed")