Coverage for trimesh/graph.py: 90%

296 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-22 02:08 +0000

1""" 

2graph.py 

3------------- 

4 

5Deal with graph operations. Primarily deal with graphs in (n, 2) 

6edge list form, and abstract the backend graph library being used. 

7 

8Currently uses networkx or scipy.sparse.csgraph backend. 

9""" 

10 

11import collections 

12 

13import numpy as np 

14 

15from . import exceptions, grouping, util 

16from .constants import log, tol 

17from .geometry import faces_to_edges 

18from .typed import ( 

19 ArrayLike, 

20 GraphEngineType, 

21 Hashable, 

22 Integer, 

23 NDArray, 

24 Number, 

25 Sequence, 

26 int64, 

27) 

28 

29try: 

30 from scipy.sparse import coo_matrix, csgraph 

31 from scipy.spatial import cKDTree 

32except BaseException as E: 

33 # re-raise exception when used 

34 cKDTree = exceptions.ExceptionWrapper(E) 

35 csgraph = exceptions.ExceptionWrapper(E) 

36 coo_matrix = exceptions.ExceptionWrapper(E) 

37 

38try: 

39 import networkx as nx 

40except BaseException as E: 

41 # create a dummy module which will raise the ImportError 

42 # or other exception only when someone tries to use networkx 

43 nx = exceptions.ExceptionWrapper(E) 

44 

45 

46def face_adjacency(faces=None, mesh=None, return_edges=False): 

47 """ 

48 Returns an (n, 2) list of face indices. 

49 Each pair of faces in the list shares an edge, making them adjacent. 

50 

51 

52 Parameters 

53 ----------- 

54 faces : (n, 3) int, or None 

55 Vertex indices representing triangles 

56 mesh : Trimesh object 

57 If passed will used cached edges 

58 instead of generating from faces 

59 return_edges : bool 

60 Return the edges shared by adjacent faces 

61 

62 Returns 

63 ---------- 

64 adjacency : (m, 2) int 

65 Indexes of faces that are adjacent 

66 edges: (m, 2) int 

67 Only returned if return_edges is True 

68 Indexes of vertices which make up the 

69 edges shared by the adjacent faces 

70 

71 Examples 

72 ---------- 

73 This is useful for lots of things such as finding 

74 face- connected components: 

75 ```python 

76 >>> graph = nx.Graph() 

77 >>> graph.add_edges_from(mesh.face_adjacency) 

78 >>> groups = nx.connected_components(graph_connected) 

79 ``` 

80 """ 

81 

82 if mesh is None: 

83 # first generate the list of edges for the current faces 

84 # also return the index for which face the edge is from 

85 edges, edges_face = faces_to_edges(faces, return_index=True) 

86 # make sure edge rows are sorted 

87 edges.sort(axis=1) 

88 else: 

89 # if passed a mesh, used the cached values 

90 edges = mesh.edges_sorted 

91 edges_face = mesh.edges_face 

92 

93 # this will return the indices for duplicate edges 

94 # every edge appears twice in a well constructed mesh 

95 # so for every row in edge_idx: 

96 # edges[edge_idx[*][0]] == edges[edge_idx[*][1]] 

97 # in this call to group rows we discard edges which 

98 # don't occur twice 

99 edge_groups = grouping.group_rows(edges, require_count=2) 

100 

101 if len(edge_groups) == 0: 

102 log.debug("No adjacent faces detected! Did you merge vertices?") 

103 

104 # the pairs of all adjacent faces 

105 # so for every row in face_idx, self.faces[face_idx[*][0]] and 

106 # self.faces[face_idx[*][1]] will share an edge 

107 adjacency = edges_face[edge_groups] 

108 

109 # degenerate faces may appear in adjacency as the same value 

110 nondegenerate = adjacency[:, 0] != adjacency[:, 1] 

111 adjacency = adjacency[nondegenerate] 

112 

113 # sort pairs in-place so we can search for indexes with ordered pairs 

114 adjacency.sort(axis=1) 

115 

116 if return_edges: 

117 adjacency_edges = edges[edge_groups[:, 0][nondegenerate]] 

118 assert len(adjacency_edges) == len(adjacency) 

119 return adjacency, adjacency_edges 

120 

121 return adjacency 

122 

123 

124def face_neighborhood(mesh) -> NDArray[int64]: 

125 """ 

126 Find faces that share a vertex i.e. 'neighbors' faces. 

127 Relies on the fact that an adjacency matrix at a power p 

128 contains the number of paths of length p connecting two nodes. 

129 Here we take the bipartite graph from mesh.faces_sparse to the power 2. 

130 The non-zeros are the faces connected by one vertex. 

131 

132 Returns 

133 ---------- 

134 neighborhood : (n, 2) int 

135 Pairs of faces which share a vertex 

136 """ 

137 

138 VT = mesh.faces_sparse 

139 TT = VT.T * VT 

140 TT.setdiag(0) 

141 TT.eliminate_zeros() 

142 TT = TT.tocoo() 

143 neighborhood = np.concatenate( 

144 (TT.row[:, None], TT.col[:, None]), axis=-1, dtype=np.int64 

145 ) 

146 return neighborhood 

147 

148 

149def face_adjacency_unshared(mesh): 

150 """ 

151 Return the vertex index of the two vertices not in the shared 

152 edge between two adjacent faces 

153 

154 Parameters 

155 ---------- 

156 mesh : Trimesh object 

157 Input mesh 

158 

159 Returns 

160 ----------- 

161 vid_unshared : (len(mesh.face_adjacency), 2) int 

162 Indexes of mesh.vertices 

163 for degenerate faces without exactly 

164 one unshared vertex per face it will be -1 

165 """ 

166 

167 # the non- shared vertex index is the same shape 

168 # as face_adjacency holding vertex indices vs face indices 

169 vid_unshared = np.zeros_like(mesh.face_adjacency, dtype=np.int64) - 1 

170 # get the shared edges between adjacent faces 

171 edges = mesh.face_adjacency_edges 

172 

173 # loop through the two columns of face adjacency 

174 for i, fid in enumerate(mesh.face_adjacency.T): 

175 # faces from the current column of face adjacency 

176 faces = mesh.faces[fid] 

177 # should have one True per row of (3,) 

178 # index of vertex not included in shared edge 

179 unshared = np.logical_not( 

180 np.logical_or( 

181 faces == edges[:, 0].reshape((-1, 1)), 

182 faces == edges[:, 1].reshape((-1, 1)), 

183 ) 

184 ) 

185 # each row should have exactly one uncontained verted 

186 row_ok = unshared.sum(axis=1) == 1 

187 # any degenerate row should be ignored 

188 unshared[~row_ok, :] = False 

189 # set the 

190 vid_unshared[row_ok, i] = faces[unshared] 

191 

192 return vid_unshared 

193 

194 

195def face_adjacency_radius(mesh): 

196 """ 

197 Compute an approximate radius between adjacent faces. 

198 

199 Parameters 

200 -------------- 

201 mesh : trimesh.Trimesh 

202 

203 Returns 

204 ------------- 

205 radii : (len(self.face_adjacency),) float 

206 Approximate radius between faces 

207 Parallel faces will have a value of np.inf 

208 span : (len(self.face_adjacency),) float 

209 Perpendicular projection distance of two 

210 unshared vertices onto the shared edge 

211 """ 

212 

213 # solve for the radius of the adjacent faces 

214 # distance 

215 # R = --------------- 

216 # 2 * sin(theta) 

217 nonzero = mesh.face_adjacency_angles > np.radians(0.01) 

218 denominator = np.abs(2.0 * np.sin(mesh.face_adjacency_angles[nonzero])) 

219 

220 # consider the distance between the non- shared vertices of the 

221 # face adjacency pair as the key distance 

222 point_pairs = mesh.vertices[mesh.face_adjacency_unshared] 

223 vectors = np.diff(point_pairs, axis=1).reshape((-1, 3)) 

224 

225 # the vertex indices of the shared edge for the adjacency pairx 

226 edges = mesh.face_adjacency_edges 

227 # unit vector along shared the edge 

228 edges_vec = util.unitize(np.diff(mesh.vertices[edges], axis=1).reshape((-1, 3))) 

229 

230 # the vector of the perpendicular projection to the shared edge 

231 perp = np.subtract( 

232 vectors, (util.diagonal_dot(vectors, edges_vec).reshape((-1, 1)) * edges_vec) 

233 ) 

234 # the length of the perpendicular projection 

235 span = util.row_norm(perp) 

236 

237 # complete the values for non- infinite radii 

238 radii = np.ones(len(mesh.face_adjacency)) * np.inf 

239 radii[nonzero] = span[nonzero] / denominator 

240 

241 return radii, span 

242 

243 

244def vertex_adjacency_graph(mesh): 

245 """ 

246 Returns a networkx graph representing the vertices and 

247 their connections in the mesh. 

248 

249 Parameters 

250 ---------- 

251 mesh : Trimesh object 

252 

253 Returns 

254 --------- 

255 graph : networkx.Graph 

256 Graph representing vertices and edges between 

257 them where vertices are nodes and edges are edges 

258 

259 Examples 

260 ---------- 

261 This is useful for getting nearby vertices for a given vertex, 

262 potentially for some simple smoothing techniques. 

263 >>> graph = mesh.vertex_adjacency_graph 

264 >>> graph.neighbors(0) 

265 > [1, 3, 4] 

266 """ 

267 g = nx.Graph() 

268 g.add_edges_from(mesh.edges_unique) 

269 return g 

270 

271 

272def shared_edges(faces_a, faces_b): 

273 """ 

274 Given two sets of faces, find the edges which are in both sets. 

275 

276 Parameters 

277 --------- 

278 faces_a : (n, 3) int 

279 Array of faces 

280 faces_b : (m, 3) int 

281 Array of faces 

282 

283 Returns 

284 --------- 

285 shared : (p, 2) int 

286 Edges shared between faces 

287 """ 

288 e_a = np.sort(faces_to_edges(faces_a), axis=1) 

289 e_b = np.sort(faces_to_edges(faces_b), axis=1) 

290 shared = grouping.boolean_rows(e_a, e_b, operation=np.intersect1d) 

291 return shared 

292 

293 

294def facets(mesh, engine: GraphEngineType = None, facet_threshold: Number | None = None): 

295 """ 

296 Find the list of parallel adjacent faces. 

297 

298 Parameters 

299 ----------- 

300 mesh : trimesh.Trimesh 

301 engine 

302 Which graph engine to use 

303 facet_threshold : float 

304 Threshold for two facets to be considered coplanar 

305 

306 Returns 

307 --------- 

308 facets : sequence of (n,) int 

309 Groups of face indexes of 

310 parallel adjacent faces. 

311 """ 

312 if facet_threshold is None: 

313 facet_threshold = tol.facet_threshold 

314 # what is the radius of a circle that passes through the perpendicular 

315 # projection of the vector between the two non- shared vertices 

316 # onto the shared edge, with the face normal from the two adjacent faces 

317 radii = mesh.face_adjacency_radius 

318 # what is the span perpendicular to the shared edge 

319 span = mesh.face_adjacency_span 

320 # a very arbitrary formula for declaring two adjacent faces 

321 # parallel in a way that is hopefully (and anecdotally) robust 

322 # to numeric error 

323 # a common failure mode is two faces that are very narrow with a slight 

324 # angle between them, so here we divide by the perpendicular span 

325 # to penalize very narrow faces, and then square it just for fun 

326 parallel = np.ones(len(radii), dtype=bool) 

327 # if span is zero we know faces are small/parallel 

328 nonzero = np.abs(span) > tol.zero 

329 # faces with a radii/span ratio larger than a threshold pass 

330 parallel[nonzero] = (radii[nonzero] / span[nonzero]) ** 2 > facet_threshold 

331 

332 # run connected components on the parallel faces to group them 

333 components = connected_components( 

334 mesh.face_adjacency[parallel], 

335 nodes=np.arange(len(mesh.faces)), 

336 min_len=2, 

337 engine=engine, 

338 ) 

339 

340 return components 

341 

342 

343def split( 

344 mesh, 

345 only_watertight: bool = True, 

346 repair: bool = True, 

347 adjacency: ArrayLike | None = None, 

348 engine: GraphEngineType = None, 

349 **kwargs, 

350) -> list: 

351 """ 

352 Split a mesh into multiple meshes from face 

353 connectivity. 

354 

355 If only_watertight is true it will only return 

356 watertight meshes and will attempt to repair 

357 single triangle or quad holes. 

358 

359 Parameters 

360 ---------- 

361 mesh : trimesh.Trimesh 

362 The source multibody mesh to split 

363 only_watertight 

364 Only return watertight components and discard 

365 any connected component that isn't fully watertight. 

366 repair 

367 If set try to fill small holes in a mesh, before the 

368 discard step in `only_watertight. 

369 adjacency : (n, 2) int 

370 If passed will be used instead of `mesh.face_adjacency` 

371 engine 

372 Which graph engine to use for the connected components. 

373 

374 Returns 

375 ---------- 

376 meshes : (m,) trimesh.Trimesh 

377 Results of splitting based on parameters. 

378 """ 

379 if adjacency is None: 

380 adjacency = mesh.face_adjacency 

381 

382 if only_watertight: 

383 # the smallest watertight mesh has 4 faces 

384 min_len = 4 

385 else: 

386 # allow any size of connected component 

387 min_len = 1 

388 

389 components = connected_components( 

390 edges=adjacency, nodes=np.arange(len(mesh.faces)), min_len=min_len, engine=engine 

391 ) 

392 return mesh.submesh( 

393 components, only_watertight=only_watertight, repair=repair, **kwargs 

394 ) 

395 

396 

397def connected_components( 

398 edges, min_len: Integer = 1, nodes=None, engine: GraphEngineType = None 

399): 

400 """ 

401 Find groups of connected nodes from an edge list. 

402 

403 Parameters 

404 ----------- 

405 edges : (n, 2) int 

406 Edges between nodes 

407 nodes : (m, ) int or None 

408 List of nodes that exist 

409 min_len : int 

410 Minimum length of a component group to return 

411 engine : str or None 

412 Which graph engine to use (None for automatic): 

413 (None, 'networkx', 'scipy') 

414 

415 

416 Returns 

417 ----------- 

418 components : (n,) sequence of (*,) int 

419 Nodes which are connected 

420 """ 

421 

422 def components_networkx(): 

423 """ 

424 Find connected components using networkx 

425 """ 

426 graph = nx.from_edgelist(edges) 

427 # make sure every face has a node, so single triangles 

428 # aren't discarded (as they aren't adjacent to anything) 

429 if min_len <= 1: 

430 graph.add_nodes_from(nodes) 

431 return [list(i) for i in nx.connected_components(graph)] 

432 

433 def components_csgraph(): 

434 """ 

435 Find connected components using scipy.sparse.csgraph 

436 """ 

437 # label each node 

438 labels = connected_component_labels(edges, node_count=node_count) 

439 

440 # we have to remove results that contain nodes outside 

441 # of the specified node set and reindex 

442 contained = np.zeros(node_count, dtype=bool) 

443 contained[nodes] = True 

444 index = np.arange(node_count, dtype=np.int64)[contained] 

445 components = grouping.group(labels[contained], min_len=min_len) 

446 return [index[c] for c in components] 

447 

448 return components 

449 

450 # check input edges 

451 edges = np.asanyarray(edges, dtype=np.int64) 

452 # if no nodes were specified just use unique 

453 if nodes is None: 

454 nodes = np.unique(edges) 

455 

456 # exit early if we have no nodes 

457 if len(nodes) == 0: 

458 return [] 

459 elif len(edges) == 0: 

460 if min_len <= 1: 

461 return np.reshape(nodes, (-1, 1)).tolist() 

462 else: 

463 return [] 

464 

465 if not util.is_shape(edges, (-1, 2)): 

466 raise ValueError("edges must be (n, 2)!") 

467 

468 # find the maximum index referenced in either nodes or edges 

469 counts = [0] 

470 if len(edges) > 0: 

471 counts.append(edges.max()) 

472 if len(nodes) > 0: 

473 counts.append(nodes.max()) 

474 node_count = np.max(counts) + 1 

475 

476 # remove edges that don't have both nodes in the node set 

477 mask = np.zeros(node_count, dtype=bool) 

478 mask[nodes] = True 

479 edges_ok = mask[edges].all(axis=1) 

480 edges = edges[edges_ok] 

481 

482 # networkx is pure python and is usually 5-10x slower than scipy 

483 engines = collections.OrderedDict( 

484 (("scipy", components_csgraph), ("networkx", components_networkx)) 

485 ) 

486 

487 # if a graph engine has explicitly been requested use it 

488 if engine in engines: 

489 return engines[engine]() 

490 

491 # otherwise, go through our ordered list of graph engines 

492 # until we get to one that has actually been installed 

493 for function in engines.values(): 

494 try: 

495 return function() 

496 # will be raised if the library didn't import correctly above 

497 except BaseException: 

498 continue 

499 raise ImportError("no graph engines available!") 

500 

501 

502def connected_component_labels(edges, node_count=None): 

503 """ 

504 Label graph nodes from an edge list, using scipy.sparse.csgraph 

505 

506 Parameters 

507 ----------- 

508 edges : (n, 2) int 

509 Edges of a graph 

510 node_count : int, or None 

511 The largest node in the graph. 

512 

513 Returns 

514 ---------- 

515 labels : (node_count,) int 

516 Component labels for each node 

517 """ 

518 matrix = edges_to_coo(edges, node_count) 

519 _body_count, labels = csgraph.connected_components(matrix, directed=False) 

520 

521 if node_count is not None: 

522 assert len(labels) == node_count 

523 

524 return labels 

525 

526 

527def _split_traversal(traversal: NDArray, edges_tree) -> list[NDArray]: 

528 """ 

529 Given a traversal as a list of nodes split the traversal 

530 if a sequential index pair is not in the given edges. 

531 Useful since the implementation of DFS we're using will 

532 happily return disconnected values in a flat traversal. 

533 

534 Parameters 

535 -------------- 

536 traversal : (m,) int 

537 Traversal through edges 

538 edges_tree : cKDTree 

539 A way to reconstruct original edge indices from 

540 sorted (n, 2) edge values. This is a slight misuse of a 

541 kdtree since one could just hash the tuples of the integer 

542 edges, but that isn't possible with numpy arrays easily 

543 and this allows a vectorized reconstruction. 

544 

545 Returns 

546 --------------- 

547 split : sequence of (p,) int 

548 Traversals split into only connected paths. 

549 """ 

550 # turn the (n,) traversal into (n-1, 2) edges 

551 # save the original order of the edges for reconstruction 

552 trav_edge = np.column_stack((traversal[:-1], traversal[1:])) 

553 

554 # check to see if the traversal edges exists in the original edges 

555 # the tree is holding the sorted edges so query after sorting 

556 exists = edges_tree.query(np.sort(trav_edge, axis=1))[0] < 1e-10 

557 

558 if exists.all(): 

559 split = [traversal] 

560 else: 

561 # contiguous groups of edges 

562 blocks = grouping.blocks(exists, min_len=1, only_nonzero=True) 

563 split = [ 

564 np.concatenate([trav_edge[:, 0][b], trav_edge[b[-1]][1:]]) for b in blocks 

565 ] 

566 

567 # a traversal may be effectively closed so check 

568 # to see if we need to add on the first index to the end 

569 needs_close = np.array( 

570 [ 

571 len(s) > 2 

572 and s[0] != s[-1] 

573 and edges_tree.query(sorted([s[0], s[-1]]))[0] < 1e-10 

574 for s in split 

575 ] 

576 ) 

577 

578 if needs_close.any(): 

579 for i in np.nonzero(needs_close)[0]: 

580 split[i] = np.concatenate([split[i], split[i][:1]]) 

581 

582 if tol.strict: 

583 for s in split: 

584 check_edge = np.sort(np.column_stack((s[:-1], s[1:])), axis=1) 

585 assert (edges_tree.query(check_edge)[0] < 1e-10).all() 

586 

587 return split 

588 

589 

590def fill_traversals(traversals: Sequence, edges: ArrayLike) -> Sequence | NDArray: 

591 """ 

592 Convert a traversal of a list of edges into a sequence of 

593 traversals where every pair of consecutive node indexes 

594 is an edge in a passed edge list 

595 

596 Parameters 

597 ------------- 

598 traversals : sequence of (m,) int 

599 Node indexes of traversals of a graph 

600 edges : (n, 2) int 

601 Pairs of connected node indexes 

602 

603 Returns 

604 -------------- 

605 splits : sequence of (p,) int 

606 Node indexes of connected traversals 

607 """ 

608 # make sure edges are correct type 

609 edges = np.sort(edges, axis=1) 

610 edges_tree = cKDTree(edges) 

611 

612 # if there are no traversals just return edges 

613 if len(traversals) == 0: 

614 return edges.copy() 

615 

616 splits = [] 

617 for nodes in traversals: 

618 # split traversals to remove edges that don't actually exist 

619 splits.extend(_split_traversal(traversal=nodes, edges_tree=edges_tree)) 

620 

621 # turn the split traversals back into (n, 2) edges 

622 included = util.vstack_empty([np.column_stack((i[:-1], i[1:])) for i in splits]) 

623 if len(included) > 0: 

624 # sort included edges in place 

625 included.sort(axis=1) 

626 # make sure any edges not included in split traversals 

627 # are just added as a length 2 traversal 

628 splits.extend(grouping.boolean_rows(edges, included, operation=np.setdiff1d)) 

629 else: 

630 # no edges were included, so our filled traversal 

631 # is just the original edges copied over 

632 splits = edges.copy() 

633 

634 return splits 

635 

636 

637def traversals(edges, mode="bfs"): 

638 """ 

639 Given an edge list generate a sequence of ordered depth 

640 first search traversals using scipy.csgraph routines. 

641 

642 Parameters 

643 ------------ 

644 edges : (n, 2) int 

645 Undirected edges of a graph 

646 mode : str 

647 Traversal type, 'bfs' or 'dfs' 

648 

649 Returns 

650 ----------- 

651 traversals : (m,) sequence of (p,) int 

652 Ordered DFS or BFS traversals of the graph. 

653 """ 

654 edges = np.array(edges, dtype=np.int64) 

655 if len(edges) == 0: 

656 return [] 

657 elif not util.is_shape(edges, (-1, 2)): 

658 raise ValueError("edges are not (n, 2)!") 

659 

660 # pick the traversal method 

661 mode = str(mode).lower().strip() 

662 if mode == "bfs": 

663 func = csgraph.breadth_first_order 

664 elif mode == "dfs": 

665 func = csgraph.depth_first_order 

666 else: 

667 raise ValueError("traversal mode must be either dfs or bfs") 

668 

669 # make sure edges are sorted so we can query 

670 # an ordered pair later 

671 edges.sort(axis=1) 

672 # coo_matrix for csgraph routines 

673 graph = edges_to_coo(edges) 

674 

675 # get unique nodes AND leaf node info from bincount 

676 bincount = np.bincount(edges.ravel()) 

677 

678 # a leaf node occurs exactly once 

679 nodes_leaf = np.nonzero(bincount == 1)[0] 

680 # a non-leaf node occurs more than once 

681 nodes = np.nonzero(bincount > 1)[0] 

682 

683 # collect traversals 

684 traversals = [] 

685 # keep track of which nodes have been visited 

686 visited = np.zeros(len(bincount) + 1, dtype=np.bool_) 

687 

688 # process leaf nodes first to avoid DFS backtracking 

689 # starting DFS from an interior node of an open path causes 

690 # backtracking, which produces non-edge consecutive pairs that 

691 # fill_traversals then splits a single path into pieces 

692 for start in np.concatenate((nodes_leaf, nodes)): 

693 if visited[start]: 

694 continue 

695 

696 # get an (n,) ordered traversal from this start 

697 ordered = func( 

698 graph, i_start=start, return_predecessors=False, directed=False 

699 ).astype(np.int64) 

700 

701 # store the traversal and mark all nodes as visited 

702 traversals.append(ordered) 

703 visited[ordered] = True 

704 

705 return traversals 

706 

707 

708def edges_to_coo(edges, count=None, data=None): 

709 """ 

710 Given an edge list, return a boolean scipy.sparse.coo_matrix 

711 representing the edges in matrix form. 

712 

713 Parameters 

714 ------------ 

715 edges : (n, 2) int 

716 Edges of a graph 

717 count : int 

718 The total number of nodes in the graph 

719 if None: count = edges.max() + 1 

720 data : (n,) any 

721 Assign data to each edge, if None will 

722 be bool True for each specified edge 

723 

724 Returns 

725 ------------ 

726 matrix: (count, count) scipy.sparse.coo_matrix 

727 Sparse COO 

728 """ 

729 edges = np.asanyarray(edges, dtype=np.int64) 

730 if not (len(edges) == 0 or util.is_shape(edges, (-1, 2))): 

731 raise ValueError("edges must be (n, 2)!") 

732 

733 # if count isn't specified just set it to largest 

734 # value referenced in edges 

735 if count is None: 

736 count = edges.max() + 1 

737 count = int(count) 

738 

739 # if no data is specified set every specified edge 

740 # to True 

741 if data is None: 

742 data = np.ones(len(edges), dtype=bool) 

743 

744 return coo_matrix((data, edges.T), dtype=data.dtype, shape=(count, count)) 

745 

746 

747def neighbors(edges, max_index=None, directed=False): 

748 """ 

749 Find the neighbors for each node in an edgelist graph. 

750 

751 TODO : re-write this with sparse matrix operations 

752 

753 Parameters 

754 ------------ 

755 edges : (n, 2) int 

756 Connected nodes 

757 directed : bool 

758 If True, only connect edges in one direction 

759 

760 Returns 

761 --------- 

762 neighbors : sequence 

763 Vertex index corresponds to set of other vertex indices 

764 """ 

765 neighbors = collections.defaultdict(set) 

766 if directed: 

767 [neighbors[edge[0]].add(edge[1]) for edge in edges] 

768 else: 

769 [ 

770 (neighbors[edge[0]].add(edge[1]), neighbors[edge[1]].add(edge[0])) 

771 for edge in edges 

772 ] 

773 

774 if max_index is None: 

775 max_index = edges.max() + 1 

776 array = [list(neighbors[i]) for i in range(max_index)] 

777 

778 return array 

779 

780 

781def smooth_shade(mesh, angle: Number | None = None, facet_minarea: Number | None = 10.0): 

782 """ 

783 Return a non-watertight version of the mesh which 

784 will render nicely with smooth shading by 

785 disconnecting faces at sharp angles to each other. 

786 

787 Parameters 

788 ----------- 

789 mesh : trimesh.Trimesh 

790 Source geometry 

791 angle : float or None 

792 Angle in radians face pairs with angles 

793 smaller than this will appear smoothed 

794 facet_minarea : float or None 

795 Minimum area fraction to consider 

796 IE for `facets_minarea=25` only facets larger 

797 than `mesh.area / 25` will be considered. 

798 

799 Returns 

800 --------- 

801 smooth : trimesh.Trimesh 

802 Geometry with disconnected face patches 

803 """ 

804 if angle is None: 

805 angle = np.radians(20) 

806 

807 # if the mesh has no adjacent faces return a copy 

808 if len(mesh.face_adjacency) == 0: 

809 return mesh.copy() 

810 

811 # face pairs below angle threshold 

812 angle_ok = mesh.face_adjacency_angles < angle 

813 # subset of face adjacency 

814 adjacency = mesh.face_adjacency[angle_ok] 

815 

816 # coplanar groups of faces 

817 facets = [] 

818 nodes = None 

819 # collect coplanar regions for smoothing 

820 if facet_minarea is not None: 

821 areas = mesh.area_faces 

822 min_area = mesh.area / facet_minarea 

823 try: 

824 # we can survive not knowing facets 

825 # exclude facets with few faces 

826 facets = [f for f in mesh.facets if areas[f].sum() > min_area] 

827 if len(facets) > 0: 

828 # mask for removing adjacency pairs where 

829 # one of the faces is contained in a facet 

830 mask = np.ones(len(mesh.faces), dtype=bool) 

831 mask[np.hstack(facets)] = False 

832 # apply the mask to adjacency 

833 adjacency = adjacency[mask[adjacency].all(axis=1)] 

834 # nodes are no longer every faces 

835 nodes = np.unique(adjacency) 

836 except BaseException: 

837 log.warning("failed to calculate facets", exc_info=True) 

838 # run connected components on facet adjacency 

839 components = connected_components(adjacency, min_len=2, nodes=nodes) 

840 

841 # add back coplanar groups if any exist 

842 if len(facets) > 0: 

843 components.extend(facets) 

844 

845 if len(components) == 0: 

846 # if no components for some reason 

847 # just return a copy of the original mesh 

848 return mesh.copy() 

849 

850 # add back any faces that were missed 

851 unique = np.unique(np.hstack(components)) 

852 if len(unique) != len(mesh.faces): 

853 # things like single loose faces 

854 # or groups below facet_minlen 

855 broke = np.setdiff1d(np.arange(len(mesh.faces)), unique) 

856 components.extend(broke.reshape((-1, 1))) 

857 

858 # get a submesh as a single appended Trimesh 

859 smooth = mesh.submesh(components, only_watertight=False, append=True) 

860 # store face indices from original mesh 

861 smooth.metadata["original_components"] = components 

862 # smoothed should have exactly the same number of faces 

863 if len(smooth.faces) != len(mesh.faces): 

864 log.warning("face count in smooth wrong!") 

865 return smooth 

866 

867 

868def is_watertight( 

869 edges: ArrayLike, edges_sorted: ArrayLike | None = None 

870) -> tuple[bool, bool]: 

871 """ 

872 Parameters 

873 ----------- 

874 edges : (n, 2) int 

875 List of vertex indices 

876 edges_sorted : (n, 2) int 

877 Pass vertex indices sorted on axis 1 as a speedup 

878 

879 Returns 

880 --------- 

881 watertight : boolean 

882 Whether every edge is shared by an even 

883 number of faces 

884 winding : boolean 

885 Whether every shared edge is reversed 

886 """ 

887 # passing edges_sorted is a speedup only 

888 if edges_sorted is None: 

889 edges_sorted = np.sort(edges, axis=1) 

890 

891 # group sorted edges throwing away any edge 

892 # that doesn't appear exactly twice 

893 groups = grouping.group_rows(edges_sorted, require_count=2) 

894 # if we didn't throw away any edges that means 

895 # every edge shows up exactly twice 

896 watertight = bool((len(groups) * 2) == len(edges)) 

897 

898 # check that the un-sorted duplicate edges are reversed 

899 opposing = edges[groups].reshape((-1, 4))[:, 1:3].T 

900 winding = bool(np.equal(*opposing).all()) 

901 

902 return watertight, winding 

903 

904 

905def graph_to_svg(graph): 

906 """ 

907 Turn a networkx graph into an SVG string 

908 using graphviz `dot`. 

909 

910 Parameters 

911 ---------- 

912 graph: networkx graph 

913 

914 Returns 

915 --------- 

916 svg: string, pictoral layout in SVG format 

917 """ 

918 

919 import subprocess 

920 import tempfile 

921 

922 with tempfile.NamedTemporaryFile() as dot_file: 

923 nx.drawing.nx_agraph.write_dot(graph, dot_file.name) 

924 svg = subprocess.check_output(["dot", dot_file.name, "-Tsvg"]) 

925 return svg 

926 

927 

928def multigraph_paths(G, source: Hashable, cutoff: Integer | None = None): 

929 """ 

930 For a networkx MultiDiGraph, find all paths from a source node 

931 to leaf nodes. This function returns edge instance numbers 

932 in addition to nodes, unlike networkx.all_simple_paths. 

933 

934 Parameters 

935 --------------- 

936 G : networkx.MultiDiGraph 

937 Graph to evaluate 

938 source : Hashable 

939 Node to start traversal at 

940 cutoff : Integer | None 

941 Number of nodes to visit 

942 If None will visit all nodes 

943 

944 Returns 

945 ---------- 

946 traversals : (n,) list of [(node, edge instance index), ] paths 

947 Traversals of the multigraph 

948 """ 

949 if cutoff is None: 

950 cutoff = (len(G.edges()) * len(G.nodes())) + 1 

951 

952 # the path starts at the node specified 

953 current = [(source, 0)] 

954 # traversals we need to go back and do 

955 queue = [] 

956 # completed paths 

957 traversals = [] 

958 

959 for _ in range(cutoff): 

960 # paths are stored as (node, instance) so 

961 # get the node of the last place visited 

962 current_node = current[-1][0] 

963 # get all the children of the current node 

964 child = G[current_node] 

965 

966 if len(child) == 0: 

967 # we have no children, so we are at the end of this path 

968 # save the path as a completed traversal 

969 traversals.append(current) 

970 # if there is nothing on the queue, we are done 

971 if len(queue) == 0: 

972 break 

973 # otherwise continue traversing with the next path 

974 # on the queue 

975 current = queue.pop() 

976 else: 

977 # oh no, we have multiple edges from current -> child 

978 start = True 

979 # iterate through child nodes and edge instances 

980 for node in child.keys(): 

981 for instance in child[node].keys(): 

982 if start: 

983 # if this is the first edge, keep it on the 

984 # current traversal and save the others for later 

985 current.append((node, instance)) 

986 start = False 

987 else: 

988 # this child has multiple instances 

989 # so we will need to traverse them multiple times 

990 # we appended a node to current, so only take the 

991 # first n-1 visits 

992 queue.append(current[:-1] + [(node, instance)]) 

993 return traversals 

994 

995 

996def multigraph_collect(G, traversal, attrib=None): 

997 """ 

998 Given a MultiDiGraph traversal, collect attributes along it. 

999 

1000 Parameters 

1001 ------------- 

1002 G: networkx.MultiDiGraph 

1003 traversal: (n) list of (node, instance) tuples 

1004 attrib: dict key, name to collect. If None, will return all 

1005 

1006 Returns 

1007 ------------- 

1008 collected: (len(traversal) - 1) list of attributes 

1009 """ 

1010 

1011 collected = [] 

1012 for u, v in util.pairwise(traversal): 

1013 attribs = G[u[0]][v[0]][v[1]] 

1014 if attrib is None: 

1015 collected.append(attribs) 

1016 else: 

1017 collected.append(attribs[attrib]) 

1018 return collected