示例#1
0
 def test_convex_hull(self):
     # Smoke test
     fig = plt.figure()
     tri = ConvexHull(self.points)
     r = convex_hull_plot_2d(tri, ax=fig.gca())
     assert_(r is fig)
     convex_hull_plot_2d(tri)
示例#2
0
 def test_convex_hull(self):
     # Smoke test
     fig = plt.figure()
     tri = ConvexHull(self.points)
     r = convex_hull_plot_2d(tri, ax=fig.gca())
     assert_(r is fig)
     convex_hull_plot_2d(tri)
示例#3
0
 def test_convex_hull(self):
     # Smoke test
     fig = plt.figure()
     tri = ConvexHull(self.points)
     with suppress_warnings() as sup:
         # filter can be removed when matplotlib 1.x is dropped
         sup.filter(message="The ishold function was deprecated in version")
         r = convex_hull_plot_2d(tri, ax=fig.gca())
     assert_(r is fig)
     convex_hull_plot_2d(tri)
示例#4
0
def GetConvexHullVertices(lst_x,lst_y, show_plt = True):
    a = np.array(lst_x)
    b = np.array(lst_y)
    points = np.column_stack((a, b))
    hull = ConvexHull(points)
    if show_plt:
        figure = convex_hull_plot_2d(hull)
        plt.suptitle("convexhull")
        plt.show()
    return hull.vertices # indices of the convex hull vertices
示例#5
0
def plot_search(results, N_data, N_queries, axlims=None):
    ts = results["ts"]
    ndcgs = results["ndcgs"]
    
    x = ts.flatten()
    y = ndcgs.flatten()
    optX, optY, idxs = pareto_frontier(x, y, maxX = False)
    b = results['bs_rep'].flatten()
    e = results['es_rep'].flatten()
    M = results['Ms_rep'].flatten()
    L = results['Ls_rep'].flatten()
    print("Optimal points")
    print("{:>3},{:>4},{:>3},{:>3},{:>5},{:>6}".format(
        "b","e","M","L","t","ndcg"))
    for i, idx in enumerate(idxs):
        print("{:3.0f},{:4.1f},{:3.0f},{:3.0f},{:5.2f},{:6.3f}".format(
            b[idx], e[idx], M[idx], L[idx], optX[i], optY[i]))
        
    x = np.append(x, 100)
    x = np.append(0, x)
    y = np.append(y, 1)
    y = np.append(0, y)
    pts = np.vstack((x,y)).T
    hull = ConvexHull(pts)
    convex_hull_plot_2d(hull)
    


#     plt.plot(optX, optY, '-b')

#     plt.plot(x, y, '.b')
    plt.xlabel('Time (msec/query)')
    plt.ylabel('NDCG')
    # plt.title('Dataset Size N = {}'.format(N_data, N_queries))
    if axlims:
        plt.axis(axlims)
        
    plt.tight_layout()
    plt.savefig("op_{}-{}".format(N_data, N_queries), dpi=300)
    plt.show()
    return idxs
示例#6
0
def zonotope_2d_plot(vertices,
                     design=None,
                     y=None,
                     f=None,
                     out_label=None,
                     opts=None):
    """A utility for plotting (m,2) zonotopes with designs and quadrature rules.

    Parameters
    ----------
    vertices : ndarray 
        M-by-2 matrix that contains the vertices that define the zonotope
    design : ndarray, optional
        N-by-2 matrix that contains a design-of-experiments on the zonotope. The
        plot will contain the Delaunay triangulation of the points in `design` 
        and `vertices`. (default None)
    y : ndarray, optional 
        K-by-2 matrix that contains points to be plotted inside the zonotope. If
        `y` is given, then `f` must be given, too. (default None)
    f: ndarray, optional
        K-by-1 matrix that contains a color value for the associated points in 
        `y`. This is useful for plotting function values or quadrature rules 
        with the zonotope. If `f` is given, then `y` must be given, too. 
        (default None)
    out_label : str, optional 
        a label for the quantity of interest (default None)
    opts : dict, optional 
        a dictionary with some plot options (default None)

    Notes
    -----
    This function makes use of the scipy.spatial routines for plotting the
    zonotopes.
    """
    if opts == None:
        opts = plot_opts()

    # set labels for plots
    if out_label is None:
        out_label = 'Output'

    if vertices.shape[1] != 2:
        raise Exception('Zonotope vertices should be 2d.')

    if design is not None:
        if design.shape[1] != 2:
            raise Exception('Zonotope design should be 2d.')

    if y is not None:
        if y.shape[1] != 2:
            raise Exception('Zonotope design should be 2d.')

    if (y is not None and f is None) or (y is None and f is not None):
        raise Exception('You need both y and f to plot.')

    if y is not None and f is not None:
        if y.shape[0] != f.shape[0]:
            raise Exception('Lengths of y and f are not the same.')

    # get the xlim and ylim
    xmin, xmax = np.amin(vertices), np.amax(vertices)

    # make the Polygon patch for the zonotope
    ch = ConvexHull(vertices)

    # make the Delaunay triangulation
    if design is not None:
        points = np.vstack((design, vertices))
        dtri = Delaunay(points)

    fig = plt.figure(figsize=(7, 7))
    ax = fig.add_subplot(111)
    fig0 = convex_hull_plot_2d(ch, ax=ax)
    for l in fig0.axes[0].get_children():
        if type(l) is Line2D:
            l.set_linewidth(3)

    if design is not None:
        fig1 = delaunay_plot_2d(dtri, ax=ax)
        for l in fig1.axes[0].get_children():
            if type(l) is Line2D:
                et_color('0.75')

    if y is not None:
        plt.scatter(y[:, 0],
                    y[:, 1],
                    c=f,
                    s=100.0,
                    vmin=np.min(f),
                    vmax=np.max(f))
        plt.axes().set_aspect('equal')
        plt.title(out_label)
        plt.colorbar()

    plt.axis([1.1 * xmin, 1.1 * xmax, 1.1 * xmin, 1.1 * xmax])
    plt.xlabel('Active variable 1')
    plt.ylabel('Active variable 2')
    show_plot(plt)
    if opts['savefigs']:
        figname = 'figs/zonotope_2d_' + out_label + opts['figtype']
        plt.savefig(figname, dpi=300, bbox_inches='tight', pad_inches=0.0)
示例#7
0
def generate_convex_hull(img, vis=False):
    rows, cols, _ = img.shape

    for i in range(rows):
        for j in range(cols):
            if(img[i,j,0] != 14):
                img[i,j,0] = 0
            else:
                img[i,j,0] = 1
    # view = img[:,:,0]
    # view[view != 14] = 1
    # view[view == 14] = 0
    
    kernel = np.ones((3,3), np.uint8)
    crosswalk = np.copy(img[:,:,0])
    if vis == True:
        plt.figure(0)
        plt.imshow(crosswalk)
    crosswalk = cv2.erode(crosswalk, kernel, iterations=1)

    if vis == True:
        plt.figure(1)
        plt.imshow(crosswalk)
    crosswalks = connected_component(crosswalk, 1)

    if vis == True:
        plt.figure(2)
        plt.imshow(crosswalks)

    select_index = 11
    chosen_crosswalk = np.copy(crosswalks)
    crosswalk_pts = np.zeros((1,2))

    for i in range(rows):
        for j in range(cols):
            if(chosen_crosswalk[i,j] == select_index):
                crosswalk_pts = np.vstack((crosswalk_pts, np.array([i, j])))
            else:
                chosen_crosswalk[i,j] = 9

    crosswalk_pts = crosswalk_pts[1:, :]
    crosswalk_pts = np.fliplr(crosswalk_pts)
    hull = ConvexHull(points=crosswalk_pts, qhull_options='Q64')
    
    nodes = np.hstack((hull.vertices, hull.vertices[0]))
    vertices = crosswalk_pts[nodes, :]
    x_vertices = vertices[:, 0]
    y_vertices = vertices[:, 1]
    
    if vis == True:
        plt.figure(3)
        plt.imshow(chosen_crosswalk)

        fig = plt.figure(4)
        ax = fig.add_subplot(1,1,1)
        convex_hull_plot_2d(hull, ax=ax)  

        plt.figure(5)
        plt.imshow(img[:,:,0])
        
        plt.scatter(x_vertices, y_vertices, s=50, c='red', marker='o')
        plt.plot(x_vertices, y_vertices, c='red')
        plt.show()
    
    return vertices.T
示例#8
0
    kmeans.fit(X_train)
    y_kmeans = kmeans.predict(X_train)  # cluster index for each observation
    centers = kmeans.cluster_centers_  # cluster center coordinates
    fig, ax = plt.subplots()
    plt.scatter(X_train[:, 0], X_train[:, 1], c=y_kmeans, s=5, cmap='summer')
    plt.scatter(centers[:, 0], centers[:, 1], c='black', s=100, alpha=0.5)

    from scipy.spatial import Voronoi, voronoi_plot_2d
    from scipy.spatial import ConvexHull, convex_hull_plot_2d

    db = DBSCAN(eps=0.5, min_samples=10).fit(X_train)
    core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
    core_samples_mask[db.core_sample_indices_] = True

    y_db = DBSCAN(eps=0.5, min_samples=10).fit_predict(X_train)
    plt.scatter(X_train[:, 0], X_train[:, 1], c=y_db, cmap='summer')

    vor = Voronoi(centers)
    voronoi_plot_2d(vor, ax)

    # plt.scatter(X_train[:, 0], X_train[:, 1], c=y_kmeans, s=5, cmap='summer')
    # plt.show()

    for label in range(n_clusters):
        points = [X_train[index] for index in np.where(db.labels_ == label)[0]]
        hull = ConvexHull(points)
        convex_hull_plot_2d(hull, ax)
    plt.xlim((xmin, xmax))
    plt.ylim((ymin, ymax))
    plt.show()
示例#9
0
    p = points[s].mean(axis=0)
    plt.text(p[0], p[1], '#%d' % j, ha='center') # label triangles
#plt.xlim(-0.5, 1.5); plt.ylim(-0.5, 1.5)
plt.show()


# Convex hulls
from scipy.spatial import ConvexHull, convex_hull_plot_2d
points = np.random.rand(30, 2)
hull = ConvexHull(points)
plt.plot(points[:, 0], points[:, 1], 'o')
for simplex in hull.simplices:
    plt.plot(points[simplex, 0], points[simplex, 1], 'k-')
plt.show()

convex_hull_plot_2d(hull)



# -----------------------------------------------------------------------------
# STATS
from scipy import stats
help(stats)


# Random variables

from scipy.stats import norm # normal
# from __future__ import print_function

print(stats.norm.__doc__)
示例#10
0
def zonotope_2d_plot(vertices, design=None, y=None, f=None, out_label=None, opts=None):
    
    if opts == None:
        opts = plot_opts()

    # set labels for plots
    if out_label is None:
        out_label = 'Output'
        
    if vertices.shape[1] != 2:
        raise Exception('Zonotope vertices should be 2d.')
        
    if design is not None:
        if design.shape[1] != 2:
            raise Exception('Zonotope design should be 2d.')
            
    if y is not None:
        if y.shape[1] != 2:
            raise Exception('Zonotope design should be 2d.')
            
    if (y is not None and f is None) or (y is None and f is not None):
        raise Exception('You need both y and f to plot.')
        
    if y is not None and f is not None:
        if y.shape[0] != f.shape[0]:
            raise Exception('Lengths of y and f are not the same.')
    
    # get the xlim and ylim
    xmin, xmax = np.amin(vertices), np.amax(vertices)
    
    # make the Polygon patch for the zonotope
    ch = ConvexHull(vertices)
    
    # make the Delaunay triangulation 
    if design is not None:
        points = np.vstack((design, vertices))
        dtri = Delaunay(points)
    
    fig = plt.figure(figsize=(7,7))
    ax = fig.add_subplot(111)
    convex_hull_plot_2d(ch, ax=ax)
    
    if design is not None:
        fig = delaunay_plot_2d(dtri, ax=ax)
        for l in fig.axes[0].get_children():
            if type(l) is Line2D:
	        l.set_color('0.75')
        
    if y is not None:
        plt.scatter(y[:,0], y[:,1], c=f, s=100.0, vmin=np.min(f), vmax=np.max(f))
        plt.axes().set_aspect('equal')
        plt.title(out_label)
        plt.colorbar()
        
    plt.axis([1.1*xmin,1.1*xmax,1.1*xmin,1.1*xmax])
    plt.xlabel('Active variable 1')
    plt.ylabel('Active variable 2')
    plt.show()
    if opts['savefigs']:
        figname = 'figs/zonotope_2d_' + out_label + opts['figtype']
        plt.savefig(figname, dpi=300, bbox_inches='tight', pad_inches=0.0)
示例#11
0
def main():
    #G, pos = generate_graph()
    G = nx.read_gpickle("../data/graphs/public_toilet2.gpickle")
    print(G.number_of_nodes())
    graph_sampler = GraphSampler()
    G = graph_sampler.down_sampler(G, 2000, 2000)
    G = nx.relabel.convert_node_labels_to_integers(G)
    pos = nx.get_node_attributes(G, 'pos')
    pos_list = list(map(list, list(pos.values())))
    nx.draw(G, pos, node_size=30, with_labels=True)

    # Construct Voronoi diagram from nodes
    vor = Voronoi(pos_list)
    voronoi_plot_2d(vor)
    #hull = concaveHull(np.array(pos_list), k=3)
    #hull = np.array(list(map(list, list(hull))))
    #plt.plot(hull[:, 0], hull[:, 1])

    # Calculate convex hull around graph
    hull = ConvexHull(pos_list)
    convex_hull_plot_2d(hull)

    # Select Voronoi points inside convex hull
    # TODO: use clockwise points instead of convex hull
    filt_vor_vertices = []
    for vertex in vor.vertices:
        if point_inside_polygon(vertex[0], vertex[1],
                                np.array(pos_list)[hull.vertices]):
            filt_vor_vertices.append(list(vertex))
    plt.scatter(np.array(vor.vertices)[:, 0],
                np.array(vor.vertices)[:, 1],
                c='g',
                s=50)
    plt.scatter(np.array(filt_vor_vertices)[:, 0],
                np.array(filt_vor_vertices)[:, 1],
                c='r',
                s=50)

    # Determine edges associated with vertices
    edge_list = list(G.edges)
    start_time = time.time()

    vertices_associated_edges = []
    for vertex in tqdm(filt_vor_vertices):
        vertex_associated_edges = []
        for edge_idx, edge in enumerate(edge_list):
            #edge1_pos1 = list(G._node[edge[0]]['pos'])
            #edge1_pos2 = list(G._node[edge[1]]['pos'])
            edge1_pos1 = pos_list[edge[0]]  #list(G._node[edge[0]]['pos'])
            edge1_pos2 = pos_list[edge[1]]
            line_of_sight = True
            for comp_edge_idx, comp_edge in enumerate(edge_list):
                if edge_idx != comp_edge_idx:
                    #edge2_pos1 = list(G._node[comp_edge[0]]['pos'])
                    #edge2_pos2 = list(G._node[comp_edge[1]]['pos'])
                    edge2_pos1 = pos_list[
                        comp_edge[0]]  # list(G._node[edge[0]]['pos'])
                    edge2_pos2 = pos_list[comp_edge[1]]
                    mid_pos = [(edge1_pos1[0] + edge1_pos2[0]) / 2,
                               (edge1_pos1[1] + edge1_pos2[1]) / 2]
                    #if intersect(edge1_pos1, vertex, edge2_pos1, edge2_pos2) and \
                    #        intersect(edge1_pos2, vertex, edge2_pos1, edge2_pos2):
                    if intersect(vertex, mid_pos, edge2_pos1, edge2_pos2):
                        line_of_sight = False
                        break
            if line_of_sight:
                vertex_associated_edges.append(edge_idx)
        vertices_associated_edges.append(vertex_associated_edges)
    print(time.time() - start_time)

    # Determine vertices associated with vertices
    vertices_associated_vertices = []
    for vertex_idx, vertex in tqdm(enumerate(filt_vor_vertices)):
        vertex_associated_vertices = []
        vertex_associated_vertices.append(vertex_idx)
        for comp_vertex_idx, comp_vertex in enumerate(filt_vor_vertices):
            if comp_vertex_idx != vertex_idx:
                line_of_sight = True
                for edge in edge_list:
                    edge_pos1 = list(G._node[edge[0]]['pos'])
                    edge_pos2 = list(G._node[edge[1]]['pos'])
                    if intersect(vertex, comp_vertex, edge_pos1, edge_pos2):
                        line_of_sight = False
                        break
                if line_of_sight:
                    vertex_associated_vertices.append(comp_vertex_idx)
        vertices_associated_vertices.append(vertex_associated_vertices)

    room_graph = to_graph(vertices_associated_vertices)
    rooms_vertices = list(connected_components(room_graph))
    #print(rooms_vertices)

    #print(vertices_associated_edges)

    print(rooms_vertices)

    rooms_nodes = []
    for room_vertices in tqdm(rooms_vertices):
        row_idx = np.array(list(room_vertices))
        plt.plot(
            np.array(filt_vor_vertices)[row_idx, 0],
            np.array(filt_vor_vertices)[row_idx, 1])
        room_nodes = []
        for vertex in list(room_vertices):
            for edge in vertices_associated_edges[vertex]:
                room_nodes.append(edge_list[edge][0])
                room_nodes.append(edge_list[edge][1])
        rooms_nodes.append(list(set(room_nodes)))

    color = iter(cm.rainbow(np.linspace(0, 1, len(rooms_nodes))))
    for room_nodes in tqdm(rooms_nodes):
        room_pos = []
        c = next(color)
        for node in room_nodes:
            pos = G._node[node]['pos']
            room_pos.append(pos)

        # TODO could be a problem
        #ConvexHull
        #center = tuple(map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), room_pos), [len(room_pos)] * 2))
        #room_pos_sorted = np.array(sorted(room_pos, key=lambda coord: (-135 - math.degrees(math.atan2(*tuple(map(operator.sub, coord, center))[::-1]))) % 360))

        #plt.fill(room_pos_sorted[:, 0], room_pos_sorted[:, 1], c=c, alpha=0.2)
        #hull = concaveHull(np.array(room_pos),3)
        #plt.fill(np.array(hull)[:, 0], np.array(hull)[:, 1], c=c, alpha=0.2)
        #plt.fill(np.array(hull)[:, 0], np.array(hull)[:, 1], c=c, alpha=0.2)
        # TODO use known edges
        print(room_pos)
        if len(room_pos) > 2:
            hull = ConvexHull(room_pos)
            plt.fill(np.array(room_pos)[hull.vertices, 0],
                     np.array(room_pos)[hull.vertices, 1],
                     c=c,
                     alpha=0.2)
        #plt.fill(np.array(room_pos)[hull.vertices][0], np.array(room_pos)[hull.vertices][1], c=c, alpha=0.2)
        print(hull)
        #plt.fill

    #plt.fill(np.array(rooms_nodes[0])[0], np.array(rooms_nodes[0])[1])

    print(rooms_nodes)
    '''for room_nodes in rooms_nodes:
        room_pos = []
        for node in room_nodes:
            edge_pos1 = G._node[node[0]]['pos']
            edge_pos2 = G._node[node[1]]['pos']
        hull = ConvexHull(room)'''
    '''rooms = [[]]
    for idx, vertices_associated in enumerate(vertices_associated_vertices):
        print(str(idx) + '/' + str(len(vertices_associated_vertices)))
        print(rooms)
        for room in rooms:
            if vertices_associated[0] in room:
                room = room + vertices_associated
            else:
                rooms.append(vertices_associated)

    for room in rooms:
        room = list(set(room))

    print(vertices_associated_vertices)
    print(len(rooms))'''

    #rooms = merge_associated_edges(vertices_associated_vertices, vertices_associated_edges)
    #print(len(rooms))
    '''for vertex_idx, vertices_associated in enumerate(vertices_associated_vertices):
        room_edges = []
        room_edges.extend(vertices_associated_edges[vertex_idx])
        for vertex in vertices_associated:
            room_edges.extend(vertices_associated_edges[vertex])
            for 
        
        room_edges = list(set(room_edges))'''

    plt.show()
    print("done")
示例#12
0
y = np.dot(X, W[:, 0])
asp.sufficient_summary(y, F)

# Get the response surface design and plot its points.

# In[3]:

# Get a design on the active variable
n = 2  # dimension of the active subspace
N = [10]  # number points in the active variable
NMC = 10  # number of monte carlo samples
XX, ind, Y = ac.response_surface_design(W, n, N, NMC, bflag=1)

# look at the zonotope and the design
zt = ac.Zonotope(W[:, :n])
convex_hull_plot_2d(zt.convhull)
plt.plot(Y[:, 0], Y[:, 1], 'ro')
plt.xlabel('Active variable 1')
plt.ylabel('Active variable 2')
plt.show()

# In[4]:

# sample the function at the design points
FF = ac.sample_function(XX, fun, dflag=True)[0]

# compute conditional expectations
G, V = ac.conditional_expectations(FF, ind)

# build the response surface on the active variable
gp = ac.GaussianProcess(2)
示例#13
0
def zonotope_2d_plot(vertices, design=None, y=None, f=None, out_label=None, opts=None):
    """
    A utility for plotting (m,2) zonotopes with associated designs and
    quadrature rules.

    :param ndarray vertices: M-by-2 matrix that contains the vertices that
        define the zonotope.
    :param ndarray design: N-by-2 matrix that contains a design-of-experiments
        on the zonotope. The plot will contain the Delaunay triangulation of the
        points in `design` and `vertices`.
    :param ndarray y: K-by-2 matrix that contains points to be plotted inside
        the zonotope. If `y` is given, then `f` must be given, too.
    :param ndarray f: K-by-1 matrix that contains a color value for the
        associated points in `y`. This is useful for plotting function values
        or quadrature rules with the zonotope. If `f` is given, then `y` must
        be given, too.
    :param str out_label: A label for the quantity of interest.
    :param dict opts: A dictionary with some plot options.

    **Notes**

    This function makes use of the scipy.spatial routines for plotting the
    zonotopes.
    """
    if opts == None:
        opts = plot_opts()

    # set labels for plots
    if out_label is None:
        out_label = 'Output'

    if vertices.shape[1] != 2:
        raise Exception('Zonotope vertices should be 2d.')

    if design is not None:
        if design.shape[1] != 2:
            raise Exception('Zonotope design should be 2d.')

    if y is not None:
        if y.shape[1] != 2:
            raise Exception('Zonotope design should be 2d.')

    if (y is not None and f is None) or (y is None and f is not None):
        raise Exception('You need both y and f to plot.')

    if y is not None and f is not None:
        if y.shape[0] != f.shape[0]:
            raise Exception('Lengths of y and f are not the same.')

    # get the xlim and ylim
    xmin, xmax = np.amin(vertices), np.amax(vertices)

    # make the Polygon patch for the zonotope
    ch = ConvexHull(vertices)

    # make the Delaunay triangulation
    if design is not None:
        points = np.vstack((design, vertices))
        dtri = Delaunay(points)

    fig = plt.figure(figsize=(7,7))
    ax = fig.add_subplot(111)
    fig0 = convex_hull_plot_2d(ch, ax=ax)
    for l in fig0.axes[0].get_children():
        if type(l) is Line2D:
	        l.set_linewidth(3)

    if design is not None:
        fig1 = delaunay_plot_2d(dtri, ax=ax)
        for l in fig1.axes[0].get_children():
            if type(l) is Line2D:
	        l.set_color('0.75')

    if y is not None:
        plt.scatter(y[:,0], y[:,1], c=f, s=100.0, vmin=np.min(f), vmax=np.max(f))
        plt.axes().set_aspect('equal')
        plt.title(out_label)
        plt.colorbar()

    plt.axis([1.1*xmin,1.1*xmax,1.1*xmin,1.1*xmax])
    plt.xlabel('Active variable 1')
    plt.ylabel('Active variable 2')
    show_plot(plt)
    if opts['savefigs']:
        figname = 'figs/zonotope_2d_' + out_label + opts['figtype']
        plt.savefig(figname, dpi=300, bbox_inches='tight', pad_inches=0.0)