当前位置: 首页>>代码示例>>Python>>正文


Python Delaunay.add_points方法代码示例

本文整理汇总了Python中scipy.spatial.Delaunay.add_points方法的典型用法代码示例。如果您正苦于以下问题:Python Delaunay.add_points方法的具体用法?Python Delaunay.add_points怎么用?Python Delaunay.add_points使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.spatial.Delaunay的用法示例。


在下文中一共展示了Delaunay.add_points方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: hadrian_min

# 需要导入模块: from scipy.spatial import Delaunay [as 别名]
# 或者: from scipy.spatial.Delaunay import add_points [as 别名]
def hadrian_min(vectorized_f, xbnds, ybnds, xtol, ytol, swarm=8, mx_iters=5,
        inc=False):
    """
    hadrian_min is a stochastic, hill climbing minimization algorithm.  It
    uses a stratified sampling technique (Latin Hypercube) to get good
    coverage of potential new points.  It also uses vectorized function
    evaluations to drive concurrent function evaluations.

    It is named after the Roman Emperor Hadrian, the most famous Latin hill
    mountain climber of ancient times.
    """
    assert xbnds[1] > xbnds[0]
    assert ybnds[1] > ybnds[0]
    assert xtol > 0
    assert ytol > 0
    # simplexes are simplex indexes
    # vertexes are vertex indexes
    # points are spatial coordinates

    bnds = np.vstack((xbnds, ybnds))
    points = latin_sample(np.vstack((xbnds, ybnds)), swarm)
    z = vectorized_f(points)

    # exclude corners from possibilities, but add them to the triangulation
    # this bounds the domain, but ensures they don't get picked
    points = np.append(points, list(product(xbnds, ybnds)), axis=0)
    z = np.append(z, 4*[z.max()])

    tri = Delaunay(points, incremental=inc)
    del points

    for step in range(1, mx_iters+1):
        i, vertexes = get_minimum_neighbors(tri, z)
        disp = tri.points[i] - tri.points[np.unique(vertexes)]
        disp /= np.array([xtol, ytol])
        err = err_mean(disp)

        if err < 1.:
            return tri.points[i], z[i], tri.points, z, 1

        tri_points = tri.points[vertexes]
        bnds = np.cumsum(area(tri_points))
        bnds /= bnds[-1]
        indx = np.searchsorted(bnds, np.random.rand(swarm))

        new_pts = sample_triangle(tri_points[indx])
        new_z = vectorized_f(new_pts)

        if inc:
            tri.add_points(new_pts)
        else:
            # make a new triangulation if I can't append points
            points = np.append(tri.points, new_pts, axis=0)
            tri = Delaunay(points)
        z = np.append(z, new_z)

    return None, None, tri.points, z, step
开发者ID:mrterry,项目名称:hadrian_min,代码行数:59,代码来源:hadrian.py

示例2: __init__

# 需要导入模块: from scipy.spatial import Delaunay [as 别名]
# 或者: from scipy.spatial.Delaunay import add_points [as 别名]
class AdaptiveParametricSpaceMapper:
    def __init__(self, parameters, target, error_norm):
        self.parameters = parameters
        self.target = target
        self.vertices = np.empty((0, len(parameters)), dtype=float)
        self.funvals = []
        self.error_norm = error_norm
        self.create_initial_mesh()
        self.iteration_times = []
    
    def rescale_parameters(self, values):
        rescaled = np.ndarray(values.shape)
        for parameter_id in range(len(self.parameters)):
            pmin = self.parameters[parameter_id][1]
            pmax = self.parameters[parameter_id][2]
            rescaled[parameter_id] = pmin+(pmax-pmin)*values[parameter_id]
        return rescaled
    
    def rescale_parameters_multiple(self, values):
        rescaled = np.ndarray(values.shape)
        for parameter_id in range(len(self.parameters)):
            pmin = self.parameters[parameter_id][1]
            pmax = self.parameters[parameter_id][2]
            rescaled[:,parameter_id] = pmin+(pmax-pmin)*values[:,parameter_id]
        return rescaled
    
    def inverse_rescale_parameters_multiple(self, values):
        rescaled = np.ndarray(values.shape)
        for parameter_id in range(len(self.parameters)):
            pmin = self.parameters[parameter_id][1]
            pmax = self.parameters[parameter_id][2]
            rescaled[:,parameter_id] = (values[:,parameter_id]-pmin)/(pmax-pmin)
        return rescaled
    
    # initial mesh is a n-parallelipiped
    def create_initial_mesh(self):
        self.vertices = np.empty((2**len(self.parameters)+1,len(self.parameters)), dtype=np.float)
        for vertex_id in range(2**len(self.parameters)):
            for parameter_id in range(len(self.parameters)):
                if vertex_id % (2**(parameter_id+1)) >= 2**parameter_id:
                    self.vertices[vertex_id, parameter_id] = 1
                else:
                    self.vertices[vertex_id, parameter_id] = 0
        self.vertices[2**len(self.parameters), :] = np.mean(self.vertices[:2**len(self.parameters),:], axis=0)
        #grids1d = []
        #for parameter_id in range(len(self.parameters)):
        #    grids1d.append(np.linspace(0, 1, 3))
        #gridsnd = np.asarray(np.meshgrid(*(tuple(grids1d))))
        #gridsnd = np.reshape(gridsnd, (len(self.parameters), 3**len(self.parameters)))
        #self.vertices = gridsnd.T
        self.triangulation = Delaunay(np.asarray(self.vertices), incremental=True)
        self.funvals = []
    
    def error_estimator(self):
        nsimplex = self.triangulation.simplices.shape[0]
        simplex_error = np.empty((nsimplex,))
        for simplex_id in range(nsimplex):
            simplex_points = self.triangulation.simplices[simplex_id, :]
            simplex_funvals = []
            for simplex_point in simplex_points:
                simplex_funvals.append(self.funvals[simplex_point])
            simplex_mean_funval = np.mean(simplex_funvals, axis=0)
            simplex_dfs = simplex_mean_funval - simplex_funvals
            print(simplex_dfs)
            simplex_dfs_norms = self.error_norm(simplex_dfs)
            simplex_error[simplex_id] = max(simplex_dfs_norms)
        return simplex_error
        
    def add_vertex(self, vertex):
        self.vertices.resize((self.vertices.shape[0]+1, self.vertices.shape[1]))
        self.vertices[self.vertices.shape[0]-1, :] = vertex
        self.triangulation.add_points(np.reshape(vertex, (1, len(vertex))))
    
    def run(self, max_vertices=sys.maxsize):
        while len(self.vertices)<max_vertices:
            iteration_begin = time.time()
            if (self.vertices.shape[0] != len(self.funvals)):
                self.funvals.append(self.target(self.rescale_parameters(self.vertices[len(self.funvals)-1,:])))
                iteration_end = time.time()
                self.iteration_times.append({'target_evaluation': iteration_end-iteration_begin})
            else:
                dfs = self.error_estimator()
                error_estimator_time = time.time()
                max_simplices_ids = np.argwhere(dfs==np.max(dfs))
                max_simplices_measures = np.empty(max_simplices_ids.shape)
                print((np.argmax(dfs),np.max(dfs)))
                #max_simplices_centroids = np.empty((max_simplices_ids.size, len(self.parameters)))
                for max_simplex_id, simplex_id in enumerate(max_simplices_ids):
                    simplex_vertices = self.triangulation.simplices[simplex_id, :]
                    simplex_vertices_coordinates = self.triangulation.points[simplex_vertices,:]
                    max_simplices_measures[max_simplex_id] = np.linalg.det(simplex_vertices_coordinates[0,1:,:]-simplex_vertices_coordinates[0,0,:])/math.factorial(len(self.parameters))
                max_simplex_vertices = self.triangulation.simplices[max_simplices_ids[np.argmax(max_simplices_measures)],:].ravel()
                simplex_edge_lengths = np.empty((len(max_simplex_vertices), len(max_simplex_vertices)))
                for simplex_vertex1_id, simplex_vertex1 in enumerate(max_simplex_vertices):
                    for simplex_vertex2_id, simplex_vertex2 in enumerate(max_simplex_vertices):
                        simplex_edge_lengths[simplex_vertex1_id, simplex_vertex2_id] = np.linalg.norm(self.triangulation.points[simplex_vertex1,:] - self.triangulation.points[simplex_vertex2,:])
                    print (self.rescale_parameters(self.triangulation.points[simplex_vertex1]))
                    print (np.real((self.funvals[simplex_vertex1][1]-self.funvals[simplex_vertex1][0])))
                simplex_vertex1_id, simplex_vertex2_id = np.unravel_index([np.argmax(simplex_edge_lengths.ravel())], simplex_edge_lengths.shape)
                simplex_vertex1 = max_simplex_vertices[simplex_vertex1_id]
#.........这里部分代码省略.........
开发者ID:iliabesedin,项目名称:QCircuit,代码行数:103,代码来源:AdaptiveParametricSpaceMapper.py

示例3: AdaptiveMesh

# 需要导入模块: from scipy.spatial import Delaunay [as 别名]
# 或者: from scipy.spatial.Delaunay import add_points [as 别名]

#.........这里部分代码省略.........
    
    simplices = self.simplices[bSkinny];                   # shape (nTriangles,3)
    triangles = self.image[simplices];                     # shape (nTriangles,3,2)
    nTriangles= triangles.shape[0];

    # identify the shortest edge of the triangle in image space (not cut)
    lensq = np.sum( np.diff(triangles[:,[0,1,2,0]],axis=1)**2, axis=2); # shape (nTriangles,3)
    min_edge = np.argmin( lensq,axis=1);                                # shape (nTriangles)
 
    # find point as C (opposit to min_edge) and calculate midpoint on CA and CB
    indC = min_edge-1;
    A,B,C,new_domain_points,new_image_points = \
                self.__resample_edges_of_triangle(simplices,indC,x=(0.5,));
    # unique domain_points
    new_domain_points = np.vstack(set(map(tuple, new_domain_points.reshape(2*nTriangles,2))))
    new_image_points = self.mapping(new_domain_points);
    
    if bPlot:   
      from matplotlib.collections import PolyCollection
      fig = self.plot_triangulation();
      fig.suptitle("DEBUG: refine_skinny_triangles()");
      ax1,ax2 = fig.axes;
      params = dict(facecolors='r', edgecolors='none', alpha=0.3);      
      ax1.add_collection(PolyCollection(self.domain[simplices],**params));      
      ax1.plot(new_domain_points[:,0],new_domain_points[:,1],'k.')      
      ax2.add_collection(PolyCollection(self.image[simplices],**params));
      ax2.plot(new_image_points[:,0],new_image_points[:,1],'k.')
        
    
    # update triangulation  
    logging.debug("refining_skinny_triangles(): adding %d points"% (new_domain_points.shape[0]));
    self.image = np.vstack((self.image,new_image_points)); 
    self.domain= np.vstack((self.domain,new_domain_points));   
    self.__tri.add_points(new_domain_points);
    self.simplices = self.__tri.simplices;

    return 2*nTriangles;     


      
  def refine_large_triangles(self,is_large):
    """
    subdivide large triangles in the image mesh
    
    Parameters
    ----------
      is_large : function, mask=is_large(triangles)
        function, which accepts a list of simplices of shape (nTriangles, 3) 
        and returns a flag for each triangle indicating if it should be subdivided
    
    Returns
    --------
      number of points added to the triangulation                 
    
    Note
    ----
      Additional points are added at the center of gravity of large triangles
      and the Delaunay triangulation is recalculated. Edge flips can occur.
      This procedure is suboptimal, as it produces skinny triangles.
    """
    # check if mesh is still a Delaunay mesh
    if self.__tri is None:
      raise RuntimeError('Mesh is no longer a Delaunay mesh. Subdivision not implemented for this case.');
    
    ind = is_large(self.simplices);
    if np.sum(ind)==0: return; # nothing to do
开发者ID:rhambach,项目名称:tados,代码行数:70,代码来源:adaptive_mesh.py

示例4: Delaunay

# 需要导入模块: from scipy.spatial import Delaunay [as 别名]
# 或者: from scipy.spatial.Delaunay import add_points [as 别名]

#.........这里部分代码省略.........
        explore_priority : float, optional
            The priority of exploration against exploitation
        """
        Sampler.__init__(self, lower, upper)
        self.triangulation = None  # Delaunay model
        self.simplex_cache = {}  # Pre-computed values of simplices
        self.explore_priority = explore_priority

    def update(self, uid, y_true):
        """
        Update a job with its observed value.

        Parameters
        ----------
        uid : str
            A hexadecimal ID that identifies the job to be updated
        y_true : float
            The observed value corresponding to the job identified by 'uid'

        Returns
        -------
        int
            Index location in the data lists 'Delaunay.X' and
            'Delaunay.y' corresponding to the job being updated
        """
        return self._update(uid, y_true)

    def pick(self):
        """
        Pick the next feature location for the next observation to be taken.

        This uses the recursive Delaunay subdivision algorithm.

        Returns
        -------
        numpy.ndarray
            Location in the parameter space for the next observation to be
            taken
        str
            A random hexadecimal ID to identify the corresponding job
        """
        n = len(self.X)

        # -- note that we are assuming the points in X are not reordered by
        # the scipy Delaunay implementation

        n_corners = 2 ** self.dims
        if n < n_corners + 1:

            # Bootstrap with a regular sampling strategy to get it started
            xq = grid_sample(self.lower, self.upper, n)
            yq_exp = [0.]
        else:

            X = self.X()  # calling returns the value as an array
            y = self.y()
            virtual = self.virtual_flag()

            # Otherwise, recursive subdivide the edges with the Delaunay model
            if not self.triangulation:
                self.triangulation = ScipyDelaunay(X, incremental=True)

            # Weight by hyper-volume
            simplices = [tuple(s) for s in self.triangulation.vertices]
            cache = self.simplex_cache

            def get_value(s):

                # Computes the sample value as:
                #   hyper-volume of simplex * variance of values in simplex
                ind = list(s)
                value = (np.var(y[ind]) + self.explore_priority) * \
                    np.linalg.det((X[ind] - X[ind[0]])[1:])
                if not np.max(virtual[ind]):
                    cache[s] = value
                return value

            # Mostly the simplices won't change from call to call - cache!
            sample_value = [cache[s] if s in cache else get_value(s)
                            for s in simplices]

            # alternatively, a nicely vectorised computation might work here
            # profile and check what the bottleneck is

            # Extract the points in the highest value simplex
            simplex_indices = list(simplices[np.argmax(sample_value)])
            simplex = X[simplex_indices]
            simplex_v = y[simplex_indices]

            # Weight the position in this simplex based on value deviation
            eps = 1e-3
            weight = eps + np.abs(simplex_v - np.mean(simplex_v))
            weight /= np.sum(weight)
            xq = np.sum(weight * simplex, axis=0)  # dot
            yq_exp = np.sum(weight * simplex_v, axis=0)

            self.triangulation.add_points(xq[np.newaxis, :])  # incremental

        uid = Sampler._assign(self, xq, yq_exp)
        return xq, uid
开发者ID:NICTA,项目名称:dora,代码行数:104,代码来源:delaunay_sampler.py

示例5: triangulatePoly

# 需要导入模块: from scipy.spatial import Delaunay [as 别名]
# 或者: from scipy.spatial.Delaunay import add_points [as 别名]
def triangulatePoly(coords,addPoints=False,iterations=2,debug=False):
	
	"""Triangulates a polygon with given coords using a Delaunay triangulation.
	
	Uses http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html#scipy.spatial.Delaunay to 
	calculate triangulation, then filters the triangles actually lying within the polygon.
	
	Args:
		coords (list): List of (x,y)-coordinates of corners.
	
	Keyword Args:
		addPoints (bool): Allow incremental addition of points.
		iterations (int): Number of iterations of additional point adding.
		debug (boo): Print debugging messages.
		
	Returns:
		tuple: Tuple containing:
		
			* triFinal (list): List of found triangles.
			* coordsTri (list): List of vertex coordinates.
	"""
	
	#Bookkeeping list
	triFinal=[]
		
	#Triangulate
	tri=Delaunay(coords,incremental=addPoints)
	
	#Backup original coordinates
	coordsOrg=list(coords)
	
	if debug:
		print "Found ", len(tri.simplices.copy()), "triangles in initial call."

	#Incrementally refine triangulation
	if addPoints:
		for i in range(iterations):
			
			mids=[]
			for j in range(len(tri.simplices)):
				mid=getCenterOfMass(coords[tri.simplices.copy()[j]])
				mids.append(mid)
				
			coords=np.asarray(list(coords)+mids)
			tri.add_points(mids,restart=True)
				
		if debug:
			print "Found ", len(tri.simplices.copy()), "triangles after iterations."
		
			
	#Remember assigment of points by traingulation function
	coordsTri=tri.points
	
	midsIn=[]
	midsOut=[]
	triOutIdx=[]
	triInIdx=[]
	
	for i in range(len(tri.simplices)):
	
		# Get COM of triangle
		mid=getCenterOfMass(coordsTri[tri.simplices.copy()[i]])
		
		#Check if triangle is inside original polygon
		if checkInsidePolyVec(mid[0],mid[1],coordsOrg):
			triFinal.append(tri.simplices.copy()[i])
			midsIn.append(mid)
			triInIdx.append(i)		
		else:
			triOutIdx.append(i)
			midsOut.append(mid)
	
	if debug:
		print "Removed ", len(tri.simplices.copy())-len(triFinal), "triangles through COM criteria."	
		print "Returning ", len(triFinal), "triangles."	
		
		
	return triFinal,coordsTri
开发者ID:alexblaessle,项目名称:PyFRAP,代码行数:80,代码来源:pyfrp_idx_module.py


注:本文中的scipy.spatial.Delaunay.add_points方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。