Skip to content

Replace np.flatnonzero with np.nonzero()[0] for faster 1-D index retrieval #1

Description

@SaFE-APIOpt

RefiNA/mnc.py

Line 33 in 532dd7e

one_hop_neighbor = np.flatnonzero(a)

Current code:

a = np.array(adj1[i, :])
one_hop_neighbor = np.flatnonzero(a)

Proposed replacement:

a = np.array(adj1[i, :])
one_hop_neighbor = np.nonzero(a)[0]

np.flatnonzero(a) is essentially a convenience wrapper that calls np.nonzero(a) and then flattens the result with .ravel(). When a is already a 1-D array, this extra flattening step is unnecessary. In contrast, np.nonzero(a)[0] directly returns the non-zero indices for the 1-D case, making it more efficient. Benchmarks confirm that np.nonzero(a)[0] runs faster while producing exactly the same output as np.flatnonzero(a) in this context.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions