├── hks20.png ├── hks5.png ├── hks200.png ├── Sampled1000.png ├── sampler.py ├── README.md ├── trimesh.py ├── hks.py └── LICENSE /hks20.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctralie/pyhks/HEAD/hks20.png -------------------------------------------------------------------------------- /hks5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctralie/pyhks/HEAD/hks5.png -------------------------------------------------------------------------------- /hks200.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctralie/pyhks/HEAD/hks200.png -------------------------------------------------------------------------------- /Sampled1000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ctralie/pyhks/HEAD/Sampled1000.png -------------------------------------------------------------------------------- /sampler.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from trimesh import load_off, sample_by_area 3 | 4 | if __name__ == '__main__': 5 | parser = argparse.ArgumentParser() 6 | parser.add_argument("--input", type=str, required=True, help="Path to OFF file for triangle mesh on which to compute the HKS") 7 | parser.add_argument("--output", type=str, required=True, help="Path to text file which will holds the sampled points and their normals") 8 | parser.add_argument("--npoints", type=float, required=True, help="Number of points to sample") 9 | parser.add_argument("--do_plot", type=int, default=0, help="Whether to plot the result with matplotlib") 10 | opt = parser.parse_args() 11 | (VPos, VColors, ITris) = load_off(opt.input) 12 | npoints = int(opt.npoints) 13 | Ps, Ns = sample_by_area(VPos, ITris, npoints, colPoints=False) 14 | if opt.do_plot == 1: 15 | import numpy as np 16 | import matplotlib.pyplot as plt 17 | from mpl_toolkits.mplot3d import Axes3D 18 | fig = plt.figure() 19 | ax = fig.add_subplot(111, projection='3d') 20 | ax.scatter(Ps[:, 0], Ps[:, 1], Ps[:, 2]) 21 | plt.show() 22 | X = np.concatenate((Ps, Ns), axis=1) 23 | fout = open(opt.output, "w") 24 | for i in range(X.shape[0]): 25 | for j in range(X.shape[1]): 26 | fout.write("{}".format(X[i, j])) 27 | if j < X.shape[1]-1: 28 | fout.write(",") 29 | fout.write("\n") 30 | fout.close() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pyhks 2 | 3 | This is a simple dependency free Python library for the Heat Kernel Signature on triangle meshes. The only dependencies are the numpy/scipy stack. If you want to view the results of the computation, you should also download [meshlab]. 4 | 5 | ## Running HKS 6 | To see all options, run the script as follows 7 | ~~~~~ bash 8 | python hks.py --help 9 | ~~~~~ 10 | 11 | As an example, let's examine the HKS on the "homer" mesh in this repository, at different scales. In each example, we output to a file which can be opened in [meshlab], which is the homer mesh colored in grayscale with the values of the HKS 12 | 13 | 14 | 15 | 16 | 21 | 26 | 31 | 32 | 33 | 34 | 37 | 40 | 43 | 44 | 45 |
17 | 18 | python hks.py --input homer.off --t 5 --output hks5.off 19 | 20 | 22 | 23 | python hks.py --input homer.off --t 20 --output hks20.off 24 | 25 | 27 | 28 | python hks.py --input homer.off --t 200 --output hks200.off 29 | 30 |
35 | 36 | 38 | 39 | 41 | 42 |
46 | 47 | Notice how at smaller time scales, finer, high frequency curvature detail is present. However, if the time scale is too small, artifacts are present from using a limited number of eigenvectors. 48 | 49 | 50 | [meshlab]: 51 | 52 | 53 | ## Running Point Sampler 54 | 55 | There's a function that comes bundled with this software that samples a triangle mesh uniformly by area. This may be of independent interest to some people. There is a script that can launch this called "PointSampler.py". To see all options, run the script as follows 56 | ~~~~~ bash 57 | python PointSampler.py --help 58 | ~~~~~ 59 | 60 | For example, the code 61 | ~~~~~ bash 62 | python sampler.py --input homer.off --output out.csv --npoints 1000 --do_plot 1 63 | ~~~~~ 64 | 65 | will evenly sample 1000 points on homer and show a plot, before saving to a csv file called "out.csv" 66 | 67 | -------------------------------------------------------------------------------- /trimesh.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import sparse 3 | 4 | 5 | def load_off(filename): 6 | """ 7 | Load in an OFF file, assuming it's a triangle mesh 8 | Parameters 9 | ---------- 10 | filename: string 11 | Path to file 12 | Returns 13 | ------- 14 | VPos : ndarray (N, 3) 15 | Array of points in 3D 16 | VColors : ndarray(N, 3) 17 | Array of RGB colors 18 | ITris : ndarray (M, 3) 19 | Array of triangles connecting points, pointing to vertex indices 20 | """ 21 | fin = open(filename, 'r') 22 | nVertices = 0 23 | nFaces = 0 24 | lineCount = 0 25 | face = 0 26 | vertex = 0 27 | divideColor = False 28 | VPos = np.zeros((0, 3)) 29 | VColors = np.zeros((0, 3)) 30 | ITris = np.zeros((0, 3)) 31 | for line in fin: 32 | lineCount = lineCount+1 33 | fields = line.split() #Splits whitespace by default 34 | if len(fields) == 0: #Blank line 35 | continue 36 | if fields[0][0] in ['#', '\0', ' '] or len(fields[0]) == 0: 37 | continue 38 | #Check section 39 | if nVertices == 0: 40 | if fields[0] == "OFF" or fields[0] == "COFF": 41 | if len(fields) > 2: 42 | fields[1:4] = [int(field) for field in fields] 43 | [nVertices, nFaces, nEdges] = fields[1:4] 44 | #Pre-allocate vertex arrays 45 | VPos = np.zeros((nVertices, 3)) 46 | VColors = np.zeros((nVertices, 3)) 47 | ITris = np.zeros((nFaces, 3)) 48 | if fields[0] == "COFF": 49 | divideColor = True 50 | else: 51 | fields[0:3] = [int(field) for field in fields] 52 | [nVertices, nFaces, nEdges] = fields[0:3] 53 | VPos = np.zeros((nVertices, 3)) 54 | VColors = np.zeros((nVertices, 3)) 55 | ITris = np.zeros((nFaces, 3)) 56 | elif vertex < nVertices: 57 | fields = [float(i) for i in fields] 58 | P = [fields[0],fields[1], fields[2]] 59 | color = np.array([0.5, 0.5, 0.5]) #Gray by default 60 | if len(fields) >= 6: 61 | #There is color information 62 | if divideColor: 63 | color = [float(c)/255.0 for c in fields[3:6]] 64 | else: 65 | color = [float(c) for c in fields[3:6]] 66 | VPos[vertex, :] = P 67 | VColors[vertex, :] = color 68 | vertex = vertex+1 69 | elif face < nFaces: 70 | #Assume the vertices are specified in CCW order 71 | fields = [int(i) for i in fields] 72 | ITris[face, :] = fields[1:fields[0]+1] 73 | face = face+1 74 | fin.close() 75 | VPos = np.array(VPos, np.float64) 76 | VColors = np.array(VColors, np.float64) 77 | ITris = np.array(ITris, np.int32) 78 | return (VPos, VColors, ITris) 79 | 80 | def save_off(filename, VPos, VColors, ITris): 81 | """ 82 | Save a .off file 83 | Parameters 84 | ---------- 85 | filename: string 86 | Path to which to write .off file 87 | VPos : ndarray (N, 3) 88 | Array of points in 3D 89 | VColors : ndarray(N, 3) 90 | Array of RGB colors 91 | ITris : ndarray (M, 3) 92 | Array of triangles connecting points, pointing to vertex indices 93 | """ 94 | nV = VPos.shape[0] 95 | nF = ITris.shape[0] 96 | fout = open(filename, "w") 97 | if VColors.size == 0: 98 | fout.write("OFF\n%i %i %i\n"%(nV, nF, 0)) 99 | else: 100 | fout.write("COFF\n%i %i %i\n"%(nV, nF, 0)) 101 | for i in range(nV): 102 | fout.write("%g %g %g"%tuple(VPos[i, :])) 103 | if VColors.size > 0: 104 | fout.write(" %g %g %g"%tuple(VColors[i, :])) 105 | fout.write("\n") 106 | for i in range(nF): 107 | fout.write("3 %i %i %i\n"%tuple(ITris[i, :])) 108 | fout.close() 109 | 110 | 111 | def sample_by_area(VPos, ITris, npoints, colPoints = False): 112 | """ 113 | Randomly sample points by area on a triangle mesh. This function is 114 | extremely fast by using broadcasting/numpy operations in lieu of loops 115 | 116 | Parameters 117 | ---------- 118 | VPos : ndarray (N, 3) 119 | Array of points in 3D 120 | ITris : ndarray (M, 3) 121 | Array of triangles connecting points, pointing to vertex indices 122 | npoints : int 123 | Number of points to sample 124 | colPoints : boolean (default True) 125 | Whether the points are along the columns or the rows 126 | 127 | Returns 128 | ------- 129 | (Ps : NDArray (npoints, 3) array of sampled points, 130 | Ns : Ndarray (npoints, 3) of normals at those points ) 131 | """ 132 | ###Step 1: Compute cross product of all face triangles and use to compute 133 | #areas and normals (very similar to code used to compute vertex normals) 134 | 135 | #Vectors spanning two triangle edges 136 | P0 = VPos[ITris[:, 0], :] 137 | P1 = VPos[ITris[:, 1], :] 138 | P2 = VPos[ITris[:, 2], :] 139 | V1 = P1 - P0 140 | V2 = P2 - P0 141 | FNormals = np.cross(V1, V2) 142 | FAreas = np.sqrt(np.sum(FNormals**2, 1)).flatten() 143 | 144 | #Get rid of zero area faces and update points 145 | ITris = ITris[FAreas > 0, :] 146 | FNormals = FNormals[FAreas > 0, :] 147 | FAreas = FAreas[FAreas > 0] 148 | P0 = VPos[ITris[:, 0], :] 149 | P1 = VPos[ITris[:, 1], :] 150 | P2 = VPos[ITris[:, 2], :] 151 | 152 | #Compute normals 153 | NTris = ITris.shape[0] 154 | FNormals = FNormals/FAreas[:, None] 155 | FAreas = 0.5*FAreas 156 | FNormals = FNormals 157 | VNormals = np.zeros_like(VPos) 158 | VAreas = np.zeros(VPos.shape[0]) 159 | for k in range(3): 160 | VNormals[ITris[:, k], :] += FAreas[:, None]*FNormals 161 | VAreas[ITris[:, k]] += FAreas 162 | #Normalize normals 163 | VAreas[VAreas == 0] = 1 164 | VNormals = VNormals / VAreas[:, None] 165 | 166 | ###Step 2: Randomly sample points based on areas 167 | FAreas = FAreas/np.sum(FAreas) 168 | AreasC = np.cumsum(FAreas) 169 | samples = np.sort(np.random.rand(npoints)) 170 | #Figure out how many samples there are for each face 171 | FSamples = np.zeros(NTris, dtype=np.int32) 172 | fidx = 0 173 | for s in samples: 174 | while s > AreasC[fidx]: 175 | fidx += 1 176 | FSamples[fidx] += 1 177 | #Now initialize an array that stores the triangle sample indices 178 | tidx = np.zeros(npoints, dtype=np.int64) 179 | idx = 0 180 | for i in range(len(FSamples)): 181 | tidx[idx:idx+FSamples[i]] = i 182 | idx += FSamples[i] 183 | N = np.zeros((npoints, 3)) #Allocate space for normals 184 | idx = 0 185 | 186 | #Vector used to determine if points need to be flipped across parallelogram 187 | V3 = P2 - P1 188 | V3 = V3/np.sqrt(np.sum(V3**2, 1))[:, None] #Normalize 189 | 190 | #Randomly sample points on each face 191 | #Generate random points uniformly in parallelogram 192 | u = np.random.rand(npoints, 1) 193 | v = np.random.rand(npoints, 1) 194 | Ps = u*V1[tidx, :] + P0[tidx, :] 195 | Ps += v*V2[tidx, :] 196 | #Flip over points which are on the other side of the triangle 197 | dP = Ps - P1[tidx, :] 198 | proj = np.sum(dP*V3[tidx, :], 1) 199 | dPPar = V3[tidx, :]*proj[:, None] #Parallel project onto edge 200 | dPPerp = dP - dPPar 201 | Qs = Ps - dPPerp 202 | dP0QSqr = np.sum((Qs - P0[tidx, :])**2, 1) 203 | dP0PSqr = np.sum((Ps - P0[tidx, :])**2, 1) 204 | idxreg = np.arange(npoints, dtype=np.int64) 205 | idxflip = idxreg[dP0QSqr < dP0PSqr] 206 | u[idxflip, :] = 1 - u[idxflip, :] 207 | v[idxflip, :] = 1 - v[idxflip, :] 208 | Ps[idxflip, :] = P0[tidx[idxflip], :] + u[idxflip, :]*V1[tidx[idxflip], :] + v[idxflip, :]*V2[tidx[idxflip], :] 209 | 210 | #Step 3: Compute normals of sampled points by barycentric interpolation 211 | Ns = u*VNormals[ITris[tidx, 1], :] 212 | Ns += v*VNormals[ITris[tidx, 2], :] 213 | Ns += (1-u-v)*VNormals[ITris[tidx, 0], :] 214 | 215 | if colPoints: 216 | return (Ps.T, Ns.T) 217 | return (Ps, Ns) 218 | 219 | 220 | 221 | def get_edges(VPos, ITris): 222 | """ 223 | Given a list of triangles, return an array representing the edges 224 | Parameters 225 | ---------- 226 | VPos : ndarray (N, 3) 227 | Array of points in 3D 228 | ITris : ndarray (M, 3) 229 | Array of triangles connecting points, pointing to vertex indices 230 | Returns: I, J 231 | Two parallel 1D arrays with indices of edges 232 | """ 233 | N = VPos.shape[0] 234 | M = ITris.shape[0] 235 | I = np.zeros(M*6) 236 | J = np.zeros(M*6) 237 | V = np.ones(M*6) 238 | for shift in range(3): 239 | #For all 3 shifts of the roles of triangle vertices 240 | #to compute different cotangent weights 241 | [i, j, k] = [shift, (shift+1)%3, (shift+2)%3] 242 | I[shift*M*2:shift*M*2+M] = ITris[:, i] 243 | J[shift*M*2:shift*M*2+M] = ITris[:, j] 244 | I[shift*M*2+M:shift*M*2+2*M] = ITris[:, j] 245 | J[shift*M*2+M:shift*M*2+2*M] = ITris[:, i] 246 | L = sparse.coo_matrix((V, (I, J)), shape=(N, N)).tocsr() 247 | return L.nonzero() 248 | -------------------------------------------------------------------------------- /hks.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy import sparse 3 | from scipy.sparse.linalg import lsqr, cg, eigsh 4 | import matplotlib.pyplot as plt 5 | import argparse 6 | from trimesh import load_off, save_off 7 | 8 | def get_cotan_laplacian(VPos, ITris, anchorsIdx = [], anchorWeights = 1): 9 | """ 10 | Quickly compute sparse Laplacian matrix with cotangent weights and Voronoi areas 11 | by doing many operations in parallel using NumPy 12 | 13 | Parameters 14 | ---------- 15 | VPos : ndarray (N, 3) 16 | Array of vertex positions 17 | ITris : ndarray (M, 3) 18 | Array of triangle indices 19 | anchorsIdx : list 20 | A list of vertex indices corresponding to the anchor vertices 21 | (for use in Laplacian mesh editing; by default none) 22 | anchorWeights : float 23 | 24 | 25 | Returns 26 | ------- 27 | L : scipy.sparse (NVertices+anchors, NVertices+anchors) 28 | A sparse Laplacian matrix with cotangent weights 29 | """ 30 | N = VPos.shape[0] 31 | M = ITris.shape[0] 32 | #Allocate space for the sparse array storage, with 2 entries for every 33 | #edge for eves ry triangle (6 entries per triangle); one entry for directed 34 | #edge ij and ji. Note that this means that edges with two incident triangles 35 | #will have two entries per directed edge, but sparse array will sum them 36 | I = np.zeros(M*6) 37 | J = np.zeros(M*6) 38 | V = np.zeros(M*6) 39 | 40 | #Keep track of areas of incident triangles and the number of incident triangles 41 | IA = np.zeros(M*3) 42 | VA = np.zeros(M*3) #Incident areas 43 | VC = 1.0*np.ones(M*3) #Number of incident triangles 44 | 45 | #Step 1: Compute cotangent weights 46 | for shift in range(3): 47 | #For all 3 shifts of the roles of triangle vertices 48 | #to compute different cotangent weights 49 | [i, j, k] = [shift, (shift+1)%3, (shift+2)%3] 50 | dV1 = VPos[ITris[:, i], :] - VPos[ITris[:, k], :] 51 | dV2 = VPos[ITris[:, j], :] - VPos[ITris[:, k], :] 52 | Normal = np.cross(dV1, dV2) 53 | #Cotangent is dot product / mag cross product 54 | NMag = np.sqrt(np.sum(Normal**2, 1)) 55 | cotAlpha = np.sum(dV1*dV2, 1)/NMag 56 | I[shift*M*2:shift*M*2+M] = ITris[:, i] 57 | J[shift*M*2:shift*M*2+M] = ITris[:, j] 58 | V[shift*M*2:shift*M*2+M] = cotAlpha 59 | I[shift*M*2+M:shift*M*2+2*M] = ITris[:, j] 60 | J[shift*M*2+M:shift*M*2+2*M] = ITris[:, i] 61 | V[shift*M*2+M:shift*M*2+2*M] = cotAlpha 62 | if shift == 0: 63 | #Compute contribution of this triangle to each of the vertices 64 | for k in range(3): 65 | IA[k*M:(k+1)*M] = ITris[:, k] 66 | VA[k*M:(k+1)*M] = 0.5*NMag 67 | 68 | #Step 2: Create laplacian matrix 69 | L = sparse.coo_matrix((V, (I, J)), shape=(N, N)).tocsr() 70 | #Create the diagonal by summing the rows and subtracting off the nondiagonal entries 71 | L = sparse.dia_matrix((L.sum(1).flatten(), 0), L.shape) - L 72 | #Scale each row by the incident areas TODO: Fix this 73 | """ 74 | Areas = sparse.coo_matrix((VA, (IA, IA)), shape=(N, N)).tocsr() 75 | Areas = Areas.todia().data.flatten() 76 | Areas[Areas == 0] = 1 77 | Counts = sparse.coo_matrix((VC, (IA, IA)), shape=(N, N)).tocsr() 78 | Counts = Counts.todia().data.flatten() 79 | RowScale = sparse.dia_matrix((3*Counts/Areas, 0), L.shape) 80 | L = L.T.dot(RowScale).T 81 | """ 82 | 83 | #Step 3: Add anchors 84 | L = L.tocoo() 85 | I = L.row.tolist() 86 | J = L.col.tolist() 87 | V = L.data.tolist() 88 | I = I + list(range(N, N+len(anchorsIdx))) 89 | J = J + anchorsIdx 90 | V = V + [anchorWeights]*len(anchorsIdx) 91 | L = sparse.coo_matrix((V, (I, J)), shape=(N+len(anchorsIdx), N)).tocsr() 92 | return L 93 | 94 | def get_umbrella_laplacian(VPos, ITris, anchorsIdx = [], anchorWeights = 1): 95 | """ 96 | Quickly compute sparse Laplacian matrix with "umbrella weights" (unweighted) 97 | by doing many operations in parallel using NumPy 98 | 99 | Parameters 100 | ---------- 101 | VPos : ndarray (N, 3) 102 | Array of vertex positions 103 | ITris : ndarray (M, 3) 104 | Array of triangle indices 105 | anchorsIdx : list 106 | A list of vertex indices corresponding to the anchor vertices 107 | (for use in Laplacian mesh editing; by default none) 108 | anchorWeights : float 109 | 110 | 111 | Returns 112 | ------- 113 | L : scipy.sparse (NVertices+anchors, NVertices+anchors) 114 | A sparse Laplacian matrix with umbrella weights 115 | """ 116 | N = VPos.shape[0] 117 | M = ITris.shape[0] 118 | I = np.zeros(M*6) 119 | J = np.zeros(M*6) 120 | V = np.ones(M*6) 121 | 122 | #Step 1: Set up umbrella entries 123 | for shift in range(3): 124 | #For all 3 shifts of the roles of triangle vertices 125 | #to compute different cotangent weights 126 | [i, j, k] = [shift, (shift+1)%3, (shift+2)%3] 127 | I[shift*M*2:shift*M*2+M] = ITris[:, i] 128 | J[shift*M*2:shift*M*2+M] = ITris[:, j] 129 | I[shift*M*2+M:shift*M*2+2*M] = ITris[:, j] 130 | J[shift*M*2+M:shift*M*2+2*M] = ITris[:, i] 131 | 132 | #Step 2: Create laplacian matrix 133 | L = sparse.coo_matrix((V, (I, J)), shape=(N, N)).tocsr() 134 | L[L > 0] = 1 135 | #Create the diagonal by summing the rows and subtracting off the nondiagonal entries 136 | L = sparse.dia_matrix((L.sum(1).flatten(), 0), L.shape) - L 137 | 138 | #Step 3: Add anchors 139 | L = L.tocoo() 140 | I = L.row.tolist() 141 | J = L.col.tolist() 142 | V = L.data.tolist() 143 | I = I + list(range(N, N+len(anchorsIdx))) 144 | J = J + anchorsIdx 145 | V = V + [anchorWeights]*len(anchorsIdx) 146 | L = sparse.coo_matrix((V, (I, J)), shape=(N+len(anchorsIdx), N)).tocsr() 147 | return L 148 | 149 | 150 | 151 | 152 | def get_laplacian_spectrum(VPos, ITris, K): 153 | """ 154 | Given a mesh, to compute first K eigenvectors of its Laplacian 155 | and the corresponding eigenvalues 156 | Parameters 157 | ---------- 158 | VPos : ndarray (N, 3) 159 | Array of points in 3D 160 | ITris : ndarray (M, 3) 161 | Array of triangles connecting points, pointing to vertex indices 162 | K : int 163 | Number of eigenvectors to compute 164 | Returns 165 | ------- 166 | (eigvalues, eigvectors): a tuple of the eigenvalues and eigenvectors 167 | """ 168 | L = get_cotan_laplacian(VPos, ITris) 169 | (eigvalues, eigvectors) = eigsh(L, K, which='LM', sigma = 0) 170 | return (eigvalues, eigvectors) 171 | 172 | 173 | def get_heat(eigvalues, eigvectors, t, initialVertices, heatValue = 100.0): 174 | """ 175 | Simulate heat flow by projecting initial conditions 176 | onto the eigenvectors of the Laplacian matrix, and then sum up the heat 177 | flow of each eigenvector after it's decayed after an amount of time t 178 | Parameters 179 | ---------- 180 | eigvalues : ndarray (K) 181 | Eigenvalues of the laplacian 182 | eigvectors : ndarray (N, K) 183 | An NxK matrix of corresponding laplacian eigenvectors 184 | Number of eigenvectors to compute 185 | t : float 186 | The time to simulate heat flow 187 | initialVertices : ndarray (L) 188 | indices of the verticies that have an initial amount of heat 189 | heatValue : float 190 | The value to put at each of the initial vertices at the beginning of time 191 | 192 | Returns 193 | ------- 194 | heat : ndarray (N) holding heat values at each vertex on the mesh 195 | """ 196 | N = eigvectors.shape[0] 197 | I = np.zeros(N) 198 | I[initialVertices] = heatValue 199 | coeffs = I[None, :].dot(eigvectors) 200 | coeffs = coeffs.flatten() 201 | coeffs = coeffs*np.exp(-eigvalues*t) 202 | heat = eigvectors.dot(coeffs[:, None]) 203 | return heat 204 | 205 | def get_hks(VPos, ITris, K, ts): 206 | """ 207 | Given a triangle mesh, approximate its curvature at some measurement scale 208 | by recording the amount of heat that remains at each vertex after a unit impulse 209 | of heat is applied. This is called the "Heat Kernel Signature" (HKS) 210 | 211 | Parameters 212 | ---------- 213 | VPos : ndarray (N, 3) 214 | Array of points in 3D 215 | ITris : ndarray (M, 3) 216 | Array of triangles connecting points, pointing to vertex indices 217 | K : int 218 | Number of eigenvalues/eigenvectors to use 219 | ts : ndarray (T) 220 | The time scales at which to compute the HKS 221 | 222 | Returns 223 | ------- 224 | hks : ndarray (N, T) 225 | A array of the heat kernel signatures at each of N points 226 | at T time intervals 227 | """ 228 | L = get_cotan_laplacian(VPos, ITris) 229 | (eigvalues, eigvectors) = eigsh(L, K, which='LM', sigma = 0) 230 | res = (eigvectors[:, :, None]**2)*np.exp(-eigvalues[None, :, None]*ts.flatten()[None, None, :]) 231 | return np.sum(res, 1) 232 | 233 | 234 | def saveHKSColors(filename, VPos, hks, ITris, cmap = 'gray'): 235 | """ 236 | Save the mesh as a .coff file using a divergent colormap, where 237 | negative curvature is one one side and positive curvature is on the other 238 | """ 239 | c = plt.get_cmap(cmap) 240 | x = (hks - np.min(hks)) 241 | x /= np.max(x) 242 | np.array(np.round(x*255.0), dtype=np.int32) 243 | C = c(x) 244 | C = C[:, 0:3] 245 | save_off(filename, VPos, C, ITris) 246 | 247 | if __name__ == '__main__': 248 | parser = argparse.ArgumentParser() 249 | parser.add_argument("--input", type=str, required=True, help="Path to OFF file for triangle mesh on which to compute the HKS") 250 | parser.add_argument("--output", type=str, required=True, help="Path to OFF file which holds a colored mesh showing the HKS") 251 | parser.add_argument("--t", type=float, required=True, help="Time parameter for the HKS") 252 | parser.add_argument("--neigvecs", type=int, required=False, default = 200, help="Number of eigenvectors to use") 253 | 254 | opt = parser.parse_args() 255 | (VPos, VColors, ITris) = load_off(opt.input) 256 | neigvecs = min(VPos.shape[0], opt.neigvecs) 257 | hks = get_hks(VPos, ITris, neigvecs, np.array([opt.t])) 258 | saveHKSColors(opt.output, VPos, hks[:, 0], ITris) 259 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------