Ejemplo n.º 1
0
 def _genBasicMesh(self):
     x = numpy.array(numpy.random.uniform(0, 2.0 * ogre.Math.PI, self.numPts))
     y = numpy.array(numpy.random.uniform(0, ogre.Math.PI, self.numPts))
     cens, edg, tri, neig = triang.delaunay(x, y)
     self.x = x
     self.y = y
     self.tris = tri
Ejemplo n.º 2
0
def generate(n, k, outfile):

    # Delaunay triangulation of random points in R^2
    print 'Generating %d-planar graph with %d tokens.' % (n, k)

    x, y = numpy.array(numpy.random.standard_normal((2, n)))
    c, E, tris, ngbr = tri.delaunay(x, y)

    # Choose k unique vertices to have tokens
    token_verts = random.sample(range(n), k)

    print "Writing to %s" % (outfile)
    with open(outfile, "wb") as f:
        writer = csv.writer(f, delimiter=' ')

        # Write the graph details
        writer.writerow([n, len(E), k])

        # Write the adjecency list
        for edge in E:
            writer.writerow(edge)

        # Write which vertices are token vertices
        for v in token_verts:
            writer.writerow([v])

        f.close()
Ejemplo n.º 3
0
def generate(n, k, outfile):


    # Delaunay triangulation of random points in R^2
    print 'Generating %d-planar graph with %d tokens.' % (n, k)

    x,y = numpy.array(numpy.random.standard_normal((2,n)))
    c,E,tris,ngbr = tri.delaunay(x,y)
                
    # Choose k unique vertices to have tokens
    token_verts = random.sample(range(n), k)

    print "Writing to %s" % (outfile)
    with open(outfile, "wb") as f:
        writer = csv.writer(f, delimiter=' ')

        # Write the graph details
        writer.writerow([n, len(E), k])

        # Write the adjecency list
        for edge in E:
            writer.writerow(edge)

        # Write which vertices are token vertices
        for v in token_verts:
            writer.writerow([v])  

        f.close()
Ejemplo n.º 4
0
def triangleImage(link, nom, s):
    a = seuil(imageio.imread(link), s)
    a = py.rot90(a, 3)
    xBis, yBis = transforme(a.tolist())
    xBis, yBis = np.array(xBis), np.array(yBis)
    cens, edg, tri, neig = triang.delaunay(xBis, yBis)

    taille = len(a.tolist())
    l = taille / 15
    b = 0
    py.figure()
    for t in tri:
        # t[0], t[1], t[2] are the points indexes of the triangle
        d1, d2, d3 = d(xBis[t[0]], yBis[t[0]], xBis[t[1]],
                       yBis[t[1]]), d(xBis[t[1]], yBis[t[1]], xBis[t[2]],
                                      yBis[t[2]]), d(xBis[t[2]], yBis[t[2]],
                                                     xBis[t[0]], yBis[t[0]])
        if (d1 < l and d2 < l and d3 < l):
            #t_i = [t[0], t[1], t[2], t[0]]
            t_i = [t[0], t[1], t[2], t[0]]
            if (b):
                py.fill(xBis[t_i], yBis[t_i], "black")
                b = 0
            else:
                b = 1
    py.savefig(nom)
Ejemplo n.º 5
0
 def interp(self,xt,yt,zorigt):
     x=xt[:,zorigt>=0.0]
     y=yt[:,zorigt>=0.0]
     z=zorigt[:,zorigt>=0.0]
     cens,edg,tri,neig = D.delaunay(x,y)
     if 0:
         #plot triangulation
         for t in tri:
             # t[0], t[1], t[2] are the points indexes of the triangle
             t_i = [t[0], t[1], t[2], t[0]]
             pylab.plot(x[t_i],y[t_i])
     
     #pylab.plot(x,y,'o')
     #pylab.show()        
     
     
     tri = D.Triangulation(x,y)
     interp = tri.nn_interpolator(z)
     xi=N.copy(x)
     yi=N.copy(y)
     xi=N.concatenate((xi,self.line_x))
     yi=N.concatenate((yi,self.line_y))
     zi = interp(xi,yi)
     mylocator=locator(xi,yi)
     inds=mylocator.inside(self.line_x,self.line_y)
     outxi=xi[inds.astype(int)]
     outyi=yi[inds.astype(int)]
     outzi=zi[inds.astype(int)]
     return outxi,outyi,outzi
Ejemplo n.º 6
0
    def plot_voronoi(self, ax=None, show_latlon=True):
        if ax is None:
            fig = pl.figure()
            ax = fig.add_subplot(111)

        # calculate half size position of each edge and
        # do delaunay interpolation again. This
        # gives then the Voronoi diagram
        if not self._interpolated:
            self._delaunay_triangulation()

        lons = []
        lats = []
        for e in self.edg:
            # half way position
            plon = self.lon[e[0]] + 0.5 * (self.lon[e[1]] - self.lon[e[0]])
            plat = self.lat[e[0]] + 0.5 * (self.lat[e[1]] - self.lat[e[0]])
            lons.append(plon)
            lats.append(plat)
        lons = np.asarray(lons)
        lats = np.asarray(lats)

        cens, edg, tris, neig = triang.delaunay(lons, lats)
        self._do_delaunay_plot(tris, lons, lats, ax)
        ax.plot(lons, lats, marker='x', linestyle='None', color='green')

        if show_latlon:
            ax.plot(self.lon, self.lat, 'o', color='black')
Ejemplo n.º 7
0
def triangulate( datadict ):

  del datadict['BEAV']
  del datadict['SLAP']
  del datadict['HOOK']
  del datadict['GOOD']
  del datadict['BOIS']
  del datadict['KENT']

  if 'WALT' in datadict.keys():
    datadict['WAL2'] = datadict['WALT']
    del datadict['WALT']

  stnfile = np.load('mesonet.npz')
  m = P( stationdict=stnfile, area='OK' ).proj()
  gridX = []
  gridY = []
  stations = []
  for stn in datadict.keys():
    if np.isnan( datadict[ stn ][ 'UMET' ] ) == True or np.isnan( datadict[ stn ][ 'VMET' ] ) == True:
      del datadict[ stn ]
      continue
    else:
      gridX.append( stnfile[ stn ][0] )
      gridY.append( stnfile[ stn ][1] )
      stations.append( stn )
  x,y = m( gridX, gridY )
  x = np.array( x )
  y = np.array( y )
  centers,edges,tri,neighbors = md.delaunay( x, y )
  return ( centers, edges, tri, neighbors, stations, x, y )
Ejemplo n.º 8
0
    def get_mst_score(cls, x, y):
        ''' Use the size of second largest connected component
        when building MST for Delaunay triangulation as score

        :param x: x-coordinates of all data
        :param y: y-coordinates of all data
        :return:
        '''
        # Do Delaunay triangulation, use length of the edges as weight
        cens, edg, tri, neig = triang.delaunay(x, y)
        edges = {}
        for t in tri:
            if not (t[0], t[1]) in edges.items():
                edges[(t[0], t[1])] = distance(x, y, t[0], t[1])
            if not (t[1], t[2]) in edges.items():
                edges[(t[1], t[2])] = distance(x, y, t[1], t[2])
            if not (t[2], t[0]) in edges.items():
                edges[(t[2], t[0])] = distance(x, y, t[2], t[0])

        # Use Kruskal to build a minimum spanning tree
        ordered_edges = sorted(edges.items(), key=operator.itemgetter(1))
        mst_edges = []
        lengths = []
        i = len(x)
        uf = UnionFind()
        for ((t1, t2), length) in ordered_edges:
            if MinSpanTree.is_connected(mst_edges, t1, t2):
                continue
            mst_edges.append((t1, t2))
            lengths.append(length)
            uf.union(t1, t2)
            i -= 1
            if length > lengths[0] * 4:
                break
        return uf.second_largest_size()
Ejemplo n.º 9
0
	def calc_triangulation(self):
		cens,edg,tri,neig = triang.delaunay(self.xList,self.yList)
		tri = numpy.array([tri])
		tri = tri[0]
		for t in tri:
		# t[0], t[1], t[2] are the points indexes of the triangle
		#Now we want to extract a complete triangle from each index
			t_i = [t[0], t[1], t[2], t[0]]
			x = [self.xList[i] for i in t_i]
			y = [self.yList[i] for i in t_i]
			z = [self.zList[i] for i in t_i]
			colourhex = [self.colourList[i] for i in t_i]
			#Retrieve only the first item of the colour value since all the 3 points have same colour
			colourhex = colourhex[:1]
			#Convert to string so we can add to a new list and extract later on
			colourhex = "".join(colourhex)
			#Convert string values of triangle to int
			x = [int(i) for i in x]
			y = [int(i) for i in y]
			z = [int(i) for i in z]
			#For performance sake, we reuse the xList, yList, zList and colourList(holding original CSV data) instead of creating and using a new lists 
			self.xList.append(x)
			self.yList.append(y)
			self.zList.append(z)
			self.colourList.append(colourhex)
		#Update the content of xList,yList,zList and colourList to the new data needed for triangulation
		self.xList[:self.len_xList] = [] #Remove all X values original appended from the CSV file 
		self.yList[:self.len_yList] = [] #Remove all Y values original appended from the CSV file
		self.zList[:self.len_zList] = [] #Remove all Z values original appended from the CSV file
		self.colourList[:self.len_colourList] = [] #Remove all hex values original appended from the CSV
Ejemplo n.º 10
0
    def plot_voronoi(self, ax=None, show_latlon=True):
        if ax is None:
            fig = pl.figure()
            ax = fig.add_subplot(111)

        # calculate half size position of each edge and
        # do delaunay interpolation again. This
        # gives then the Voronoi diagram
        if not self._interpolated:
            self._delaunay_triangulation()

        lons = []
        lats = []
        for e in self.edg:
            # half way position
            plon = self.lon[e[0]] + 0.5 * (self.lon[e[1]] - self.lon[e[0]])
            plat = self.lat[e[0]] + 0.5 * (self.lat[e[1]] - self.lat[e[0]])
            lons.append(plon)
            lats.append(plat)
        lons = np.asarray(lons)
        lats = np.asarray(lats)

        cens, edg, tris, neig = triang.delaunay(lons, lats)
        self._do_delaunay_plot(tris, lons, lats, ax)
        ax.plot(lons, lats, marker='x', linestyle='None', color='green')

        if show_latlon:
            ax.plot(self.lon, self.lat, 'o', color='black')
Ejemplo n.º 11
0
    def __init__(self, boundary_callable=CircleBoundary(), sample_count=20):
        '''
        :param boundary_callable: a callable we can sample sample_count times in [0,1)
        :param sample_count: how many points to sample from boundary_callable
        if boundary function is of that fancy cas package we could sample
        weighed by the absolute value of the gradient. otherwise sampling is uniform
        '''
        super(PrescribedBoundaryGrid, self).__init__()
        fac = 1 / sample_count
        self._px = np.array(
            [boundary_callable(p * fac)[0] for p in range(sample_count)])
        self._py = np.array(
            [boundary_callable(p * fac)[1] for p in range(sample_count)])
        self._vertices = zip(self._px, self._py)

        self._centers, _, triangles, self._neighbours_ids = delaunay(
            self._px, self._py)
        self._edges = []
        for ids in triangles:
            self._edges.extend([
                self.Edge(ids[i[0]], ids[i[1]])
                for i in [(0, 1), (1, 2), (2, 0)]
            ])

        self._triangles = [self.Triangle(x, self._edges) for x in triangles]
        self._sizes = {
            0: len(self._triangles),
            1: len(self._edges),
            2: len(self._px)
        }
        self.__subentities = list(xrange(self.dim + 1))
        self.__subentities[2] = np.array([c.vertices for c in self._triangles],
                                         dtype='int32')
        self.__subentities[1] = np.array([c.edges for c in self._triangles],
                                         dtype='int32')
        self.__subentities[0] = np.arange(len(self._triangles),
                                          dtype='int32')[:, np.newaxis]
        self.__embed_A = np.empty((self._sizes[0], 2, 2))
        self.__embed_B = np.empty((self._sizes[0], 2))

        for i, triangle in enumerate(self._triangles):
            x = [(self._px[triangle.vertices[j]],
                  self._py[triangle.vertices[j]]) for j in (0, 1, 2)]
            W = np.array([[x[0][0], x[0][1], 0, 0, 1, 0],
                          [0, 0, x[0][0], x[0][1], 0, 1],
                          [x[1][0], x[1][1], 0, 0, 1, 0],
                          [0, 0, x[1][0], x[1][1], 0, 1],
                          [x[2][0], x[2][1], 0, 0, 1, 0],
                          [0, 0, x[2][0], x[2][1], 0, 1]])
            K = np.array([0, 0, 0, 1, 1, 1])
            try:
                R = np.linalg.solve(W, K)
            except np.linalg.linalg.LinAlgError, e:
                import pprint
                self.logger.critical(pprint.pformat(K))
                self.logger.critical(pprint.pformat(W))
                self.logger.error(pprint.pformat(self._vertices))
                raise e
            self.__embed_A[i] = [[R[0], R[1]], [R[2], R[3]]]
            self.__embed_B[i] = [R[4], R[5]]
Ejemplo n.º 12
0
 def find_minimum_weight_matching(self):
     """ finds a minimum weight perfect matching"""
     print "computing delaunay of odd_deg_nodes"
     circumcenters, edges, tri_points, tri_neighbors = triang.delaunay(
         self.x[self.odd_deg_nodes], self.y[self.odd_deg_nodes])
     o = nx.Graph()
     o.dist_func = lambda i, j: -self.euclidean_dist(i, j)
     for i, j in edges:
         mi = self.odd_deg_nodes[i]
         mj = self.odd_deg_nodes[j]
         o.add_edge(mi, mj, weight=o.dist_func(mi, mj))
     self.o = o
     print '#edges:', len(edges), '#nodes:', len(o.nodes()), len(
         self.odd_deg_nodes)
     print "computing minimum matching"
     t1 = time.time()
     mates = max_weight_matching(o, maxcardinality=True)
     t2 = time.time()
     print "took %s" % (t2 - t1)
     m = nx.Graph()
     for i in mates.keys():
         m.add_edge(i, mates[i], weight=self.g.dist_func(i, mates[i]))
     print '#edges:', len(m.edges()), '#nodes:', len(m.nodes())
     self.plot_edges(m.edges(), 'r-', 2)
     self.m = m
Ejemplo n.º 13
0
 def triangulation(cls, x, y):
     cens, edg, tri, neig = triang.delaunay(x, y)
     for t in tri:
         x_line = [x[t[0]], x[t[1]], x[t[2]], x[t[0]]]
         y_line = [y[t[0]], y[t[1]], y[t[2]], y[t[0]]]
         plt.plot(x_line, y_line)
     plt.plot(x, y, '.')
     plt.show()
Ejemplo n.º 14
0
def delaunay_pairs(date, location, perp_max, temp_max, dir):

    centers, edges, tri, neighbors = md.delaunay(date, location)
    pairs = edges.tolist()

    bperp = []
    for idx in xrange(len(pairs)):
        if pairs[idx][0] > pairs[idx][1]:
            index1 = pairs[idx][1]
            index2 = pairs[idx][0]
            pairs[idx][0] = index1
            pairs[idx][1] = index2
    pairs_in = sorted(pairs, key=itemgetter(0))
    pairs_in2 = []
    [pairs_in2.append(i) for i in pairs_in if not i in pairs_in2]
    pairs = []
    for idx in xrange(len(pairs_in2)):
        perp = location[pairs_in2[idx][1]] - location[pairs_in2[idx][0]]
        abs_perp = abs(perp)
        date_1 = datetime.datetime.strptime(date[pairs_in2[idx][1]], "%y%m%d")
        date_2 = datetime.datetime.strptime(date[pairs_in2[idx][0]], "%y%m%d")
        temp_base = date_2 - date_1
        btemp = abs(temp_base.days)
        if abs_perp > perp_max:
            pass
        elif btemp > temp_max:
            pass
        else:
            bperp.append(perp)
            pairs.append(pairs_in2[idx])

    fig = plt.figure()
    ax = fig.add_subplot(111)
    datelist = []
    for i in xrange(len(date)):
        datelist.append(datetime.datetime.strptime(date[i], '%y%m%d'))


#    location_base = array(location) - location[0]
    location_base = array(location)
    ax.plot([datelist], [location_base], 'ro')
    for k, j in pairs:
        date_1 = datelist[k]
        date_2 = datelist[j]
        ax.plot([date_1, date_2], [location_base[k], location_base[j]], 'b')
    fig.suptitle('Baselines')
    plt.ylabel('Orbital Location')
    plt.xlabel('Time (years)')
    #    plt.xticks(rotation = 45)

    plt.xlim([(datelist[0] - (datetime.timedelta(90))),
              (datelist[-1] + (datetime.timedelta(90)))])

    fig.savefig('Pairs_' + str(dir) + '.png')

    print 'PAIRS: ' + str(len(pairs))
    return pairs, bperp
Ejemplo n.º 15
0
def square_mesh(N):
    """Build an uniform triangular mesh on unit square."""
    xs,ys = np.meshgrid(np.linspace(0,1,N),np.linspace(0,1,N))
    xs = xs.flatten(1)
    ys = ys.flatten(1)
    _,_,t,_ = triang.delaunay(xs,ys)
    p = np.vstack((xs,ys)).T

    return Trimesh(p,t)
Ejemplo n.º 16
0
def plot_delaunay(pts):
    x = pts[:, 0]
    y = pts[:, 1]
    cens, edg, tri, neig = triang.delaunay(x, y)
    for t in tri:
        t_i = [t[0], t[1], t[2], t[0]]
        pylab.plot(x[t_i], y[t_i])
    pylab.plot(x, y, 'o')
    pylab.show()
Ejemplo n.º 17
0
def triangulated_surface(x,y,z):
    """
    3d surface plot of irregularly space samples. Surface is found by tessulating XY plane.
    """

    # Create a triangulation of our region.
    _, _, tri_points, _ = delaunay(x, y)

    data = np.array([x,y,z]).T

    # Construct the triangles for the surface.
    verts = np.array([[data[i], data[j], data[k]] for (i,j,k) in tri_points])

    # To get a coloured plot, we need to assign a value to each face that
    # dictates the colour.  In this case we'll just use the average z
    # co-ordinate of the three triangle vertices.  One of these values is
    # required for each face (triangle).
    z_color = np.array([(np.sum(v_p[:,2]) / 3.0) for v_p in verts])

    # Choiced for colour maps are :
    #   autumn bone cool copper flag gray hot hsv jet pink prism spring summer
    #   winter spectral
    cm = pl.cm.get_cmap("jet")

    # Our triangles are now turned into a collection of polygons using the
    # vertex array.  We assign the colour map here, which will figure out its
    # required ranges all by itself.
    triCol = Poly3DCollection(verts, cmap=cm)

    triCol.set_edgecolor('k')
    triCol.set_linewidth(0.1)

    # Set the value array associated with the polygons.
    triCol.set_array(z_color)

    # Create the plotting figure and the 3D axes.
    fig = pl.figure()
    ax = Axes3D(fig)

    # Add our two collections of 3D polygons directly.  The collections have all of
    # the point and color information.  We don't need the add_collection3d method,
    # since that method actually converts 2D polygons to 3D polygons.  We already
    # have 3D polygons.
    ax.add_collection(triCol)

    # Add a label, for interest
    #ax.text3D(0.0, 0.0, 2.1, "Peak/Trough")

    # If we don't bound the axes correctly the display will be off.
    ax.set_xlim3d(x.min(), x.max())
    ax.set_ylim3d(y.min(), y.max())
    ax.set_zlim3d(z.min(), z.max())

    # We could also print to a file here.
    pl.show()

    return ax
Ejemplo n.º 18
0
def triangulated_surface(x, y, z):
    """
    3d surface plot of irregularly space samples. Surface is found by tessulating XY plane.
    """

    # Create a triangulation of our region.
    _, _, tri_points, _ = delaunay(x, y)

    data = np.array([x, y, z]).T

    # Construct the triangles for the surface.
    verts = np.array([[data[i], data[j], data[k]] for (i, j, k) in tri_points])

    # To get a coloured plot, we need to assign a value to each face that
    # dictates the colour.  In this case we'll just use the average z
    # co-ordinate of the three triangle vertices.  One of these values is
    # required for each face (triangle).
    z_color = np.array([(np.sum(v_p[:, 2]) / 3.0) for v_p in verts])

    # Choiced for colour maps are :
    #   autumn bone cool copper flag gray hot hsv jet pink prism spring summer
    #   winter spectral
    cm = pl.cm.get_cmap("jet")

    # Our triangles are now turned into a collection of polygons using the
    # vertex array.  We assign the colour map here, which will figure out its
    # required ranges all by itself.
    triCol = Poly3DCollection(verts, cmap=cm)

    triCol.set_edgecolor('k')
    triCol.set_linewidth(0.1)

    # Set the value array associated with the polygons.
    triCol.set_array(z_color)

    # Create the plotting figure and the 3D axes.
    fig = pl.figure()
    ax = Axes3D(fig)

    # Add our two collections of 3D polygons directly.  The collections have all of
    # the point and color information.  We don't need the add_collection3d method,
    # since that method actually converts 2D polygons to 3D polygons.  We already
    # have 3D polygons.
    ax.add_collection(triCol)

    # Add a label, for interest
    #ax.text3D(0.0, 0.0, 2.1, "Peak/Trough")

    # If we don't bound the axes correctly the display will be off.
    ax.set_xlim3d(x.min(), x.max())
    ax.set_ylim3d(y.min(), y.max())
    ax.set_zlim3d(z.min(), z.max())

    # We could also print to a file here.
    pl.show()

    return ax
Ejemplo n.º 19
0
 def initPartition(self):
     if self.nDim == 1:
         self.partitionCenters = []
         self.partitionCells = []
         for i in range(self.nSamples-1):
             self.partitionCenters.append([self.tVec[0][i],self.tVec[0][i+1]])
             self.partitionCells.append([i,i+1])
     elif self.nDim == 2:
         (self.partitionCenters, _, self.partitionCells, _) = delaunay(self.tVec[0],self.tVec[1])
     self.nCells = len(self.partitionCells)
Ejemplo n.º 20
0
def select_pairs_delaunay(tempBaseList,perpBaseList,normalize=1):
    ## Select Pairs using Delaunay Triangulation based on temporal/perpendicular baselines
    ##
    ## Usage:
    ##     tempBaseList : list of temporal baseline
    ##     perpBaseList : list of perpendicular spatial baseline
    ##     normalize    : normalize temporal baseline to perpendicular baseline
    ##                    1 - enable  normalization, default
    ##                    0 - disable normalization
    ##
    ## Key points
    ##     1. Define a ratio between perpendicular and temporal baseline axis units (Pepe and Lanari, 2006, TGRS).
    ##     2. Pairs with too large perpendicular / temporal baseline or Doppler centroid difference should be removed
    ##        after this, using a threshold, to avoid strong decorrelations (Zebker and Villasenor, 1992, TGRS).
    ##
    ## Reference:
    ##     Pepe, A., and R. Lanari (2006), On the extension of the minimum cost flow algorithm for phase unwrapping
    ## of multitemporal differential SAR interferograms, IEEE TGRS, 44(9), 2374-2383.
    ##     Zebker, H. A., and J. Villasenor (1992), Decorrelation in interferometric radar echoes, IEEE TGRS, 30(5), 950-959.
    ##


    import matplotlib.delaunay as md

    ##### Generate Delaunay Triangulation based on temporal and spatial perpendicular baselines
    if normalize == 0:
        centers,edges,tri,neighbors = md.delaunay(tempBase,perpBase)
    else:
        ##### Ratio between perpendicular and temporal baselines (Pepe and Lanari, 2006, TGRS)
        tempBaseFacList = []
        temp2perp_scale = (max(perpBaseList)-min(perpBaseList)) / (max(tempBaseList)-min(tempBaseList))
        for tempBase in tempBaseList:
            #tempBaseFac = (tempBase - min(tempBaseList)) * temp2perp_scale + min(perpBaseList)
            tempBaseFac = tempBase * temp2perp_scale   # giving same result as the line above
            tempBaseFacList.append(tempBaseFac)
        centers,edges,tri,neighbors = md.delaunay(tempBaseFacList,perpBaseList)

    ## The delaunay pairs do not necessarily have the indexes with lowest 
    ## first, so let's arrange and sort the delaunay pairs
    delaunayPairs = edges.tolist()
    delaunayPairs = pair_sort(delaunayPairs)

    return delaunayPairs
Ejemplo n.º 21
0
def test_data(npoints):
    #A simple testing function that generate random triangles
    # 10 random points (x,y) in the plane
    import numpy
    import matplotlib.delaunay as triang
    x, y = numpy.array(numpy.random.standard_normal((2, npoints)))
    z = numpy.array(numpy.random.standard_normal(npoints))
    points = []
    for i in range(npoints):
        points.append((x[i], y[i], z[i]))
    cens, edg, tri, neig = triang.delaunay(x, y)
    return points, tri
Ejemplo n.º 22
0
def test_data(npoints):
    #A simple testing function that generate random triangles
    # 10 random points (x,y) in the plane
    import numpy
    import matplotlib.delaunay as triang
    x,y =  numpy.array(numpy.random.standard_normal((2,npoints)))
    z =  numpy.array(numpy.random.standard_normal(npoints))
    points=[]
    for i in range(npoints):
            points.append((x[i],y[i],z[i]))
    cens,edg,tri,neig = triang.delaunay(x,y)
    return points, tri 
Ejemplo n.º 23
0
    def __init__(self, boundary_callable=CircleBoundary(), sample_count=20):
        '''
        :param boundary_callable: a callable we can sample sample_count times in [0,1)
        :param sample_count: how many points to sample from boundary_callable
        if boundary function is of that fancy cas package we could sample
        weighed by the absolute value of the gradient. otherwise sampling is uniform
        '''
        super(PrescribedBoundaryGrid, self).__init__()
        fac = 1 / sample_count
        self._px = np.array([boundary_callable(p * fac)[0] for p in range(sample_count)])
        self._py = np.array([boundary_callable(p * fac)[1] for p in range(sample_count)])
        self._vertices = zip(self._px, self._py)

        self._centers, _, triangles, self._neighbours_ids = delaunay(self._px, self._py)
        self._edges = []
        for ids in triangles:
            self._edges.extend([self.Edge(ids[i[0]], ids[i[1]]) for i in [(0, 1), (1, 2), (2, 0)]])

        self._triangles = [self.Triangle(x, self._edges) for x in triangles]
        self._sizes = {0: len(self._triangles), 1: len(self._edges), 2: len(self._px)}
        self.__subentities = list(xrange(self.dim + 1))
        self.__subentities[2] = np.array([c.vertices for c in self._triangles], dtype='int32')
        self.__subentities[1] = np.array([c.edges for c in self._triangles], dtype='int32')
        self.__subentities[0] = np.arange(len(self._triangles), dtype='int32')[:, np.newaxis]
        self.__embed_A = np.empty((self._sizes[0], 2, 2))
        self.__embed_B = np.empty((self._sizes[0], 2))

        for i, triangle in enumerate(self._triangles):
            x = [(self._px[triangle.vertices[j]], self._py[triangle.vertices[j]]) for j in (0, 1, 2)]
            W = np.array([[x[0][0], x[0][1], 0,       0,       1, 0],
                          [0,       0,       x[0][0], x[0][1], 0, 1],
                          [x[1][0], x[1][1], 0,       0,       1, 0],
                          [0,       0,       x[1][0], x[1][1], 0, 1],
                          [x[2][0], x[2][1], 0,       0,       1, 0],
                          [0,       0,       x[2][0], x[2][1], 0, 1]])
            K = np.array([0, 0, 0, 1, 1, 1])
            try:
                R = np.linalg.solve(W, K)
            except np.linalg.linalg.LinAlgError, e:
                import pprint
                self.logger.critical(pprint.pformat(K))
                self.logger.critical(pprint.pformat(W))
                self.logger.error(pprint.pformat(self._vertices))
                raise e
            self.__embed_A[i] = [[R[0], R[1]],
                                 [R[2], R[3]]]
            self.__embed_B[i] = [R[4], R[5]]
Ejemplo n.º 24
0
def main(argv=None):
    """."""
    global xl, yl, zl, xyl, xa, ya, cens, edgs, tris, neighs, triPts, trWithPoint
    # global width, height
    if argv is None:
        argv = sys.argv
    # generate_points()
    read_points()

    for i in range(len(xl)):
        xyl.append([xl[i], yl[i]])
        xyzl.append([xl[i], yl[i], zl[i]])
    # transform array data to list data (for delaunay())
    xa = numpy.array(xl)
    ya = numpy.array(yl)
    cens, edgs, triPts, neighs = triang.delaunay(xa, ya)
    intersections = 0
    for i in range(len(triPts)):
        triNormal.append(normal(xyzl[triPts[i][0]], xyzl[triPts[i][1]], xyzl[triPts[i][2]]))
    find_path()
    print("Path length: {}".format(path_length(path_edges)))
    print("Line segments: {}".format(path_edges))
    glutInit(argv)
    glutInitWindowSize(width, height)
    glutCreateWindow("Mount Elk")
    glClearDepth(1.0)
    glEnable(GL_DEPTH_TEST)
    glClearColor(1.0, 1.0, 1.0, 0.0)
    glShadeModel(GL_FLAT)
    glEnable(GL_COLOR_MATERIAL)
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
    glEnable(GL_DEPTH_TEST)
    glutInitWindowPosition(100, 100)
    glLightfv(GL_LIGHT0, GL_POSITION, lightOnePosition)
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightOneColor)
    glEnable(GL_LIGHT0)
    glEnable(GL_LIGHTING)
    glEnable(GL_RESCALE_NORMAL)
    glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE)
    glEnable(GL_COLOR_MATERIAL)
    glutDisplayFunc(display3D)
    glutReshapeFunc(reshape3D)
    glutKeyboardFunc(keyboard)
    generate_dl()
    glutMainLoop()
    return
Ejemplo n.º 25
0
    def _compute(self, config):
        """ Calculate the Delaunay triangulation.
            Sets triangles, a set of 3-tuples of particle ids in
                config.*images that form the vertices of a Delaunay triangle.

        @param self The object pointer
        
        @param config Config object
        
        @retval neighbors Dict with key=vertex,
            val=set of particle ids in *coords based on Delaunay triangulation

        """
        # use matplotlib's Delaunay triangulation
        # https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/tri/triangulation.py
        # centers is Ntri x 2 float array of circumcenter x,y coords (ie vertices in Voronoi)
        # edges is N? x 2 int array of indices defining triangle edges
        # triangles is Ntri x 3 int array of triangle vertex indices, ordered counterclockwise
        # tri_nhbrs is Ntri x 3 int array of triangle indices that share edges (null = -1)
        #   tri_nhbrs[i,j] is the triangle that is the neighbor to the edge from
        #   point index triangles[i,j] to point index triangles[i,(j+1)%3].
        centers, edges, triangles_list, tri_nbhrs = delaunay.delaunay(config.ximages,
                                                                      config.yimages)

        # store triangles as set of tuples, only keeping those in or near
        triangles_set = set()
        for tri in triangles_list:
            if config.is_tri_in_image(tri[0], tri[1], tri[2]):
                triangles_set.add(tuple(sorted(tri)))

        # identify nearest neighbors in triangulation
        # nbhrs is a dict with key=vertex, val=set of neighbor particle ids
        # all particle indices are in original image
        nbhrs = dict(zip(config.indices, [set() for i in config.indices]))
        for tri in triangles_set:
            inds = [ip % int(config.N) for ip in tri]
            for ivert in range(3): # loop through triangle vertices
                for offset in [1,2]: # loop through the two neighboring vertices
                    nbhrs[inds[ivert]].add(inds[(ivert+offset)%3])

        # return neighbors and triangles
        self._triangles = triangles_set
        return nbhrs
Ejemplo n.º 26
0
def lloyd(xn,yn):
    f = open('points.in','w')
    f.write("2 rbox %d D2\n" % len(xn))
    f.write("%d\n" % len(xn))
    for p in range(len(xn)):
        f.write("%e " % xn[p])
        f.write("%e\n" % yn[p])
    f.close()

    for count in range(20):
        cmd = 'cat points.in | qvoronoi s o QJ'
        sub_process = Popen(cmd, shell=True,stdout=PIPE,stderr=PIPE)
        output = sub_process.communicate()
        lines = [line.split() for line in output[0].split('\n') if line]

        setsize = len(lines)
        nv = int(lines[1][0])
        coord = lines[2:2+nv]
        ref = lines[2+nv:]

        for P in range(len(xn)):
            cx = 0.
            cy = 0.

        for V in range(int(ref[P][0])):
            cx += float(coord[int(ref[P][V+1])][0])
            cy += float(coord[int(ref[P][V+1])][1])

        n = int(ref[P][0])
        xn[P] = xn[P] - (xn[P]-cx/n)/15.
        yn[P] = yn[P] - (yn[P]-cy/n)/15.

        f = open('points.in','w')
        f.write("2 rbox %d D2\n" % len(xn))
        f.write("%d\n" % len(xn))
        for p in range(len(xn)):
            f.write("%e " % xn[p])
            f.write("%e\n" % yn[p])
        f.close()

    return triang.delaunay(xn,yn)
Ejemplo n.º 27
0
def main(argv=None):
    """."""
    global xl, yl, xyl, xa, ya, cens, edgs, triPts, lp
    if argv is None:
        argv = sys.argv
    generate_points()
    for i in range(len(xl)):
        xyl.append([xl[i], yl[i]])
    xa = numpy.array(xl)  # transform array data to list data (for delaunay())
    ya = numpy.array(yl)
    cens, edgs, triPts, neigs = triang.delaunay(xa, ya)
    glutInit(argv)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
    glutInitWindowSize(width, height)
    glutInitWindowPosition(100, 100)
    glutCreateWindow("Delaunay triangulation")
    glutDisplayFunc(display)
    glutReshapeFunc(reshape)
    glutKeyboardFunc(keyboard)
    glutMainLoop()
    return
Ejemplo n.º 28
0
def delaunay_triangulation(portals):
    xx = []
    yy = []
    ids = []
    names = []

    for p in portals:
        ids.append(p['id'])
        names.append(p['name'])
        xx.append(p['coords']['gmaps']['lat'])
        yy.append(p['coords']['gmaps']['long'])

    xx = numpy.array(xx)
    yy = numpy.array(yy)

    cens,edg,tri,neig = triang.delaunay(xx,yy)

    print min(xx), max(xx)
    print min(yy), max(yy)

    return {'cens': cens, 'edg': edg, 'tri': tri, 'neig': neig, 'xx': xx, 'yy': yy, 'id': ids, 'names': names}
Ejemplo n.º 29
0
def get_dely(d, nodes):
    """
    get the delaunay tesselation
    return centers, triangles, neighbors, bars, barmids
    """
    x,y = nodes[0].squeeze(), nodes[1].squeeze()
    centers, bars, tris, neighs = delaunay.delaunay(*nodes)#x,y)#*nodes)

    # remove outside triangles
    kin = nonzero( d(*centers.T)<geps)
    centers = centers[kin].T
    tris = tris[kin]
    neighs = neighs[kin]
    
    # remove outside bars
    barmids = .5 * (nodes[:,bars[:,0]] + nodes[:,bars[:,1]])
    # kin = nonzero(d(*barmids)<geps)
    bars = bars[d(*barmids)<geps]

    barmids = .5 * (nodes[:,bars[:,0]] + nodes[:,bars[:,1]])
    return centers, tris, neighs, bars, barmids
Ejemplo n.º 30
0
 def tessilate(self, X,Y,Z):
     x1 = X[0]
     y1 = Y[0]
     z1 = Z[0]
     
     hasX = self.hasCoordinate(x1,X)
     hasY = self.hasCoordinate(y1,Y)
     hasZ = self.hasCoordinate(z1,Z)
     n = []
     if hasX:
         n.append(X)
     if hasY:
         n.append(Y)
     if hasZ:
         n.append(Z)
     if len(n) < 2:
            print "something is wrong"
            tri = []
            return tri
     cens,edg,tri,neig = triang.delaunay(n[0], n[1])
     return tri
Ejemplo n.º 31
0
    def _calc_triangles(self, ax=None):
        if ax is None:
            fig = pl.figure()
            ax = fig.add_subplot(111)
        if self.gridtype != 'regular':
            raise ValueError('only supported for regular grids so far!')
        if self._lon0.ndim != 2:
            raise ValueError('2D grid required!')

        ny, nx = self._lon0.shape
        lons = []
        lats = []
        for i in range(1, ny - 1):  # todo revise this calculation method!!!
            for j in range(1, nx - 1):
                # half way to corner neighbors?

                # upper left
                lons.append(self._lon0[i - 1, j - 1] + 0.5 *
                            (self._lon0[i, j] - self._lon0[i - 1, j - 1]))
                lats.append(self._lat0[i - 1, j - 1] + 0.5 *
                            (self._lat0[i, j] - self._lat0[i - 1, j - 1]))

                # lower right
                lons.append(self._lon0[i, j] + 0.5 *
                            (self._lon0[i + 1, j + 1] - self._lon0[i, j]))
                lats.append(self._lat0[i, j] + 0.5 *
                            (self._lat0[i + 1, j + 1] - self._lat0[i, j]))

                # lower left
                # lons.append(self._lon0[i-1,j]+0.5
                #*(self._lon0[i+1,j+1]-self._lon0[i,j]))
                # add also current center coordinate for
                # plotting vizualization
                lons.append(self._lon0[i, j])
                lats.append(self._lat0[i, j])
        lons = np.asarray(lons)
        lats = np.asarray(lats)
        cens, edg, tri, neig = triang.delaunay(lons, lats)
        self._do_delaunay_plot(tri, lons, lats, ax)
Ejemplo n.º 32
0
    def _calc_triangles(self, ax=None):
        if ax is None:
            fig = pl.figure()
            ax = fig.add_subplot(111)
        if self.gridtype != 'regular':
            raise ValueError('only supported for regular grids so far!')
        if self._lon0.ndim != 2:
            raise ValueError('2D grid required!')

        ny, nx = self._lon0.shape
        lons = []
        lats = []
        for i in range(1, ny - 1):   # todo revise this calculation method!!!
            for j in range(1, nx - 1):
                # half way to corner neighbors?

                # upper left
                lons.append(self._lon0[i - 1, j - 1] + 0.5
                            * (self._lon0[i, j] - self._lon0[i - 1, j - 1]))
                lats.append(self._lat0[i - 1, j - 1] + 0.5
                            * (self._lat0[i, j] - self._lat0[i - 1, j - 1]))

                # lower right
                lons.append(self._lon0[i, j] + 0.5
                            * (self._lon0[i + 1, j + 1] - self._lon0[i, j]))
                lats.append(self._lat0[i, j] + 0.5
                            * (self._lat0[i + 1, j + 1] - self._lat0[i, j]))

                # lower left
                # lons.append(self._lon0[i-1,j]+0.5
                #*(self._lon0[i+1,j+1]-self._lon0[i,j]))
                # add also current center coordinate for
                # plotting vizualization
                lons.append(self._lon0[i, j])
                lats.append(self._lat0[i, j])
        lons = np.asarray(lons)
        lats = np.asarray(lats)
        cens, edg, tri, neig = triang.delaunay(lons, lats)
        self._do_delaunay_plot(tri, lons, lats, ax)
def main(argv=None):
    """."""
    global xl, yl, xyl, xa, ya, cens, edgs, tris, neighs, triPts, trWithPoint
    if argv is None:
        argv = sys.argv
    generate_points()
    for i in range(len(xl)):
        xyl.append([xl[i], yl[i]])
    # transform array data to list data (for delaunay())
    xa = numpy.array(xl)
    ya = numpy.array(yl)
    cens, edgs, triPts, neighs = triang.delaunay(xa, ya)

    find_intersected_edges()
    # find_edges_on_path()

    # print results
    print "Intersected edges:"
    for edge in intersected_line_segments:
        print("({x1}, {y1}) - ({x2}, {y2})".format(x1=xl[edge[0]],
                                                   y1=yl[edge[0]],
                                                   x2=xl[edge[1]],
                                                   y2=yl[edge[1]]))
    if (intersection_points):
        print "\nIntersection points:"
        for intersection in intersection_points:
            print("({x}, {y})".format(x=intersection[0], y=intersection[1]))

    glutInit(argv)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
    glutInitWindowSize(width, height)
    glutInitWindowPosition(100, 100)
    glutCreateWindow("Delaunay triangulation")
    glutDisplayFunc(display)
    glutReshapeFunc(reshape)
    glutKeyboardFunc(keyboard)
    glutMainLoop()
    return
Ejemplo n.º 34
0
 def find_minimum_weight_matching(self):
     """ finds a minimum weight perfect matching"""
     print "computing delaunay of odd_deg_nodes"
     circumcenters, edges, tri_points, tri_neighbors = triang.delaunay(self.x[self.odd_deg_nodes], self.y[self.odd_deg_nodes])
     o = nx.Graph()
     o.dist_func = lambda i,j: -self.euclidean_dist(i,j)
     for i, j in edges:
         mi = self.odd_deg_nodes[i]
         mj = self.odd_deg_nodes[j]
         o.add_edge(mi, mj, weight=o.dist_func(mi, mj))
     self.o = o
     print '#edges:', len(edges), '#nodes:', len(o.nodes()), len(self.odd_deg_nodes)
     print "computing minimum matching"
     t1 = time.time()
     mates = max_weight_matching(o, maxcardinality=True)
     t2 = time.time()
     print "took %s" % (t2-t1)        
     m = nx.Graph()
     for i in mates.keys():
         m.add_edge(i,mates[i], weight=self.g.dist_func(i,mates[i]))
     print '#edges:', len(m.edges()), '#nodes:', len(m.nodes())
     self.plot_edges(m.edges(),'r-',2)
     self.m = m
def main(
    displayFunction,
    argv=None,
):
    """."""
    global xl, yl, xyl, xa, ya, cens, edgs, tris, neighs, triPts, dcel
    if argv is None:
        argv = sys.argv
    generate_points(True)
    xa = numpy.array(xl)  # transform array data to list data (for delaunay())
    ya = numpy.array(yl)
    cens, edgs, triPts, neighs = triang.delaunay(xa, ya)
    # Generate the DCEL
    dcel = DCEL.from_delaunay_triangulation(xl, yl, triPts, cens)
    glutInit(argv)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
    glutInitWindowSize(width, height)
    glutInitWindowPosition(100, 100)
    glutCreateWindow("Delaunay triangulation")
    glutDisplayFunc(displayFunction)
    glutReshapeFunc(reshape)
    glutKeyboardFunc(keyboard)
    glutMainLoop()
    return
Ejemplo n.º 36
0
def display_tile_stacked(tile):
    real_x_pos = []
    real_y_pos = []
    real_tile = []
    point = []

    for starfield_position in tile:
        real_x_pos.append((starfield_position[6] * 4800) / 10)
        real_y_pos.append((starfield_position[7] * 4800) / 10)

        point.append(((starfield_position[6] * 4800) / 10, (starfield_position[7] * 4800) / 10))

        real_tile_x = starfield_position[2]
        real_tile_y = starfield_position[3]

        real_tile.append(real_tile_x + 1.5 * real_tile_y + 9.323)

    # plt.ylim([-10, 4810])
    # plt.xlim([-10, 4810])
    # plt.title('Starfield - True Gridded Star Single Subfield')
    # plt.scatter(real_x_pos, real_y_pos, c=real_tile, marker='+')
    # plt.ion()
    # plt.draw()
    # plt.show()

    real_x_pos = numpy.array(real_x_pos)
    real_y_pos = numpy.array(real_y_pos)

    cens, edg, tri, neig = triang.delaunay(real_x_pos, real_y_pos)

    for t in tri:
        t_i = [t[0], t[1], t[2], t[0]]
        plt.plot(real_x_pos[t_i], real_y_pos[t_i])

    plt.plot(real_x_pos, real_y_pos, 'o')
    plt.show()
Ejemplo n.º 37
0
def triangle(a):
    xBis, yBis = transforme(a)
    xBis, yBis = np.array(xBis), np.array(yBis)
    cens, edg, tri, neig = triang.delaunay(xBis, yBis)

    taille = len(a)
    l = taille / 6
    b = 0
    for t in tri:
        # t[0], t[1], t[2] are the points indexes of the triangle
        d1, d2, d3 = d(xBis[t[0]], yBis[t[0]], xBis[t[1]],
                       yBis[t[1]]), d(xBis[t[1]], yBis[t[1]], xBis[t[2]],
                                      yBis[t[2]]), d(xBis[t[2]], yBis[t[2]],
                                                     xBis[t[0]], yBis[t[0]])
        if (d1 < l and d2 < l and d3 < l):
            t_i = [t[0], t[1], t[2], t[0]]
            if (b):
                pylab.fill(xBis[t_i], yBis[t_i], "black")
                b = 0
            else:
                b = 1

        #pylab.plot(xBis, yBis, 'o')
        pylab.show()
Ejemplo n.º 38
0
Archivo: util.py Proyecto: shdwdln/fos
def find_triangulation2d(x, y):
    cens, edg, tri, neig = triang.delaunay(x, y)
    return tri
Ejemplo n.º 39
0
             [max(m_contour[:, 0]),
              max(m_contour[:, 1]), 1],
             [max(m_contour[:, 0]),
              min(m_contour[:, 1]), 1]])  ##pay attention to the sequence
        #data_brect = np.dstack(( data_brect[:,1], data_brect[:,0] ))[0]
        #model_brect = np.dstack(( model_brect[:,1], model_brect[:,0] ))[0]

        model = np.concatenate((self.model, model_brect[:, 0:2]))
        data = np.concatenate((self.data, data_brect[:, 0:2]))

        x = data[:, 0]
        y = data[:, 1]
        tri = align.triangulate_points(x, y)
        fp = np.dstack((data[:, 1], data[:, 0], np.ones(data.shape[0])))[0]
        tp = np.dstack((model[:, 1], model[:, 0], np.ones(model.shape[0])))[0]
        #nphoto = pw_affine(img,img2,fp.T,tp.T,tri)
        '''
        aft = align.compute_affine(data, model)
        
        shape = img2.shape
        nphoto = cv2.warpAffine(img, aft, (shape[1], shape[0]))
        
        cv2.imshow('img', nphoto)
        cv2.waitKey(0)
        '''
        self.sigPiecewiseRequested.emit((fp.T, tp.T, tri))


if __name__ == '__main__':
    delaunay()
Ejemplo n.º 40
0
 def delaunay(pts):
     _, _, tri, _ = md.delaunay(pts[:, 0], pts[:, 1])
     return tri
Ejemplo n.º 41
0
 def delaunay(pts):
     _, _, tri, _ = md.delaunay(pts[:,0], pts[:,1])
     return tri
Ejemplo n.º 42
0
        osgb_point = Point(new_x, new_y, srid=27700)
        wgs84_point = osgb_point.transform(4326, clone=True)
        wgs84_postcode_and_points.append(('infinity{0:06d}'.format(i), wgs84_point))

    if args.postcode_points:
        output_postcode_points_kml(
            join(postcodes_output_directory, 'postcode-points.kml'),
            wgs84_postcode_and_points,
        )

    x = np.array(x)
    y = np.array(y)

    print("Calculating the Delaunay Triangulation...")

    ccs, edges, triangles, neighbours = delaunay(x, y)

    point_to_triangles = [[] for _ in x]

    for i, triangle in enumerate(triangles):
        for point_index in triangle:
            point_to_triangles[point_index].append(i)

    # Now generate the KML output:

    print("Now generating KML output")

    def output_kml(point_index_and_triangle_indices):
        point_index, triangle_indices = point_index_and_triangle_indices

        centre_x = x[point_index]
Ejemplo n.º 43
0
execfile('/Users/wkerzend/Documents/science/thesis/thesis/tex/thesis_plot_defaults.py')

import matplotlib.delaunay as triang
import pylab
import numpy

np.random.seed(250819801106)


# 10 random points (x,y) in the plane
x,y =  numpy.array(numpy.random.standard_normal((2,15)))
cens,edg,tri,neig = triang.delaunay(x,y)
clf()
for t in tri:
 # t[0], t[1], t[2] are the points indexes of the triangle
 t_i = [t[0], t[1], t[2], t[0]]
 pylab.plot(x[t_i],y[t_i], color='k')
ax = gca()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.axes.set_frame_on(False)
savefig('simple_delauney.pdf')
pylab.plot(x,y,'ko')
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 16:41:10 2016

@author: user
"""
from PIL import Image
from numpy import *
import matplotlib.delaunay as md
x, y = array(random.standard_normal((2, 100)))
centers, edges, tri, neighbors = md.delaunay(x, y)
figure()
for t in tri:
    t_ext = [t[0], t[1], t[2], t[0]]  # add first point to end
    plot(x[t_ext], y[t_ext], 'r')
plot(x, y, '*')
axis('off')
show()
Ejemplo n.º 45
0
execfile(
    '/Users/wkerzend/Documents/science/thesis/thesis/tex/thesis_plot_defaults.py'
)

import matplotlib.delaunay as triang
import pylab
import numpy

np.random.seed(250819801106)

# 10 random points (x,y) in the plane
x, y = numpy.array(numpy.random.standard_normal((2, 15)))
cens, edg, tri, neig = triang.delaunay(x, y)
clf()
for t in tri:
    # t[0], t[1], t[2] are the points indexes of the triangle
    t_i = [t[0], t[1], t[2], t[0]]
    pylab.plot(x[t_i], y[t_i], color='k')
ax = gca()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.axes.set_frame_on(False)
savefig('simple_delauney.pdf')
pylab.plot(x, y, 'ko')
Ejemplo n.º 46
0
def main():
    clos = parse()
    print(clos)
    dat = open(clos.infile, 'r').readlines()
    data = []
    for d in dat:
        data.append(d.split())

    dates = []
    tbase = []
    pbase = []
    slcs = []
    prms = []
    for d in data:
        date = datetime.datetime.strptime(d[0], "%Y%m%d")
        if date.month >= clos.monthMin and date.month <= clos.monthMax:
            pbase.append(float(d[1]))
            dates.append(d[0])
            slcs.append(d[3])
            prms.append(os.path.splitext(d[3])[0] + '.PRM')
    print("************************************")
    print("Total # of scenes in %s: %d" % (clos.infile, len(data)))
    print("Total after filtering by month: %d" % len(dates))
    print("************************************")
    '''calculate tbase from d1 to dni'''
    d1 = datetime.datetime.strptime(dates[0], "%Y%m%d")
    for d in dates:
        d2 = datetime.datetime.strptime(d, "%Y%m%d")
        diff = d2 - d1
        tbase.append(diff.days)
    '''
    This returns a list of all possible pairs of dates.  Should eliminate
    those pairs with bad bperp and doppler overlap and leave elimination
    based on time for later since we can still use them if there is no
    other alternative.
    '''
    indexList = []
    for ni in range(len(dates)):
        indexList.append(ni)
    allPairs = list(itertools.combinations(indexList, 2))
    ## Lets remove the ones with bad doppler and baselines
    print("all possible pairs = " + str(len(allPairs)))
    allPairs = remove_bad_pairs(allPairs, pbase, tbase, clos.Bcrit, clos.Tcrit)
    print(
        "all pairs with baselines less than Bcrit (%d m) and Tcrit (%d days): %d"
        % (clos.Bcrit, clos.Tcrit, len(allPairs)))
    ''' 
    Do a delaunay triangulation to find the "best" pairs.
    The edges will contain index to the pairs we need. We apply a 
    weighting factor to the time baseline so that the space being
    triangulated is symetric (base on Pepe and Lanari (2006))
  
    After the pairs are selected we then eliminate pairs which 
    are not "good" due to perpendicular baseline and doppler overlap.
    We then add in the pairs with short temporal baselines (lengthDayMax).  
    '''
    tbaseFac = []
    for idx in range(len(tbase)):
        tbaseFac.append(tbase[idx] * (max(pbase) - min(pbase)) / (max(tbase)))
    centers, edges, tri, neighbors = md.delaunay(tbaseFac, pbase)
    delaunayPairs = edges.tolist()
    '''
    The delaunay pairs do not necessarily have the indexes with lowest 
    first, so let's arrange and sort the delaunay pairs
    '''
    for idx in range(len(delaunayPairs)):
        if delaunayPairs[idx][0] > delaunayPairs[idx][1]:
            index1 = delaunayPairs[idx][1]
            index2 = delaunayPairs[idx][0]
            delaunayPairs[idx][0] = index1
            delaunayPairs[idx][1] = index2
    delaunayPairs = sorted(delaunayPairs, key=itemgetter(0))
    ## Lets remove the ones with bad doppler and baselines
    print("delaunay possible pairs = " + str(len(delaunayPairs)))
    delaunayPairs = remove_bad_pairs(delaunayPairs, pbase, tbase, clos.Bcrit,
                                     clos.Tcrit)
    print(
        "delaunay pairs with baselines less than Bcrit (%d m) and Tcrit (%d days): %d"
        % (clos.Bcrit, clos.Tcrit, len(delaunayPairs)))
    ## Now lets add all additional pairs less than lengthDayMax from allPairs
    for idx in range(len(allPairs)):
        allPairs[idx] = list(allPairs[idx])
        if tbase[allPairs[idx][1]] - tbase[allPairs[idx]
                                           [0]] <= clos.lengthDayMax:
            if allPairs[idx] not in delaunayPairs:
                delaunayPairs.append(allPairs[idx])
    print("delaunay pairs with added pairs less than " +
          str(clos.lengthDayMax) + " days = " + str(len(delaunayPairs)))

    projectDir = os.getcwd()
    projectName = os.path.basename(projectDir)

    if clos.selectMethod == 'all':
        pairs = allPairs
    else:
        pairs = delaunayPairs

    dates_obj = [datetime.datetime.strptime(d, "%Y%m%d") for d in dates]
    if clos.dateSpan:
        """ This will filter out the pairs that don't span the date of interest """
        date_span = datetime.datetime.strptime(clos.dateSpan, "%Y-%m-%d")
        pairs = [
            igram for igram in pairs if dates_obj[igram[0]] < date_span
            and dates_obj[igram[1]] > date_span
        ]
        print("# of pairs spanning %s: %d" % (clos.dateSpan, len(pairs)))

    intf = open('intf.in', 'w')
    f = open('run_p2pTOPS', 'w')
    for igram in sorted(pairs):
        ndx1 = igram[0]
        ndx2 = igram[1]
        baseline = '%05.0f' % round(pbase[ndx1] - pbase[ndx2])
        temporalbaseline = '%04.0f' % round(tbase[ndx2] - tbase[ndx1])
        #        print(slcs[ndx1].split("_")[0]+":"+slcs[ndx2].split("_")[0])
        intf.write(slcs[ndx1].split("_")[0] + ":" + slcs[ndx2].split("_")[0] +
                   '\n')
        f.write(
            'p2p_S1A_TOPS.csh %s %s config.tops.txt\n' %
            (os.path.splitext(slcs[ndx1])[0], os.path.splitext(slcs[ndx2])[0]))
    intf.close()
    f.close()

    f = open('config.tops.txt', 'w')
    f.write('proc_stage = 4\n')
    f.write('topo_phase = 1\n')
    f.write('topo_shift = 1\n')
    f.write('switch_master = 0\n')
    f.write('filter_wavelength = 200\n')
    f.write('dec_factor = 2\n')
    f.write('threshold_snaphu = 0.1\n')
    f.write('switch_land = 1\n')
    f.write('defomax = 0\n')
    f.write('threshold_geocode = .10')
    f.close()

    plt.figure()
    for e in edges:
        x = [dates_obj[e[0]], dates_obj[e[1]]]
        y = [pbase[e[0]], pbase[e[1]]]
        plt.plot(x, y, '--', c='gray')
    for igram in sorted(pairs):
        ndx1 = igram[0]
        ndx2 = igram[1]
        x = [dates_obj[ndx1], dates_obj[ndx2]]
        y = [pbase[ndx1], pbase[ndx2]]
        plt.plot(x, y, 'b')
    plt.plot(dates_obj, pbase, 'ro')
    if clos.dateSpan:
        plt.axvline(datetime.datetime.strptime(clos.dateSpan, '%Y-%m-%d'),
                    ls='-',
                    color='g')
        plt.annotate('Event',
                     xy=(datetime.datetime.strptime(clos.dateSpan,
                                                    '%Y-%m-%d'), min(pbase)),
                     xycoords='data',
                     color='g')
    plt.xlabel('Date')
    plt.ylabel('Perpendicular Baseline (m)')
    projectName = os.path.basename(os.getcwd())
    plt.title('SBAS Network - ' + projectName)
    plt.savefig(projectName + '_network.png', transparent=True)
    if clos.np:
        plt.show()
Ejemplo n.º 47
0
    center_x = rect_width / 2

    rect_height = (bottom - top)
    center_y = rect_height / 2

    #compute the amount to offset the points by
    offset_from_center_x = width / 2 - (center_x) - left
    offset_from_center_y = height / 2 - (center_y) - top

    #actually offset the points
    points = [(x + offset_from_center_x,
               y + offset_from_center_y)
              for x, y in points]

    #compute the delunay triangulation
    cens, edg, tri, neig = triang.delaunay([x for x, y in points],
                                        [y for x, y in points])
    if args.color_edges:
        #perform edge coloring
        edg_colors = edge_color(edg)

        #remember the physical colors we've used
        physical_colors = defaultdict(generate_hipster_color)

    #draw the delunay triangulation lines
    for i in range(0, len(edg)):
        start, end = edg[i]
        x = points[start][0]
        y = points[start][1]
        x2 = points[end][0]
        y2 = points[end][1]
        if args.color_edges:
Ejemplo n.º 48
0
def triangulate_points(x, y):
    # Delaunay triangulation of 2D points. """
    centers, edges, tri, neighbors = md.delaunay(x, y)
    return tri
Ejemplo n.º 49
0
def triangulate_points(x, y):
    """ 二维点的 Delaunay 三角剖分 """

    centers, edges, tri, neighbors = md.delaunay(x, y)
    return tri
Ejemplo n.º 50
0
 def build_mesh(self):
     print 'triangulating ...'
     circumcenters, edges, tri_points, tri_neighbors = triang.delaunay(self.x, self.y)
     self.tri_points = tri_points
     self.edges = edges
Ejemplo n.º 51
0
	is_color = len(fromim.shape) == 3
	# create image to warp to (needed if iterate colors)
	im_t = zeros(im.shape, 'uint8')
	for t in tri:
		# compute affine transformation
		H = homography.Haffine_from_points(tp[:,t],fp[:,t])						        
		if is_color:
			for col in range(fromim.shape[2]):
				im_t[:,:,col] = ndimage.affine_transform(fromim[:,:,col],H[:2,:2],(H[0,2],H[1,2]),im.shape[:2])
			else:
				im_t = ndimage.affine_transform(fromim,H[:2,:2],(H[0,2],H[1,2]),im.shape[:2])																
			# alpha for triangle
			alpha = alpha_for_triangle(tp[:,t],im.shape[0],im.shape[1])																							        		# add triangle to image
			im[alpha>0] = im_t[alpha>0]
	return im

x,y = array(np.random.standard_normal((2,100)))
centers,edges,tri,neighbors = md.delaunay(x,y)
figure()
gray()
subplot(121)
axis('off')
plot(x,y,'*')
for t in tri:
	t_ext = [t[0], t[1], t[2], t[0]] # add first point to end
	subplot(122)
	plot(x[t_ext],y[t_ext],'r')
plot(x,y,'*')
axis('off')
show()
Ejemplo n.º 52
0
def surfplot(dbc, agent_name, filter, colormap = 'hot'):

    global axes

    P_copyFail = []
    P_c = []
    fitness = []

    # We should only include samples from the database using the latest commit of Simulate.py, and using the latest
    # commit of the agent script being plotted. First, find the latest entry of this agent script, and note the
    # hashes.

    sample = dbc.find({'agent_name': filter['agent_name']}, sort = [('timestamp', -1)], limit = 1).next()
    filter['agent_hash'] = sample['agent_hash']
    filter['simulate_hash'] = sample['simulate_hash']
    
    for sample in dbc.find(filter):
        P_copyFail.append(sample['param_P_copyFail'])
        P_c.append(sample['param_P_c'])
        fitness.append(sample['fitness'])

    circumcenters, edges, tri_points, tri_neighbors = dl.delaunay(P_copyFail, P_c)
    
    # Construct the triangles for the surface.
    verts = ( [ np.array( [ [ P_copyFail[ t[0] ] , P_c[ t[0] ] , fitness[ t[0] ] ]
                          , [ P_copyFail[ t[1] ] , P_c[ t[1] ] , fitness[ t[1] ] ]
                          , [ P_copyFail[ t[2] ] , P_c[ t[2] ] , fitness[ t[2] ] ] ] )
                for t in tri_points
              ]
            )
    # To get a coloured plot, we need to assign a value to each face that dictates
    # the colour.  In this case we'll just use the average z co-ordinate of the
    # three triangle vertices.  One of these values is required for each face
    # (triangle).
    z_color = np.array( [ ( np.sum( v_p[:,2] ) / 5000.0 ) for v_p in verts ] )
    
    # Choiced for colour maps are :
    #   autumn bone cool copper flag gray hot hsv jet pink prism spring summer
    #   winter spectral
    cm = plt.cm.get_cmap(colormap)
    
    # Our triangles are now turned into a collection of polygons using the vertex
    # array.  We assign the colour map here, which will figure out its required
    # ranges all by itself.
    triCol = art3d.Poly3DCollection( verts, cmap=cm )
    
    triCol.set_edgecolor('k')
    triCol.set_linewidth( 1.0 )
    
    # Set the value array associated with the polygons.
    triCol.set_array(z_color)

    # Add our two collections of 3D polygons directly.  The collections have all of
    # the point and color information.  We don't need the add_collection3d method,
    # since that method actually converts 2D polygons to 3D polygons.  We already
    # have 3D polygons.
    axes.add_collection(triCol)
    
    if axes.get_xlabel() == '':
        xvals = P_copyFail
        yvals = P_c
        zvals = fitness
    #else:   
        #xvals = concatenate((axes.get_xlim3d(), P_copyFail))
        #yvals = concatenate((axes.get_ylim3d(), P_c))
        #zvals = concatenate((axes.get_ylim3d(), fitness))
    
    axes.set_xlim3d(np.min(xvals), np.max(xvals))
    axes.set_ylim3d(np.min(yvals), np.max(yvals))
    axes.set_zlim3d(0, np.max([np.max(zvals), 1500.0]))
    
    axes.set_xlabel('P_copyFail')
    axes.set_ylabel('P_c')
    axes.set_zlabel('fitness')
Ejemplo n.º 53
0
    # plota boundingbox
    # rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
    #                           fill=False, edgecolor='red', linewidth=2)
    # ax1.add_patch(rect)
    x0 = region['Centroid'][1]
    y0 = region['Centroid'][0]
    # pontos.append([x0, y0])
    pontos.append([minc, minr])
    pontos.append([maxc, minr])
    pontos.append([minc, maxr])
    pontos.append([maxc, maxr])

pontos = np.array(pontos)

# calculamos pontos dos triânbulos através de Delaunay
cens, edg, tri, neig = triang.delaunay(pontos[:,0], pontos[:,1])
patches = []
cores = []
coords_tri = []
for t in tri:
  # t[0], t[1], t[2] are the points indexes of the triangle
  t_i = [t[0], t[1], t[2], t[0]]
  ax2.plot(pontos[:,0][t_i], pontos[:,1][t_i], 'k-', linewidth=.5)
  ax4.plot(pontos[:,0][t_i], pontos[:,1][t_i], 'w-', linewidth=.3)
  ax4.plot(pontos[:,0][t_i], pontos[:,1][t_i], 'wo', markersize=2)
  #print '---'
  t_i2 = [t[0], t[1], t[2]]
  #print pontos[:,[0,1]][t_i2]
  coords_tri.append([list(aa) for aa in list(pontos[:,[0,1]][t_i2])])
  x = pontos[:,0][t_i][0]
  y = pontos[:,1][t_i][0]
Ejemplo n.º 54
0
def triangulate_points(x, y):
    """ Delaunay triangulation of 2D points. """

    centers, edges, tri, neighbors = md.delaunay(x, y)
    return tri
Ejemplo n.º 55
0
def main():
    clos = parse()
    print(clos)
    dat = open(clos.infile,'r').readlines()
    data = []
    for d in dat:
        data.append(d.split())
  
    dates = []
    tbase = []
    pbase = []
    slcs = []
    prms = []
    for d in data:
      date=datetime.datetime.strptime(d[0],"%Y%m%d")
      if date.month >= clos.monthMin and date.month <= clos.monthMax:
          pbase.append(float(d[1]))
          dates.append(d[0])
          slcs.append(d[3])
          prms.append(os.path.splitext(d[3])[0]+'.PRM')
    print("************************************")
    print("Total # of scenes in %s: %d" % (clos.infile,len(data)))
    print("Total after filtering by month: %d" % len(dates))
    print("************************************")
  
    '''calculate tbase from d1 to dni'''
    d1 = datetime.datetime.strptime(dates[0],"%Y%m%d")
    for d in dates:
        d2 = datetime.datetime.strptime(d,"%Y%m%d")
        diff = d2-d1
        tbase.append(diff.days)
  
    '''
    This returns a list of all possible pairs of dates.  Should eliminate
    those pairs with bad bperp and doppler overlap and leave elimination
    based on time for later since we can still use them if there is no
    other alternative.
    '''
    indexList = []
    for ni in range(len(dates)): 
        indexList.append(ni)
    allPairs = list(itertools.combinations(indexList, 2))    
    ## Lets remove the ones with bad doppler and baselines
    print("all possible pairs = " + str(len(allPairs)))
    allPairs = remove_bad_pairs(allPairs,pbase,tbase,clos.Bcrit,clos.Tcrit)
    print("all pairs with baselines less than Bcrit (%d m) and Tcrit (%d days): %d" % (clos.Bcrit, clos.Tcrit, len(allPairs)))
  
    ''' 
    Do a delaunay triangulation to find the "best" pairs.
    The edges will contain index to the pairs we need. We apply a 
    weighting factor to the time baseline so that the space being
    triangulated is symetric (base on Pepe and Lanari (2006))
  
    After the pairs are selected we then eliminate pairs which 
    are not "good" due to perpendicular baseline and doppler overlap.
    We then add in the pairs with short temporal baselines (lengthDayMax).  
    '''
    tbaseFac = []
    for idx in range(len(tbase)): tbaseFac.append(tbase[idx] * (max(pbase) - min(pbase)) / (max(tbase)))
    centers, edges, tri, neighbors = md.delaunay(tbaseFac, pbase)
    delaunayPairs = edges.tolist()
    '''
    The delaunay pairs do not necessarily have the indexes with lowest 
    first, so let's arrange and sort the delaunay pairs
    '''
    for idx in range(len(delaunayPairs)):
        if delaunayPairs[idx][0] > delaunayPairs[idx][1]:
            index1 = delaunayPairs[idx][1]
            index2 = delaunayPairs[idx][0]
            delaunayPairs[idx][0] = index1
            delaunayPairs[idx][1] = index2
    delaunayPairs = sorted(delaunayPairs, key=itemgetter(0)) 
    ## Lets remove the ones with bad doppler and baselines
    print("delaunay possible pairs = " + str(len(delaunayPairs)))
    delaunayPairs = remove_bad_pairs(delaunayPairs,pbase,tbase,clos.Bcrit,clos.Tcrit)
    print("delaunay pairs with baselines less than Bcrit (%d m) and Tcrit (%d days): %d"  % (clos.Bcrit,clos.Tcrit,len(delaunayPairs)))
    ## Now lets add all additional pairs less than lengthDayMax from allPairs
    for idx in range(len(allPairs)):
        allPairs[idx] = list(allPairs[idx])
        if tbase[allPairs[idx][1]] - tbase[allPairs[idx][0]] <= clos.lengthDayMax:
            if allPairs[idx] not in delaunayPairs: 
                delaunayPairs.append(allPairs[idx])
    print("delaunay pairs with added pairs less than " + str(clos.lengthDayMax) + " days = " + str(len(delaunayPairs)))
  
    projectDir = os.getcwd()
    projectName = os.path.basename(projectDir) 
  
    if clos.selectMethod == 'all':
        pairs = allPairs
    else:
        pairs = delaunayPairs
  
    dates_obj = [datetime.datetime.strptime(d,"%Y%m%d") for d in dates]
    if clos.dateSpan:
        """ This will filter out the pairs that don't span the date of interest """
        date_span = datetime.datetime.strptime(clos.dateSpan,"%Y-%m-%d")
        pairs = [igram for igram in pairs if dates_obj[igram[0]]<date_span and dates_obj[igram[1]]>date_span ]
        print("# of pairs spanning %s: %d" % (clos.dateSpan,len(pairs)))
  
    intf = open('intf.in','w')
    f = open('run_p2pTOPS','w')
    for igram in sorted(pairs):
        ndx1 = igram[0]
        ndx2 = igram[1]
        baseline = '%05.0f' % round(pbase[ndx1]-pbase[ndx2])
        temporalbaseline = '%04.0f' % round(tbase[ndx2]-tbase[ndx1])
#        print(slcs[ndx1].split("_")[0]+":"+slcs[ndx2].split("_")[0])
        intf.write(slcs[ndx1].split("_")[0]+":"+slcs[ndx2].split("_")[0]+'\n')
        f.write('p2p_S1A_TOPS.csh %s %s config.tops.txt\n' % (os.path.splitext(slcs[ndx1])[0],os.path.splitext(slcs[ndx2])[0])) 
    intf.close()
    f.close()

    f = open('config.tops.txt','w')
    f.write('proc_stage = 4\n')
    f.write('topo_phase = 1\n')
    f.write('topo_shift = 1\n')
    f.write('switch_master = 0\n')
    f.write('filter_wavelength = 200\n')
    f.write('dec_factor = 2\n')
    f.write('threshold_snaphu = 0.1\n')
    f.write('switch_land = 1\n')
    f.write('defomax = 0\n')
    f.write('threshold_geocode = .10')
    f.close()

    plt.figure()
    for e in edges:
        x = [dates_obj[e[0]],dates_obj[e[1]]]
        y = [pbase[e[0]],pbase[e[1]]]
        plt.plot(x,y,'--', c='gray')
    for igram in sorted(pairs):
        ndx1 = igram[0]
        ndx2 = igram[1]
        x = [dates_obj[ndx1], dates_obj[ndx2]]
        y = [pbase[ndx1], pbase[ndx2]]
        plt.plot(x, y, 'b')
    plt.plot(dates_obj, pbase, 'ro')
    if clos.dateSpan:
        plt.axvline(datetime.datetime.strptime(clos.dateSpan,'%Y-%m-%d'),ls='-',color='g')
        plt.annotate('Event',xy=(datetime.datetime.strptime(clos.dateSpan,'%Y-%m-%d'),min(pbase)), xycoords='data', color='g' ) 
    plt.xlabel('Date')
    plt.ylabel('Perpendicular Baseline (m)')
    projectName = os.path.basename(os.getcwd())
    plt.title('SBAS Network - ' + projectName)
    plt.savefig(projectName+'_network.png',transparent=True)
    if clos.np:
        plt.show()
Ejemplo n.º 56
0
Archivo: warp.py Proyecto: ta-oyama/PCV
def triangulate_points(x,y):
    """ 2Dの点のドロネー三角形分割 """
    centers,edges,tri,neighbors = md.delaunay(x,y)
    return tri
Ejemplo n.º 57
0
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp


import matplotlib.delaunay as delaunay
import matplotlib.pyplot as pp
np.random.seed(250819801106)
#generate points
npts=10
xpt=(sp.random.random_sample(npts)-0.5)*4
ypt=(sp.random.random_sample(npts)-0.5)*4
#create triangulation
circumcenters,edges,tri_points,tri_neighbors=delaunay.delaunay(xpt, ypt)
#plot using edges


fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(111, projection='3d')
ax.set_axis_off()
X = np.arange(-2, 2, 0.25)
Y = np.arange(-2, 2, 0.25)
X, Y = np.meshgrid(X, Y)
R = X**2 + Y**2 +1

surf = ax.plot_surface(X, Y, R, rstride=1, cstride=1, cmap=cm.autumn,
        linewidth=0, antialiased=False, alpha=0.5)
ax.set_axis_off()