dirac.adj

class sodirac.adj.graph(data: numpy.ndarray, rad_cutoff: float, k: int, distType: str = 'euclidean')[source]

Bases: object

Graph builder over points (e.g., spatial coordinates or embeddings).

Parameters:
  • data (np.ndarray) – Shape [N, d]. Coordinates or feature vectors used for neighbor search.

  • rad_cutoff (float) – Radius cutoff used when distType == “Radius”.

  • k (int) – Number of neighbors used by kNN-style methods.

  • distType (str, default "euclidean") – Graph type / distance metric. Supported options include: - “spearmanr”: top-k by Spearman correlation. - “BallTree”: sklearn BallTree kNN. - “KDTree”: sklearn KDTree kNN. - “kneighbors_graph”: sklearn kneighbors_graph connectivity. - “Radius”: sklearn NearestNeighbors with radius. - Any metric listed in SciPy cdist (see below in graph_computing).

data

Input data.

Type:

np.ndarray

distType

Distance or method type.

Type:

str

k

kNN count.

Type:

int

rad_cutoff

Radius cutoff for “Radius” mode.

Type:

float

num_cell

Number of nodes (N).

Type:

int

Notes

Class name intentionally kept as graph (lowercase) to preserve external interface compatibility.

__init__(data: numpy.ndarray, rad_cutoff: float, k: int, distType: str = 'euclidean') None[source]
graph_computing() List[Tuple[int, int]][source]

Build an edge list according to the selected method/metric.

Parameters:

attributes). (None (uses constructor) –

Returns:

  • graphList (List[Tuple[int, int]])

  • Directed edges (i, j) produced by the chosen neighbor rule.

Notes

Supported distType values:

  • “spearmanr”: Uses Spearman correlation across rows of self.data (axis=1), then selects top-(k+1) indices per node and adds k edges.

  • “BallTree”: Uses sklearn.neighbors.BallTree with k+1 query (self + k).

  • “KDTree”: Uses sklearn.neighbors.KDTree with k+1 query (self + k).

  • “kneighbors_graph”: Uses sklearn.neighbors.kneighbors_graph in connectivity mode, no self-loops.

  • “Radius”: Uses sklearn.neighbors.NearestNeighbors(radius=rad_cutoff), excludes zero distances (self).

  • Any metric in the following SciPy list will trigger an on-the-fly cdist-based neighbor selection with a simple cutoff heuristic (boundary = mean + std of the top-k distances from each node): [“euclidean”,”braycurtis”,”canberra”,”mahalanobis”,”chebyshev”,”cosine”,

    “jensenshannon”,”mahalanobis”,”minkowski”,”seuclidean”,”sqeuclidean”, “hamming”,”jaccard”,”jensenshannon”,”kulsinski”,”mahalanobis”,”matching”, “minkowski”,”rogerstanimoto”,”russellrao”,”seuclidean”,”sokalmichener”, “sokalsneath”,”sqeuclidean”,”wminkowski”,”yule”]

Raises:

ValueError – If distType is not supported.

List2Dict(graphList: List[Tuple[int, int]]) Dict[int, List[int]][source]

Convert an edge list into an adjacency list dictionary.

Parameters:

graphList (List[Tuple[int, int]]) – Directed edges (i, j).

Returns:

graphdict – Adjacency list, mapping node -> list of out-neighbors.

Return type:

Dict[int, List[int]]

Notes

Ensures all nodes [0, num_cell) appear as keys, including those with no neighbors (empty lists).

mx2SparseTensor(mx: scipy.sparse.spmatrix) torch_sparse.SparseTensor[source]

Convert a SciPy sparse matrix to a torch SparseTensor.

Parameters:

mx (sp.spmatrix) – Input matrix (will be converted to COO, float32).

Returns:

adj_t – Transposed sparse tensor (as returned by .t() in the original code).

Return type:

SparseTensor

Notes

Keeps values as float32. Matches original transpose behavior.

pre_graph(adj: scipy.sparse.spmatrix) torch_sparse.SparseTensor[source]

Preprocess an adjacency matrix with symmetric normalization.

Parameters:

adj (sp.spmatrix) – Sparse adjacency (no self loops).

Returns:

adj_norm – Normalized adjacency as a SparseTensor.

Return type:

SparseTensor

Notes

Applies A_hat = D^{-1/2} (A + I) D^{-1/2}.

main() Dict[str, Any][source]

Build graph, preprocess adjacency, and package tensors for downstream use.

Parameters:

None

Returns:

graph_dict

{

“adj_norm”: SparseTensor, # normalized adjacency (SparseTensor) “adj_label”: torch.FloatTensor, # adjacency with self-loops (dense FloatTensor) “norm_value”: float # scalar normalization factor (as in original)

}

Return type:

Dict[str, Any]

Notes

  • Uses NetworkX to convert adjacency list to a SciPy adjacency matrix.

  • adj_label = A (no self-loop) + I.

  • The norm_value follows the exact original expression.

sodirac.adj.combine_graph_dict(dict_1: Dict[str, Any], dict_2: Dict[str, Any]) Dict[str, Any][source]

Block-diagonally combine two graph dictionaries returned by graph.main().

Parameters:
  • dict_1 (Dict[str, Any]) – First graph dict with keys: “adj_norm” (SparseTensor), “adj_label” (FloatTensor), “norm_value” (float).

  • dict_2 (Dict[str, Any]) – Second graph dict, same schema as dict_1.

Returns:

graph_dict – Combined graph dict with: - “adj_norm”: SparseTensor (block-diagonal of the dense forms, then re-sparsified) - “adj_label”: torch.FloatTensor (block-diagonal) - “norm_value”: float (mean of the two input `norm_value`s)

Return type:

Dict[str, Any]

Notes

Converts adj_norm to dense for block-diagonal composition, then back to SparseTensor to match the original behavior.