File: test_graph.py

package info (click to toggle)
trimesh 4.5.1-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 33,416 kB
  • sloc: python: 35,596; makefile: 96; javascript: 85; sh: 38
file content (279 lines) | stat: -rw-r--r-- 10,564 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
try:
    from . import generic as g
except BaseException:
    import generic as g


class GraphTest(g.unittest.TestCase):
    def setUp(self):
        self.engines = []
        try:
            self.engines.append("scipy")
        except BaseException:
            pass
        try:
            self.engines.append("networkx")
        except BaseException:
            pass

    def test_soup(self):
        # a soup of random triangles, with no adjacent pairs
        soup = g.get_mesh("soup.stl")

        assert len(soup.face_adjacency) == 0
        assert len(soup.face_adjacency_radius) == 0
        assert len(soup.face_adjacency_edges) == 0
        assert len(soup.face_adjacency_convex) == 0
        assert len(soup.face_adjacency_unshared) == 0
        assert len(soup.face_adjacency_angles) == 0
        assert len(soup.facets) == 0

    def test_components(self):
        # a soup of random triangles, with no adjacent pairs
        soup = g.get_mesh("soup.stl")
        # a mesh with multiple watertight bodies
        mult = g.get_mesh("cycloidal.ply")
        # a mesh with a single watertight body
        sing = g.get_mesh("featuretype.STL")
        # mesh with a single tetrahedron
        tet = g.get_mesh("tet.ply")

        for engine in self.engines:
            # without requiring watertight the split should be into every face
            split = soup.split(only_watertight=False, engine=engine)
            assert len(split) == len(soup.faces)

            # with watertight there should be an empty list
            split = soup.split(only_watertight=True, engine=engine)
            assert len(split) == 0

            split = mult.split(only_watertight=False, engine=engine)
            assert len(split) >= 119

            split = mult.split(only_watertight=True, engine=engine)
            assert len(split) >= 117

            # random triangles should have no facets
            facets = g.trimesh.graph.facets(mesh=soup, engine=engine)
            assert len(facets) == 0

            facets = g.trimesh.graph.facets(mesh=mult, engine=engine)
            assert all(len(i) >= 2 for i in facets)
            assert len(facets) >= 8654

            split = sing.split(only_watertight=False, engine=engine)
            assert len(split) == 1
            assert split[0].is_watertight
            assert split[0].is_winding_consistent

            split = sing.split(only_watertight=True, engine=engine)
            assert len(split) == 1
            assert split[0].is_watertight
            assert split[0].is_winding_consistent

            # single tetrahedron
            assert tet.is_volume
            assert tet.body_count == 1
            # regardless of method or flag we should have one body result
            split = tet.split(only_watertight=True, engine=engine)
            assert len(split) == 1
            split = tet.split(only_watertight=False, engine=engine)
            assert len(split) == 1

    def test_vertex_adjacency_graph(self):
        f = g.trimesh.graph.vertex_adjacency_graph

        # a mesh with a single watertight body
        sing = g.get_mesh("featuretype.STL")
        vert_adj_g = f(sing)
        assert len(sing.vertices) == len(vert_adj_g)

    def test_engine_time(self):
        for mesh in g.get_meshes():
            tic = [g.time.time()]
            for engine in self.engines:
                mesh.split(engine=engine, only_watertight=False)
                g.trimesh.graph.facets(mesh=mesh, engine=engine)
                tic.append(g.time.time())

            diff = g.np.abs(g.np.diff(tic))
            if diff.min() > 0.0:
                diff /= diff.min()

            g.log.info(
                "graph engine on %s (scale %f sec):\n%s",
                mesh.metadata["file_name"],
                diff.min(),
                str(g.np.column_stack((self.engines, diff))),
            )

    def test_smoothed(self):
        # Make sure smoothing is keeping the same number
        # of faces.

        for name in ["ADIS16480.STL", "featuretype.STL"]:
            mesh = g.get_mesh(name)
            assert len(mesh.faces) == len(mesh.smooth_shaded.faces)

    def test_engines(self):
        edges = g.np.arange(10).reshape((-1, 2))
        for i in range(0, 20):
            check_engines(nodes=g.np.arange(i), edges=edges)
        edges = g.np.column_stack((g.np.arange(1, 11), g.np.arange(0, 10)))
        for i in range(0, 20):
            check_engines(nodes=g.np.arange(i), edges=edges)

    def test_watertight(self):
        m = g.get_mesh("shared.STL")  # NOQA
        # assert m.is_watertight
        # assert m.is_winding_consistent
        # assert m.is_volume

    def test_traversals(self):
        # Test traversals (BFS+DFS)

        # generate some simple test data
        simple_nodes = g.np.arange(20)
        simple_edges = g.np.column_stack((simple_nodes[:-1], simple_nodes[1:]))
        simple_edges = g.np.vstack(
            (simple_edges, [[19, 0], [10, 1000], [500, 501]])
        ).astype(g.np.int64)

        all_edges = g.data["edges"]
        all_edges.append(simple_edges)

        for edges in all_edges:
            edges = g.np.array(edges, dtype=g.np.int64)
            assert g.trimesh.util.is_shape(edges, (-1, 2))

            # collect the new nodes
            nodes = g.np.unique(edges)

            # the basic BFS/DFS traversal
            dfs_basic = g.trimesh.graph.traversals(edges, "dfs")
            bfs_basic = g.trimesh.graph.traversals(edges, "bfs")
            # check return types
            assert all(i.dtype == g.np.int64 for i in dfs_basic)
            assert all(i.dtype == g.np.int64 for i in bfs_basic)

            # check to make sure traversals visited every node
            dfs_set = set(g.np.hstack(dfs_basic))
            bfs_set = set(g.np.hstack(bfs_basic))
            nodes_set = set(nodes)
            assert dfs_set == nodes_set
            assert bfs_set == nodes_set

            # check traversal filling
            # fill_traversals should always include every edge
            # regardless of the path so test on bfs/dfs/empty
            for traversal in [dfs_basic, bfs_basic, []]:
                # disconnect consecutive nodes that are not edges
                # and add edges that were left off by jumps
                dfs = g.trimesh.graph.fill_traversals(traversal, edges)
                # edges that are included in the new separated traversal
                inc = g.trimesh.util.vstack_empty(
                    [g.np.column_stack((i[:-1], i[1:])) for i in dfs]
                )

                # make a set from edges included in the traversal
                inc_set = {
                    i.tobytes()
                    for i in g.trimesh.grouping.hashable_rows(g.np.sort(inc, axis=1))
                }
                # make a set of the source edges we were supposed to include
                edge_set = {
                    i.tobytes()
                    for i in g.trimesh.grouping.hashable_rows(g.np.sort(edges, axis=1))
                }

                # we should have exactly the same edges
                # after the filled traversal as we started with
                assert len(inc) == len(edges)
                # every edge should occur exactly once
                assert len(inc_set) == len(inc)
                # unique edges should be the same
                assert inc_set == edge_set

                # check all return dtypes
                assert all(i.dtype == g.np.int64 for i in dfs)

    def test_adjacency(self):
        for add_degen in [False, True]:
            for name in ["featuretype.STL", "soup.stl"]:
                m = g.get_mesh(name)
                if add_degen:
                    # make the first face degenerate
                    m.faces[0][2] = m.faces[0][0]
                # degenerate faces should be filtered
                assert g.np.not_equal(*m.face_adjacency.T).all()

                # check the various paths of calling face adjacency
                a = g.trimesh.graph.face_adjacency(
                    m.faces.view(g.np.ndarray).copy(), return_edges=False
                )
                b, be = g.trimesh.graph.face_adjacency(
                    m.faces.view(g.np.ndarray).copy(), return_edges=True
                )
                c = g.trimesh.graph.face_adjacency(mesh=m, return_edges=False)
                c, ce = g.trimesh.graph.face_adjacency(mesh=m, return_edges=True)
                # make sure they all return the expected result
                assert g.np.allclose(a, b)
                assert g.np.allclose(a, c)
                assert len(be) == len(a)
                assert len(ce) == len(a)

                # package properties to loop through
                zips = zip(
                    m.face_adjacency, m.face_adjacency_edges, m.face_adjacency_unshared
                )
                for a, e, v in zips:
                    # get two adjacenct faces as a set
                    fa = set(m.faces[a[0]])
                    fb = set(m.faces[a[1]])

                    # face should be different
                    assert fa != fb
                    # shared edge should be in both faces

                    # removing 2 vertices should leave one
                    da = fa.difference(e)
                    db = fb.difference(e)
                    assert len(da) == 1
                    assert len(db) == 1

                    # unshared vertex should be correct
                    assert da.issubset(v)
                    assert db.issubset(v)
                    assert da != db
                    assert len(v) == 2


def check_engines(edges, nodes):
    """
    Make sure connected component graph engines are
    returning the exact same values
    """
    results = []
    engines = [None, "scipy", "networkx"]

    for engine in engines:
        c = g.trimesh.graph.connected_components(edges, nodes=nodes, engine=engine)
        if len(c) > 0:
            # check to see if every resulting component
            # was in the passed set of nodes
            diff = g.np.setdiff1d(g.np.hstack(c), nodes)
            assert len(diff) == 0
        # store the result as a set of tuples so we can compare
        results.append({tuple(sorted(i)) for i in c})

    # make sure different engines are returning the same thing
    try:
        assert all(i == results[0] for i in results[1:])
    except BaseException as E:
        g.log.debug(results)
        raise E


if __name__ == "__main__":
    g.trimesh.util.attach_to_log()
    g.unittest.main()