Ejemplo n.º 1
0
def ret_schedule(cur_lat, cur_lon, cur_time, candidates, error, hist_time_win):
    ret = {}
    print(cur_time)
    print(hist_time_win)
    df_candidates = df_train.loc[((cur_time - hist_time_win*60*60*24) <= df_train['time'])  & (df_train['time'] < cur_time)]
    for num, pair in zip(candidates.keys(), candidates.values()):
        lat = pair[0]
        lon = pair[1]
        start_cir = Circle((cur_lat, cur_lon), radius = error)
        end_cir = Circle((lat, lon), radius = error)
        df_start = np.array([start_cir.contains_point([j, i]) for i,j in zip(df_candidates['pickup_longitude'], df_candidates['pickup_latitude'])])
        df_end = np.array([end_cir.contains_point([j, i]) for i,j in zip(df_candidates['dropoff_longitude'], df_candidates['dropoff_latitude'])])
        #df_start_lat = (df_candidates['pickup_latitude'] <= cur_lat+error) & (df_candidates['pickup_latitude'] >= cur_lat-error)
        #df_start_lon = (df_candidates['pickup_longitude'] <= cur_lon+error) & (df_candidates['pickup_longitude'] >= cur_lon-error)
        #df_end_lat = (df_candidates['dropoff_latitude'] <= lat+error) & (df_candidates['dropoff_latitude'] >= lat-error)
        #df_end_lon = (df_candidates['dropoff_longitude'] <= lon+error) & (df_candidates['dropoff_longitude'] >= lon-error)
        #df_finals = df_candidates.loc[df_start_lat & df_start_lon & df_end_lat & df_end_lon]
        df_finals = df_candidates.loc[df_start & df_end]
        ret[num] = []
        for hour in range(0, 24):
            df_cur_hour = df_finals.loc[pd.to_datetime(df_finals['pickup_datetime']).dt.hour == hour]
            s = np.sum(df_cur_hour['trip_duration']) - np.max(df_cur_hour['trip_duration'])*0.5 - np.min(df_cur_hour['trip_duration'])*0.5
            ret[num].append(s/len(df_cur_hour))
        ret[num].append(np.mean(ret[num]))
    return ret
Ejemplo n.º 2
0
def user_hotspot(num_users, radius):
    x = random.randint(int(2 * CELL_RADIUS),
                       int(NETWORK_SIZE_X - 2 * CELL_RADIUS))
    y = random.randint(int(2 * CELL_RADIUS),
                       int(NETWORK_SIZE_Y - 2 * CELL_RADIUS))
    bs_num = random.randint(0, len(basestations) - 1)
    mon_bs = []
    for bs in monitored_basestations:
        mon_bs.append(bs.basestation_id)
    bs_num = random.choice(mon_bs)
    bs = basestations[bs_num]
    x, y = bs.coords
    coord = (x, y)
    hotspot = Circle(coord, radius)
    hotspot.set_facecolor('Red')
    hotspot.set_alpha(0.2)
    ax.add_patch(hotspot)
    current_users = 0
    while current_users < num_users:
        x1 = random.randint(int(x - radius), int(x + radius))
        y1 = random.randint(int(y - radius), int(y + radius))
        point = (x1, y1)
        if hotspot.contains_point(ax.transData.transform(point)):
            user = User(x1, y1)
            user.user_id = len(users)
            user.bs = bs
            user.bs_coords = (bs.x_coord, bs.y_coord)
            user.first_tier_cells = bs.first_tier_cells
            if bs.monitored:
                monitored_users.append(user)
            user.plot_user()
            users.append(user)
            bs.users.append(user)
            current_users += 1
    def getUserTopicDistribution(self, event):
        # when click into circle, we need to get newly topic's distribution and show
        self.canvas.delete("TopicDistribution")
        color = "red"  # self.getRandomColor()
        print event.x, event.y
        x = event.x
        y = event.y
        from matplotlib.patches import Circle
        for key, value in self.circlescoordinates.iteritems():
            circ = Circle(value, radius=self.radius)
            if circ.contains_point([x, y]):
                filename = "User_Topics_Distribution_" + self.period + ".json"
                considerperiod = int(self.period[6:])
                while os.path.exists(filename) == False:
                    considerperiod = considerperiod - 1
                    filename = "User_Topics_Distribution_period" + str(
                        considerperiod) + ".json"

                with open(filename) as data_file:
                    data = json.load(data_file)

                TopicDis = (filter(
                    lambda dataelement: dataelement['name'] == key,
                    data)[0]["Topics"])
                temp = []
                for topic in TopicDis:
                    temp.append(round(float(topic[1]), 2))
                self.canvas.create_text(value[0],
                                        value[1],
                                        text=str(temp),
                                        fill=color,
                                        tags="TopicDistribution")
                break
Ejemplo n.º 4
0
    def _update_neighbors(self, bmu, vector):
        """
        Updates the weight vectors for the neighbors of the best matching unit.
        """

        r = 1 * self.decay_rate
        area = Circle((bmu.vector[0], bmu.vector[1]), radius=r)

        neighbors = [
            node for node in self.map
            if area.contains_point([node.vector[0], node.vector[1]])
            and node is not bmu
        ]

        print(len(self.map))
        print(len(neighbors))

        for node in neighbors:
            node.vector += self.decay_rate * (node.vector - vector)

        if self.decay_rate > 0.03:
            self.decay_rate -= .01
Ejemplo n.º 5
0
 def add_cell(self, network):
     cell = Circle((self.centre_x, self.centre_y), self.radius)
     nodes = network.vertices
     ridges = network.ridge_vertices
     nodes_to_delete = []
     ridges_to_delete = []
     for i in range(len(nodes)):
         if cell.contains_point(nodes[i]) == True:
             nodes_to_delete = np.append(nodes_to_delete, i)
     for i in range(len(ridges)):
         if ridges[i][0] in nodes_to_delete and ridges[i][
                 1] in nodes_to_delete:
             ridges_to_delete = np.append(ridges_to_delete, i)
     ridges_to_delete = np.array(sorted(ridges_to_delete, reverse=True))
     for ridge in ridges_to_delete:
         network.ridge_vertices = np.delete(network.ridge_vertices,
                                            int(ridge),
                                            axis=0)
     center = sg.Point(self.centre_x, self.centre_y)
     circ = sg.Circle(center, self.radius)
     k = 0
     for node in nodes_to_delete:
         node = int(node)
         for ridge in network.ridge_vertices:
             if ridge[0] == node:
                 if len(nodes[node]) == 3:
                     In_point = sg.Point(nodes[node][0], nodes[node][1],
                                         nodes[node][2])
                     Out_point = sg.Point(nodes[ridge[1]][0],
                                          nodes[ridge[1]][1],
                                          nodes[ridge[1]][1])
                 elif len(nodes[node]) == 2:
                     In_point = sg.Point(nodes[node][0], nodes[node][1])
                     Out_point = sg.Point(nodes[ridge[1]][0],
                                          nodes[ridge[1]][1])
                 line = sg.Line(In_point, Out_point)
                 intersec = sg.intersection(circ, line)
                 if length_square(nodes[ridge[1]] -
                                  intersec[0]) >= length_square(
                                      nodes[ridge[1]] - intersec[1]):
                     nodes = np.append(
                         nodes,
                         [[float(intersec[1].x),
                           float(intersec[1].y)]],
                         axis=0)
                 else:
                     nodes = np.append(
                         nodes,
                         [[float(intersec[0].x),
                           float(intersec[0].y)]],
                         axis=0)
                 ridge[0] = len(nodes) - 1
                 k += 1
             if ridge[1] == node:
                 if len(nodes[node]) == 3:
                     In_point = sg.Point(nodes[node][0], nodes[node][1],
                                         nodes[node][2])
                     Out_point = sg.Point(nodes[ridge[0]][0],
                                          nodes[ridge[0]][1],
                                          nodes[ridge[0]][1])
                 elif len(nodes[node]) == 2:
                     In_point = sg.Point(nodes[node][0], nodes[node][1])
                     Out_point = sg.Point(nodes[ridge[0]][0],
                                          nodes[ridge[0]][1])
                 line = sg.Line(In_point, Out_point)
                 intersec = sg.intersection(circ, line)
                 if length_square(nodes[ridge[0]] -
                                  intersec[0]) >= length_square(
                                      nodes[ridge[0]] - intersec[1]):
                     nodes = np.append(
                         nodes,
                         [[float(intersec[1].x),
                           float(intersec[1].y)]],
                         axis=0)
                 else:
                     nodes = np.append(
                         nodes,
                         [[float(intersec[0].x),
                           float(intersec[0].y)]],
                         axis=0)
                 ridge[1] = len(nodes) - 1
                 k += 1
     nodes_to_delete = np.array(sorted(nodes_to_delete, reverse=True))
     for point in nodes_to_delete:
         nodes = np.delete(nodes, int(point), 0)
     # Renumber points after deleting some
     for ridge in network.ridge_vertices:
         for i in range(2):
             r = 0
             for node in nodes_to_delete:
                 if node < ridge[i]:
                     r += 1
             ridge[i] = ridge[i] - r
     network.vertices = nodes
     network.vertices_ini = np.array(network.vertices.tolist())
     network = network.create_ridge_node_list()
     network = network.sort_nodes()
     network.interior_nodes = network.interior_nodes[:-k]
     self.boundary_cell = list(range(len(nodes) - k, len(nodes)))
     return network
Ejemplo n.º 6
0
circ_neg_inner = Circle((x_sec, y_sec), radius=rad)
circ_neg_outer = Circle((x_sec, y_sec), radius=rad + thk)

# arrays to hold x and y point values
pts_pos_x = []
pts_pos_y = []
pts_neg_x = []
pts_neg_y = []

# check if n number of points have been generated within bounds
while not len(pts_pos_x) + len(pts_neg_x) == n:
    x = random.uniform(x_min + buff, x_max - buff)  # randomly generate x value
    y = random.uniform(y_min + buff, y_max - buff)  # randomly generate y value

    # check if point is in positive semi-circle, and add point to pos arrays
    if circ_pos_outer.contains_point([x,y]) and \
       not circ_pos_inner.contains_point([x,y]) and y > y_origin:
        pts_pos_x.append(x)
        pts_pos_y.append(y)
    # check if point is in negative semi-circle, and add point to neg arrays
    elif circ_neg_outer.contains_point([x,y]) and \
        not circ_neg_inner.contains_point([x,y]) and y < y_sec:
        pts_neg_x.append(x)
        pts_neg_y.append(y)


def plot_points(x1, x2, y1, y2):
    """ Plots the generated points, sorted into the +1 and -1 classes.
    """
    plt.xlim(x_min, x_max)
    plt.ylim(y_min, y_max)
Ejemplo n.º 7
0
    cnt=np.array(cnt)
    rv=vrt-rp
    rc=cnt-rp
    csx=rv.dot(rc)/np.linalg.norm(rv)/np.linalg.norm(rc)
    return np.arccos(csx)
    
fg,ax=plt.subplots(figsize=(10,10))
sq=RegularPolygon((5,4),4,5,edgecolor='k',fill=False,orientation=np.pi/4)
cr=Circle((5,4),1,edgecolor='r',fill=False)
pnt=sq.get_verts()[:4]

x=np.linspace(pnt.min(0)[0],pnt.max(0)[0],100)
y=np.linspace(pnt.min(0)[1],pnt.max(0)[1],100)

rx,ry=5,4
while not cr.contains_point((rx,ry),0):
    rx=rd.choice(x)
    ry=rd.choice(y)

sx=-2;ix=-1

i=0
inp = int(input("Enter no. of iterations(min 1000):"))
while i<inp:
    ix=rd.choice(range(0,4))
    if ix==sx  :
        continue
    sx=ix
    cx,cy=pnt[sx]
    mx=(rx+cx)/2
    my=(ry+cy)/2