Skip to content

Consolidate could_be_isomorphic - #7852

Merged
dschult merged 10 commits into
networkx:mainfrom
rossbar:consolidate-could-be-isomorphic
Mar 31, 2025
Merged

dschult merged 10 commits into
networkx:mainfrom
rossbar:consolidate-could-be-isomorphic

Conversation

@rossbar

@rossbar rossbar commented Feb 12, 2025

Copy link
Copy Markdown
Contributor

This is a left-over idea from the summit that I thought I'd write up for further discussion!

NetworkX has a function could_be_isomorphic to check various properties of two graphs to determine whether or not they, well, could be isomorphic. could_be_isomorphic checks three properties: 1) degree sequences, 2) sequences of triangles, and 3) sequences of number-of-cliques.

There also exist two other functions, fast_could_be_isomorphic and faster_could_be_isomorphic that check degree+triangles and just degree, respectively. IMO, the name of these functions doesn't do a whole lot to illuminate what they are checking. There is also a lot of code duplication between these three functions as all of them check degree, two check triangles, etc.

Therefore I thought it might be worth trying to consolidate things a bit. This is one proposal to do so: adding a mode= kwarg to could_be_isomorphic to determine which properties to check. For consistency, I've used the same designation as the functions (i.e. "fast" and "faster") but one could imagine different patterns here. For example, we could do something like check="cdt" where "c" indicates cliques, "d" degree and "t" triangles, to allow users to specify whichever combination of property checks they'd like (e.g. check="cd" for cliques and degree, check="t" for just triangles, etc.)

I'm mostly looking for opinions here, so LMK what you think!

@rossbar rossbar added type: Enhancements Discussion Issues for discussion and decision making labels Feb 12, 2025
 - Make sure properties are collated before sorting.
 - Change API to use character mapping to specify which properties
   to check.

Co-authored-by: Erik Welch <[email protected]>
@rossbar
rossbar force-pushed the consolidate-could-be-isomorphic branch from 738674f to 03464c6 Compare March 1, 2025 23:47

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this demonstration @rossbar
I think it is turning into more than a proposal.
I have some thoughts below -- mostly adding
more docs and thinking about whether we
should add "short-cut" tests that would be redundant
if the answer turns out to be True (but not very costly)
and would avoid property computation if the answer shows
up False using only some of the properties.

assert iso.fast_could_be_isomorphic(self.G3, self.G2)
assert not iso.fast_could_be_isomorphic(self.G3, self.G5)
assert not iso.fast_could_be_isomorphic(self.G1, self.G6)
@pytest.mark.parametrize("fn", (iso.fast_could_be_isomorphic, fast_cbi))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a test for the example where the full table is needed (not each row separately) to report that they are not isomorphic? (suggestions put at beginning of previous change -- but no change occurs to that line.)

Suggested change
@pytest.mark.parametrize("fn", (iso.fast_could_be_isomorphic, fast_cbi))
def test_full table_of_properties(self):
G1 = nx.Graph([(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (3, 4), (4, 5), (4, 6)])
G2 = G1.copy()
G1.add_edge(0, 7)
G2.add_edge(4, 7)
assert not nx.could_be_isomorphic(G1, G2)
@pytest.mark.parametrize("fn", (iso.fast_could_be_isomorphic, fast_cbi))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes we definitely should - I tried but failed to come up with such a case :)

Unfortunately this proposed case also doesn't work because G1.order() = 7 and G2.order() = 8 (order is the very first check)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmmm.... I think both G1 and G2 have nodes 0-7 so they should have order=8 ... right?
I tried drawing an ascii picture for this.

G1: 1   3    G2: 1   3       
    |\ / \       |\ / \     
    | 0---4      | 0---4   
    |/ \  |\     |/   /|\  
    2   7 6 5    2   7 6 5  

The key being 1, 2, 3, 5, 6, 7 don't change. 0 and 4 have two and one triangles in both. respectively. but their degree gets switched between 4 and 5. So the degree sequence is the same, the triangle sequence is the same, but if you compare (degree, triangle) pairs G1 has a [(5,2), (4,1)] while G2 has [(4,2), (5,1)]. This one doesn't require the cliques. But it does require making the property tuples for each node.

@rossbar rossbar Mar 7, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, I screwed up the G1 and G2 (i.e. I did G1.add_edge twice :) ).

On a related note, I decided to investigate potential test cases by brute force! Specifically, looking at all fully-connected, non-isomorphic pairs of graphs with 7 nodes (drawn from the graph atlas). There are a couple hundred such examples :)

I'll fix my error and add this test!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay - I added the test in 62c825c . It's a nice test that probes areas that the current tests don't, but unfortunately it doesn't quite get all the way to exactly what we want - the reason for this is the difference between sorting the properties individually vs. combined! It turns out that considering the combined degree-triangle property is enough to establish a difference, and the clique comparison is never really needed.

I think this test should be added and we should continue trying to find others! I have potential cases from the brute-force search over all 7-node connected graphs that I will investigate further!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe I've reached the bottom of the rabbit hole...

According to my analysis (which I intend to propose as an nx-guide, because I found it quite interesting & fun), there are only two possible graph-pairs out of all fully-connected graphs with 7 nodes that have the same combined degree-triangle distribution but a different maximal-clique distribution. In other words, using the terminology proposed in this PR, there are only two graph pairs that satisfy could_be_isomorphic(G, H, properties="dt") but don't satisfy could_be_isomorphic(G, H, properties="dtc"):

pair1

pair2

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work!
I spent a while looking for pairs of graphs that had the same d and t and c sequences but didn't have the same sequence of 3-tuples. I learned a lot about how maximal clique counts and degree interact (and had good fun)! But the graphs started getting pretty big. I like these examples a lot! :)

@rossbar rossbar changed the title Proposal: Consolidate could_be_isomorphic Consolidate could_be_isomorphic Mar 6, 2025

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks great! Very nice addition!

@dschult

dschult commented Mar 24, 2025

Copy link
Copy Markdown
Member

I'm going to merge this PR about could_be_isomorphic soon unless someone else posts something. We have 3 core devs who have taken a look at it. And I think 2 of us have taken a fairly deep dive in. :)

@eriknw

eriknw commented Mar 24, 2025

Copy link
Copy Markdown
Contributor

I'm going to merge this PR about could_be_isomorphic soon unless someone else posts something. We have 3 core devs who have taken a look at it. And I think 2 of us have taken a fairly deep dive in. :)

Sounds good. I'll take one more close look today.

@eriknw eriknw left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is nice, and I think it's very close!

I left a couple suggestions to consider and a question.

Stepping back, I think this function could handle directed graphs better. Notably, triangles and number of cliques don't work for directed graphs, so degrees is the only one that works, and the default could_be_isomorphic is likely to raise given directed graphs.
nx.cluster._directed_triangles_and_degree_iter could be useful for directed graphs. Checking in-degree and out-degree would also be better than simply checking total degree. Thoughts? This can also be considered an enhancement outside the scope of the current PR.

Comment on lines +72 to +73
G1_ptable = [tuple(p[n] for p in G1_props) for n in G1]
G2_ptable = [tuple(p[n] for p in G2_props) for n in G2]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does __getitem__ for all nodes for each property each time _properties_consistent is called, which may not be very efficient. Instead, we could compute p[n] at the time a property is added to e.g. G1_props. For example:

from operator import itemgetter

get_values1 = itemgetter(*G1)
get_values2 = itemgetter(*G2)

G1_props.append(get_values1(compute_property(G1)))
G2_props.append(get_values2(compute_property(G2)))

Then, G1_ptable can simply be G1_ptable = zip(*G1_props). I might take this one step further and optimize when there's one property such as:

G1_ptable = G1_props[0] if len(G1_props) == 1 else zip(*G1_props)

Also, using get_values1 could be skipped if we're confident that the property dict has the same iteration order as G1 (but it's probably not worth the risk of assuming).

@eriknw eriknw Mar 25, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, an even better data structure is probably defaultdict(list). Then you could do something like

G1_ptable = defaultdict(list)
prop1 = compute_property(G1)
for n, v in prop1.items():
    G1_ptable[n].append(v)

and compare via sorted(G1_ptable.values()) == sorted(G2_ptable.values()).

Alternatively, just set e.g. G1_ptable = {n: [] for n in G}.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The defaultdict(list) is a much better idea - will do!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went through the exercise of implementing using defaultdict(list) but in the end I'd like to stick with this implementation. The main reason is readability - see rossbar#15 for the comparison between the two implementations.

Anyways - for now I'd like to push off the discussion about a more efficient implementation to a separate PR if it's not a blocker for you @eriknw - LMK!

Comment on lines +104 to 105
# All checked conditions passed
return True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if no conditions were checked (so len(G1_props) == 0) other than checking number of nodes? Should we warn or raise?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question - it's a new corner-case given the flexibility of the properties kwarg.

My initial reaction is not to do any input validation. In other words, if users pass something different than the supported characters then they get the results of the len(G) == len(H) check.

If we did want input validation, we could check that the properties are a valid subset of the supported characters. Something like

if not set(properties).issubset("dtc"):
    raise ValueError("Properties must be a combination of the characters 'd', 't', and/or 'c'")

I have a slight preference for the former (i.e. the current status quo: garbage-in-garbage-out!) but don't feel strongly!

@rossbar
rossbar force-pushed the consolidate-could-be-isomorphic branch from 7ff8ee2 to 38204a9 Compare March 26, 2025 03:31
@dschult

dschult commented Mar 31, 2025

Copy link
Copy Markdown
Member

I think this is ready to be merged. All concerns have been responded to.
(I wish I had looked at this before I merged the nx-guides notebook so merging this could have allowed clean up of some parts in the notebook where it says we should change things once this PR is merged...)

:)

We can do more in follow-up PRs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Discussion Issues for discussion and decision making type: Enhancements

Development

Successfully merging this pull request may close these issues.

3 participants