def main(border,path): from scipy.spatial import Delaunay as delaunay rows,cols=border[0],border[1] array=randommap(rows*10,cols*10) array+=array.min() array/=array.max() array-=array.max() indices = np.vstack(np.unravel_index(np.arange(array.shape[0]*array.shape[1]),array.shape)).T points= np.column_stack((indices,array[indices[:,0],indices[:,1]])) triangles=np.sort(delaunay(indices).simplices) points*=np.array([0.1,0.1,10]) points-=np.array([-rows/2,-cols/2,0]) import pickle with open(path+"/temp/randommap.txt","w") as f: f.write(pickle.dumps([points.tolist(),triangles.tolist()])) print "New random heightmap generated. If you wish to use an existing one, change the corresponding variable heightmap_name in roadmap.conf" return 0
def main(border, path): from scipy.spatial import Delaunay as delaunay rows, cols=border[0], border[1] array=randommap(rows*10, cols*10) array+=array.min() array/=array.max() array-=array.max() indices = np.vstack(np.unravel_index(np.arange(array.shape[0]*array.shape[1]), array.shape)).T points= np.column_stack((indices, array[indices[:, 0], indices[:, 1]])) triangles=np.sort(delaunay(indices).simplices) points*=np.array([0.1, 0.1, 10]) points-=np.array([-rows/2, -cols/2, 0]) import pickle with open(os.path.join(path, "temp", "randommap_"+str(border[0])+"_"+str(border[1])), "w") as f: f.write(pickle.dumps([points.tolist(), triangles.tolist()])) print("New random heightmap generated. If you wish to use an existing one, change the corresponding variable heightmap_name in roadmap.conf") return 0
def return_meshed_point_cloud(self, sourcepoint, points, simplify=0.1): #from sklearn.cluster import KMeans as kmeans from sklearn.cluster import MiniBatchKMeans as mbkmeans from scipy.spatial import Delaunay as delaunay nclusters = int(len(points) * simplify) #km = kmeans(n_clusters=nclusters, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='auto', verbose=0, random_state=None, copy_x=True, n_jobs=1, algorithm='auto').fit(points) km = mbkmeans(n_clusters=nclusters, init='k-means++', n_init=10, max_iter=300, tol=0.001, verbose=0, random_state=None, init_size=3 * nclusters).fit(points) self.clusters = km.cluster_centers_ clusters = [list(item) for item in list(km.cluster_centers_)] if list(sourcepoint) in clusters: print('sourcepoint already in clusters') else: clusters = [list(sourcepoint)] + clusters print('got ' + str(len(clusters)) + ' clusters') tri_volume = delaunay(np.array(clusters), furthest_site=False, incremental=False, qhull_options=None) return (tri_volume.points, tri_volume.simplices)
def get_triangulation(self, v): from scipy.spatial import Delaunay as delaunay flags = 'QJ Qc Pp' tri = delaunay(v, incremental=False, qhull_options=flags) return tri
def get_triangulation(self,v): from scipy.spatial import Delaunay as delaunay flags = 'QJ Qc Pp' tri = delaunay(v,incremental=False,qhull_options=flags) return tri
def __triangulate(self,v): ''' Performs triangulation on vertices in v ((n,3) array) ''' from scipy.spatial import Delaunay as delaunay flags = 'QJ Qc Pp' tri = delaunay(v, incremental=False, qhull_options=flags) return tri
def delauPoints(self): # print 'len self.points', len(self.points[:self.npoints]['pos']) tri = delaunay(self.points['pos']) self.ntets = tri.nsimplex self.tets = zeros(self.ntets, dtype = [('tet', '4int'),('vol', 'float'),('anyInCell', 'bool')]) self.tets['tet'] = tri.simplices #vertex labels self.tets['anyInCell'] = False for itet, tet in enumerate(self.tets[:]['tet']): for ivert in range(4): #find those with at least one vertex in the cell if self.points[tet[ivert]]['inCell']: self.tets[itet]['anyInCell'] = True break if self.tets[itet]['anyInCell']: self.tets[itet]['vol'] = abs(self.volTet([self.points[iv]['pos'] for iv in tet])) self.tets.sort(order='vol');self.tets = reverseStructured(self.tets)
def delauPoints(self): # print 'len self.points', len(self.points[:self.npoints]['pos']) tri = delaunay(self.points['pos']) self.ntets = tri.nsimplex self.tets = zeros(self.ntets, dtype=[('tet', '4int'), ('vol', 'float'), ('anyInCell', 'bool')]) self.tets['tet'] = tri.simplices #vertex labels self.tets['anyInCell'] = False for itet, tet in enumerate(self.tets[:]['tet']): for ivert in range( 4): #find those with at least one vertex in the cell if self.points[tet[ivert]]['inCell']: self.tets[itet]['anyInCell'] = True break if self.tets[itet]['anyInCell']: self.tets[itet]['vol'] = abs( self.volTet([self.points[iv]['pos'] for iv in tet])) self.tets.sort(order='vol') self.tets = reverseStructured(self.tets)
def plot_triangulation(x_obs, y_obs, xlabel = "", ylabel = "", title = "", fileo = ""): # Tracé de la triangulation sur des sites d'observations # x_obs, y_obs : observations # xlabel, ylabel : étiquettes des axes (facultatif) # title : titre (facultatif) # fileo : nom du fichier d'enregistrement de la figure (facultatif) from scipy.spatial import Delaunay as delaunay tri = delaunay(np.hstack((x_obs,y_obs))) plt.figure() plt.triplot(x_obs[:,0], y_obs[:,0], tri.simplices) plt.plot(x_obs, y_obs, 'or', ms=4) plt.xlim(0.95*min(x_obs),max(x_obs)+0.05*min(x_obs)) plt.ylim(0.95*min(y_obs),max(y_obs)+0.05*min(y_obs)) plt.gca().set_aspect('equal', adjustable='box') plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.grid() if not fileo == "": plt.savefig(fileo,bbox_inches='tight')
def setup_heightmap(singleton, path): #TODO: Document '''Sets up the heightmap image from roadmap.conf entry heightmap_name, writes ./Heightmaps/inuse.txt so other functions know which heightmap to load possible inputs: random: generates a new random map with randommap.py insert_name insert_name.png insert_name.txt ''' #TODO make inputs more flexible name=singleton.heightmap_name if name == "random": print("New random heightmap is being created with randommap.py") #Writes correct inuse.txt from procedural_city_generation.additional_stuff import randommap randommap.main(singleton.border, path) with open(path+"/temp/"+singleton.output_name+"_heightmap.txt", 'w') as f: f.write("randommap_"+str(singleton.border[0])+"_"+str(singleton.border[1])) return 0 #Writes correct inuse.txt with open(path+"/temp/"+singleton.output_name+"_heightmap.txt", 'w') as f: f.write(name[0:-4]+"_"+str(singleton.border[0])+"_"+str(singleton.border[1])) #If a txt has already been written for the input in the image, OR if the input was a .txt to begin with, simply load that txt if (name[0:-4]+"_"+str(singleton.border[0])+"_"+str(singleton.border[1]) in os.listdir(path+"/temp/")): return 0 #If the given image has no .txt yet, write the corresponding.txt #Load image and resize from PIL import Image img = Image.open(path+'/inputs/heightmaps/'+name) #TODO: set these numbers to some file where they can be edited easier rsize = img.resize(((singleton.border[1]+20)*10, (singleton.border[0]+20)*10)) array = np.asarray(rsize) from copy import copy array= np.rot90(copy(array), k=3) #If image is a jpeg, all values have to be divided by 255 array=array[::, :, 0]/255. print("You have selected a heightmap which has no .txt file yet, OR the given .txt file has the wrong dimensions. The parameter heightDif will be used to describe the height difference between the lowest and the highest points on the map.") h=singleton.heightDif print("Processing image") #TODO: Find and Fix this Bug array*=abs(h) #Caused weird bugs when -=h was used.. I still can't explain them... array-= h+0.01 #Create all necessary stuff for the heightmap from scipy.spatial import Delaunay as delaunay indices = np.vstack(np.unravel_index(np.arange(array.shape[0]*array.shape[1]), array.shape)).T points= np.column_stack((indices, array[indices[:, 0], indices[:, 1]])) triangles=np.sort(delaunay(indices).simplices) print("Processed image being saved as ", name) #TODO: set thse numbers to some file where they can be edited easier points*=[0.1, 0.1, 1] points-=np.array([ (singleton.border[1]+20)/2, (singleton.border[0]+20)/2, 0]) points=points.tolist() import pickle with open(path+"/temp/"+name[0:-4]+"_"+str(singleton.border[0])+"_"+str(singleton.border[1]), "wb") as f: f.write(pickle.dumps([points, triangles.tolist()])) return 0
def setup_heightmap(singleton, path): #TODO: Document '''Sets up the heightmap image from roadmap.conf entry heightmap_name, writes ./Heightmaps/inuse.txt so other functions know which heightmap to load possible inputs: random: generates a new random map with randommap.py insert_name insert_name.png insert_name.txt ''' #TODO make inputs more flexible name = singleton.heightmap_name if name == "random": print("New random heightmap is being created with randommap.py") #Writes correct inuse.txt from procedural_city_generation.additional_stuff import randommap randommap.main(singleton.border, path) with open(path + "/temp/" + singleton.output_name + "_heightmap.txt", 'w') as f: f.write("randommap_" + str(singleton.border[0]) + "_" + str(singleton.border[1])) return 0 #Writes correct inuse.txt with open(path + "/temp/" + singleton.output_name + "_heightmap.txt", 'w') as f: f.write(name[0:-4] + "_" + str(singleton.border[0]) + "_" + str(singleton.border[1])) #If a txt has already been written for the input in the image, OR if the input was a .txt to begin with, simply load that txt if (name[0:-4] + "_" + str(singleton.border[0]) + "_" + str(singleton.border[1]) in os.listdir(path + "/temp/")): return 0 #If the given image has no .txt yet, write the corresponding.txt #Load image and resize from PIL import Image img = Image.open(path + '/inputs/heightmaps/' + name) #TODO: set these numbers to some file where they can be edited easier rsize = img.resize( ((singleton.border[1] + 20) * 10, (singleton.border[0] + 20) * 10)) array = np.asarray(rsize) from copy import copy array = np.rot90(copy(array), k=3) #If image is a jpeg, all values have to be divided by 255 array = array[::, :, 0] / 255. print( "You have selected a heightmap which has no .txt file yet, OR the given .txt file has the wrong dimensions. The parameter heightDif will be used to describe the height difference between the lowest and the highest points on the map." ) h = singleton.heightDif print("Processing image") #TODO: Find and Fix this Bug array *= abs(h) #Caused weird bugs when -=h was used.. I still can't explain them... array -= h + 0.01 #Create all necessary stuff for the heightmap from scipy.spatial import Delaunay as delaunay indices = np.vstack( np.unravel_index(np.arange(array.shape[0] * array.shape[1]), array.shape)).T points = np.column_stack((indices, array[indices[:, 0], indices[:, 1]])) triangles = np.sort(delaunay(indices).simplices) print("Processed image being saved as ", name) #TODO: set thse numbers to some file where they can be edited easier points *= [0.1, 0.1, 1] points -= np.array([(singleton.border[1] + 20) / 2, (singleton.border[0] + 20) / 2, 0]) points = points.tolist() import pickle with open( path + "/temp/" + name[0:-4] + "_" + str(singleton.border[0]) + "_" + str(singleton.border[1]), "wb") as f: f.write(pickle.dumps([points, triangles.tolist()])) return 0
import numpy as np import sys import matplotlib.pyplot as plt def plot_triangle(a,b,c): x = [a[0],b[0],c[0]] y = [a[1],b[1],c[1]] z = [a[2],b[2],c[2]] verts = [zip(x, y,z)] ax.add_collection3d(Poly3DCollection(verts)) n_samples=10**5 data = np.random.uniform(size=3*n_samples).reshape((-1,3)) data=np.loadtxt('cup.csv',dtype='float',delimiter=',') triangulation = delaunay(data) n_exterior_faces=(triangulation.neighbors==-1).sum(axis=None) print n_exterior_faces exterior_faces=np.zeros(shape=(n_exterior_faces,3),dtype='int') face_counter=0 for i,tetrahedron in enumerate(triangulation.neighbors): for j,face in enumerate(tetrahedron): if face ==-1: exterior_faces[face_counter,:j]=triangulation.simplices[i,:j] exterior_faces[face_counter,j:]=triangulation.simplices[i,j+1:] face_counter+=1 from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection fig = plt.figure()