TGraphX for Scientific Data: Graph Learning in Biology and Materials Science
Graph-structured data appears naturally in biology and materials science. Protein interaction networks, molecular graphs, brain connectomes, crystal lattices and phylogenetic trees are all graphs. The question for a researcher in these fields is not whether to use graphs, but which graph learning tools fit the structure of their data.
TGraphX's tensor-native design addresses one particular case: graph elements that carry multi-dimensional features, such as volumetric density maps or image-derived node representations, where you want message passing that keeps that layout. This article explains where TGraphX applies in biology and materials science, and where you should use other tools.
The code examples use random placeholder data to show shapes and API calls, not scientific results. Examples tested with TGraphX 1.5.1.
Graph Structures in Biology
Protein-protein interaction networks (PPINs). Each node is a protein; edges are physical interactions or functional associations. Node features can be amino acid composition vectors, structural descriptors or embeddings from protein language models. Vector features [N, D] work with vector layers such as GCNConv. If node features are 3D density maps [N, C, D, H, W], TGraphX's tensor layers (TensorGraphSAGELayer, TensorGATLayer, TensorGINLayer with spatial_rank=3) and ConvMessagePassing can pass messages over them.
Metabolic and signaling networks. Pathway graphs with enzyme or metabolite nodes. Node features can be kinetic parameters, expression levels or functional annotations.
Brain connectomes. Structural connectivity between brain regions, often derived from diffusion MRI tractography. Edge features are usually tract-level summaries, such as streamline counts or mean fractional anisotropy along a tract (the diffusion tensor itself is a per-voxel quantity). Node features can be regional morphometry or fMRI activation patterns.
Single-cell RNA sequencing (scRNA-seq) graphs. Cell-cell similarity graphs where each node is a cell with a gene expression profile [N, num_genes]. Graphs are often built with k-nearest neighbors on a low-dimensional embedding (tgraphx.build_knn_graph returns such an edge index).
Phylogenetic trees. Hierarchical graphs where node features encode traits. A tree is a special graph, so the general graph representation holds it.
Graph Structures in Materials Science
Crystal graphs. Atoms are nodes and neighbor relations are edges. Node features describe the element; edge features often encode interatomic distance. Bond angles involve three atoms, so they do not belong to a single edge; some models add them through a line graph. This is the domain of models such as CGCNN and MEGNet.
Periodic lattices. Periodic boundary conditions require edges to periodic images of atoms. TGraphX does not handle periodicity: you must build those edges externally.
Molecular property prediction. Molecular graphs, for example from SMILES, with atom features on nodes and bond features on edges. MPNN-style models typically pass messages over the bond graph (some variants add distances or all atom pairs). SchNet and DimeNet instead build their graph from 3D atomic positions with a distance cutoff and do not use bond types.
Amorphous materials. Graphs built from atomic positions with a distance cutoff. tgraphx.build_radius_graph does this for non-periodic coordinates.
By default, tgraphx.build_radius_graph and tgraphx.build_knn_graph include self-loops and return both directions of each edge. Pass self_loops=False when your layer adds its own (as GCNConv does) or when you compute network statistics. Before degree_statistics or graph_summary, also keep one direction only, for example edge_index[:, edge_index[0] < edge_index[1]].
When TGraphX's Tensor Features Apply
TGraphX is most relevant when node or edge features have spatial or volumetric structure that flattening would discard.
Example: image-like activation maps as node features
Suppose each brain region is summarized by T activation maps of size H × W, giving a node feature of shape [T, H, W]. ConvMessagePassing can treat the time steps as channels:
import torch
from tgraphx import Graph, ConvMessagePassing
from tgraphx.reproducibility import set_seed
set_seed(42)
# 90 brain regions, each with T=20 activation maps of size 16 x 16 (placeholder data)
N_regions = 90
T, H, W = 20, 16, 16
x = torch.randn(N_regions, T, H, W) # [N, C, H, W] with C = T
# Structural connections are undirected: list each pair once, then add the reverse
pairs = torch.randint(0, N_regions, (2, 150))
pairs = pairs[:, pairs[0] != pairs[1]]
edge_index = torch.cat([pairs, pairs.flip(0)], dim=1)
g = Graph(node_features=x, edge_index=edge_index)
layer = ConvMessagePassing(in_shape=(T, H, W), out_shape=(32, H, W), dropout_prob=0.0)
out = layer(g.node_features, g.edge_index)
print(out.shape) # torch.Size([90, 32, 16, 16])
Be clear about what this does: the convolutions mix time steps as unordered channels and mix pixels spatially. It does not model temporal order the way a sequence model would, and it only makes sense if the H × W layout is a meaningful grid.
Example: molecular graph with bond features
Atom features here are vectors. TensorGINLayer expects [N, C, H, W], so add two unit axes; it accepts vector edge features [E, edge_dim] when constructed with edge_features_kind="vector":
from tgraphx import TensorGINLayer
N_atoms, D, N_bonds, bond_dim = 23, 64, 25, 16
atoms = torch.randn(N_atoms, D) # per-atom features (placeholder)
bonds = torch.randint(0, N_atoms, (2, N_bonds)) # random pairs, not a real molecule
bond_features = torch.randn(N_bonds, bond_dim) # e.g. bond type, length, ring flags
edge_index = torch.cat([bonds, bonds.flip(0)], dim=1) # both directions
edge_features = torch.cat([bond_features, bond_features], 0) # same features each way
gin = TensorGINLayer(D, 128, use_edge_features=True, edge_dim=bond_dim,
edge_features_kind="vector")
atom_out = gin(atoms[:, :, None, None], edge_index, edge_features=edge_features).flatten(1)
print(atom_out.shape) # torch.Size([23, 128])
# the bond features are really used: changing them changes the output
other = gin(atoms[:, :, None, None], edge_index, edge_features=edge_features * 0).flatten(1)
print(torch.allclose(atom_out, other)) # False
If you do not need bond features, GCNConv(in_dim, out_dim) works on [N, D] directly and ignores them.
Knowledge Graphs in Biology
Biological knowledge graphs connect entities of several types: genes, proteins, diseases, drugs, pathways, phenotypes. tgraphx.kg provides embedding models over (head, relation, tail) triples:
from tgraphx.kg import KnowledgeGraph, TransEModel, KGTrainer, KGTrainingConfig
# Entities: 0-99 genes, 100-149 proteins, 150-199 diseases
triples = torch.tensor([
[0, 0, 100], # gene_0 --encodes--> protein_100
[100, 1, 150], # protein_100 --associated_with--> disease_150
[0, 2, 150], # gene_0 --linked_to--> disease_150
])
kg = KnowledgeGraph(triples, num_entities=200, num_relations=3)
model = TransEModel(num_entities=kg.num_entities, num_relations=kg.num_relations,
embedding_dim=64)
config = KGTrainingConfig(num_epochs=50, lr=1e-3, seed=42)
history = KGTrainer(model, config, kg.triples).train()
print(round(history["final_loss"], 3))
Three triples only show the calls; they cannot be evaluated. For entity types with different features, MultimodalKGModel projects each feature type into a shared space, with masks saying which entities have it:
from tgraphx.kg import MultimodalKGModel, VectorEntityProjector
n = kg.num_entities
is_gene = torch.arange(n) < 100
is_protein = (torch.arange(n) >= 100) & (torch.arange(n) < 150)
sequence = torch.zeros(n, 32)
sequence[is_gene] = torch.randn(int(is_gene.sum()), 32) # e.g. sequence embeddings
structure = torch.zeros(n, 16)
structure[is_protein] = torch.randn(int(is_protein.sum()), 16) # e.g. structural descriptors
mm = MultimodalKGModel(n, kg.num_relations, out_dim=64, projectors={
"sequence": VectorEntityProjector(32, 64),
"structure": VectorEntityProjector(16, 64),
})
entity_emb = mm.encode_entities({"sequence": sequence, "structure": structure},
{"sequence": is_gene, "structure": is_protein})
print(mm.score_triples(kg.triples, entity_emb).shape) # torch.Size([3])
MultimodalKGModel scores with DistMult, which is symmetric in head and tail. For directed relations such as "encodes", that is a real limitation to consider. This block only runs a forward pass; training it is up to you. See the knowledge graph with tensor features tutorial.
Graph Mining for Biological Network Analysis
Before training a GNN on a biological network, look at its structure. List each undirected interaction once: the degree statistics count every listed edge, so listing both directions doubles the reported degrees.
from tgraphx.mining import graph_summary, degree_statistics, local_clustering_coefficient
# Placeholder PPI network: random pairs, de-duplicated, one row order per pair
pairs = torch.randint(0, 200, (2, 1000))
pairs = pairs[:, pairs[0] != pairs[1]]
ppi = torch.unique(pairs.sort(dim=0).values, dim=1)
summary = graph_summary(ppi, num_nodes=200, directed=False)
degrees = degree_statistics(ppi, num_nodes=200, directed=False)
clustering = local_clustering_coefficient(ppi, num_nodes=200) # one value per node
print("Density:", round(summary["density"], 4))
print("Connected components:", summary["num_connected_components"])
print("Mean degree:", degrees["mean_degree"], "Max:", degrees["max_degree"])
print("Mean clustering coefficient:", round(clustering.mean().item(), 4))
These numbers are meaningful only relative to a reference. Compare clustering and path lengths with a random graph of the same size and density: much higher clustering with similarly short paths is the small-world pattern described by Watts and Strogatz (1998), whose examples included the neural network of C. elegans. The mining functions are small pure PyTorch and Python implementations. For large networks, use igraph or cuGraph (GPU), or NetworkX with an accelerated backend such as nx-cugraph. Plain NetworkX is a broad general-purpose analysis library, but it is itself largely pure Python.
What TGraphX Does Not Cover for Scientific Applications
Periodic boundary conditions. Crystal graphs need edges across unit cell boundaries, which you must construct yourself.
Molecular featurization. TGraphX has no SMILES parser or atom featurizer. RDKit does this; PyTorch Geometric has torch_geometric.utils.from_smiles (which uses RDKit), and DeepChem offers featurizers.
Geometry-aware molecular architectures. TGraphX does not implement SchNet, DimeNet or PaiNN. PyTorch Geometric provides SchNet and DimeNet; SchNetPack provides PaiNN.
Protein structure models. Models such as GVP-GNN (geometric vector features) or ProteinMPNN are not in TGraphX.
Biological databases. There are no loaders for STRING, BioGRID or KEGG. The dataset registry does include optional adapters for some benchmark datasets, such as ogb:ogbg-molhiv and pyg:tudataset/proteins, which need OGB or PyTorch Geometric and download data.
Domain benchmarks. TGraphX makes no performance claims on biological or materials benchmarks. See TGraphX benchmark disclaimers.
Whatever library you use, split with the science in mind. Random splits of molecules or proteins can place near-duplicates in both training and test; scaffold splits or sequence-identity-based splits test generalization more honestly.
When to Use Domain-Specific Libraries Instead
| Use case | Consider |
|---|---|
| Molecular property prediction from SMILES | PyTorch Geometric, DeepChem |
| Protein structure prediction | AlphaFold, ESMFold |
| Geometry-aware molecular models | SchNet or DimeNet in PyTorch Geometric, SchNetPack |
| Crystal graph learning with periodic boundaries | CGCNN, MatGL |
| Large-scale biological knowledge graphs | PyKEEN, mOWL |
| General biological network analysis | NetworkX |
| Biological network analysis at scale | igraph, cuGraph, NetworkX with the nx-cugraph backend |
TGraphX is most useful in these fields when you have custom tensor-valued node or edge features that you want to process with message passing, and want its mining, reproducibility and reporting utilities in the same project.
Further Reading
- What is a TGX graph: the core data model
- Tensor-valued nodes in GNNs: why multi-dimensional features matter
- Knowledge graph embedding with tensor features: for biological knowledge graphs
- Graph mining vs GNN message passing: when to use each approach
- GNN research reproducibility: making GNN experiments reproducible
- Structured annotation for graph and vision research: annotation practices for graph datasets