Find connected components in list of triangle vertices

风格不统一 提交于 2020-05-16 05:53:10

问题


Consider two graphs, G1 = (V1, E1), G2 = (V2, E2)

V1 = {1,2,3,4,5,6}
V2 = {7,8,9,10,11,12}

In space, these vertices are connected by triangles faces (each with three vertices)

F1 = [[ 2,  1,  0],  [ 0,  3,  2],  [ 1,  4,  0],  [ 0,  4,  3],  [ 5,  1,  2],  [ 3,  5,  2], [ 5,  4,  1],  [ 4,  5,  3]]  
F2 = [[ 8,  7,  6],  [ 6,  9,  8],  [ 7, 10,  6],  [ 6, 10,  9], [11,  7,  8],  [ 9, 11,  8],  [11, 10,  7],  [10, 11,  9]]

The above is what I am trying to find. If we are given the entire array of faces:

faces = [[ 2,  1,  0],  [ 0,  3,  2],  [ 1,  4,  0],  [ 0,  4,  3],  [ 5,  1,  2],  [ 3,  5,  2],
 [ 5,  4,  1],  [ 4,  5,  3],  [ 8,  7,  6],  [ 6,  9,  8],  [ 7, 10,  6],  [ 6, 10,  9],
 [11,  7,  8],  [ 9, 11,  8],  [11, 10,  7],  [10, 11,  9]]

can we find the connected components, and separate into F1 and F2?

A version of this problem has been solved in Mathematica, but I cannot translate.

My work is found in this post.


回答1:


Making a graph from your faces is pretty straightforward: each triplet yields 3 edges corresponding to all combinations of the triplet's members. Then it is just a matter of instantiating the networkx Graph object and calling networkx.algorithms.components.connected_components.

#!/usr/bin/env python
"""
Given a list of triangles, find the connected components.

https://stackoverflow.com/q/61584283/2912349
"""
import itertools
import networkx as nx

faces = [[ 2,  1,  0],  [ 0,  3,  2],  [ 1,  4,  0],  [ 0,  4,  3],  [ 5,  1,  2],  [ 3,  5,  2],
         [ 5,  4,  1],  [ 4,  5,  3],  [ 8,  7,  6],  [ 6,  9,  8],  [ 7, 10,  6],  [ 6, 10,  9],
         [11,  7,  8],  [ 9, 11,  8],  [11, 10,  7],  [10, 11,  9]]

#create graph
edges = []
for face in faces:
    edges.extend(list(itertools.combinations(face, 2)))
g = nx.from_edgelist(edges)

# compute connected components and print results
components = list(nx.algorithms.components.connected_components(g))

for component in components:
    print(component)

# {0, 1, 2, 3, 4, 5}
# {6, 7, 8, 9, 10, 11}

# separate faces by component
component_to_faces = dict()
for component in components:
    component_to_faces[tuple(component)] = [face for face in faces if set(face) <= component] # <= operator tests for subset relation

for component, component_faces in component_to_faces.items():
    print(component, component_faces)
# (0, 1, 2, 3, 4, 5) [[2, 1, 0], [0, 3, 2], [1, 4, 0], [0, 4, 3], [5, 1, 2], [3, 5, 2], [5, 4, 1], [4, 5, 3]]
# (6, 7, 8, 9, 10, 11) [[8, 7, 6], [6, 9, 8], [7, 10, 6], [6, 10, 9], [11, 7, 8], [9, 11, 8], [11, 10, 7], [10, 11, 9]]


来源:https://stackoverflow.com/questions/61584283/find-connected-components-in-list-of-triangle-vertices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!