Suppose we have a graph g
and a subset of vs = VertexList[g]
. The vertex names of g
could be anything.
How can I quickly and reliably get the subgraph induced by vs
?
Subgraph[g, vs]
does not work reliably. Consider the following example:
Let's take a list of sets,
sets = {{2}, {3}, {2, 3}}
Their elements are
elements = Union @@ sets
(* {2, 3} *)
Now let us build the containment-relationship graph:
g = RelationGraph[MemberQ, Join[sets, elements]]
This is a subset of it's elements:
vs1 = {2,3}
SubsetQ[VertexList[g], vs1]
(* True *)
Subgraph
does not give what I need and described above:
Subgraph[g, vs1, VertexLabels -> Automatic]
Getting the subgraph of a larger graph is a fundamental operation. Is it possible in Mathematica?
Note that when developing a package, it is not possible to control the input that the package functions receive. I need a way that is fast and that works with any graph and any subset of its vertices. A solution that works only with the example graph from above is not satisfactory.
I posted this question because I am hoping that Subgraph
has some way to disambiguate its input.
Extract
has a potentially ambiguous syntax. But it's not really ambiguous. Extract[list, 1]
takes the first element. What does Extract[list, {1,2}]
do? it takes element 2 at level 1, and not the first two elements. For that we can use Extract[list, {{1}, {2}]]
. The unambiguous way is Extract[..., {pos1, pos2, ...}]
where each pos
is a List
. This is a robust syntax.
Lookup
has a potentially ambiguous syntax. But again there's a completely unabiguous version: use a list as the second argument. asc = <|{1, 2} -> "a", 1 -> "b", 2 -> "c"|>;
, then Lookup[asc, {1,2}]
gives the results for keys 1
and 2
and Lookup[asc, {{1,2}}]
gives it for key {1,2}
in a list. I can program confidently with this. There's also Key
if I want a single result.
Subgraph
is complicated because the second argument can be either a list of vertices or a pattern, which is an extremely general thing. Is there any way out or is the design just broken?
VertexDelete
suffers from the same problem.