gNODE: gLV model-informed neural ordinary differential equations for modeling microbial community dynamics.
Paper
Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
Python · 291 lines · 9.2 KB · GPL-3.0
- import argparse
- import os
- import random
- from concurrent.futures import ProcessPoolExecutor
- from copy import deepcopy
- import h5py
- import numpy as np
- import torch
- import torch.nn as nn
- import torch.optim as optim
- from sklearn.model_selection import KFold
- from torch.utils.data import DataLoader, Dataset
- from torchdiffeq import odeint
- learning_rate = 0.001
- num_epochs = 500
- device = torch.device("cpu")
- t3 = torch.tensor([0, 12, 24], dtype=torch.float32)
- t5 = torch.tensor([0, 6, 12, 18, 24], dtype=torch.float32)
- t10 = torch.tensor([0, 1, 2, 3, 7, 10, 12, 15, 18, 24], dtype=torch.float32)
- t15 = torch.tensor([0, 1, 2, 3, 4, 6, 7, 9, 11, 13, 15, 17, 19, 21, 24], dtype=torch.float32)
- t20 = torch.tensor(
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24],
- dtype=torch.float32,
- )
- t25 = torch.tensor(
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
- dtype=torch.float32,
- )
- timepoint_map = {
- "t3": t3,
- "t5": t5,
- "t10": t10,
- "t15": t15,
- "t20": t20,
- "t25": t25,
- }
- class CustomDataset(Dataset):
- def __init__(self, tensor):
- self.tensor = tensor
- def __len__(self):
- return len(self.tensor)
- def __getitem__(self, idx):
- input_data = self.tensor[idx, 0, :]
- output_data = self.tensor[idx, :, :]
- return input_data, output_data
- def loss_fn(pred_y, y):
- return torch.mean((y - pred_y) ** 2)
- class ODEFunc(nn.Module):
- def __init__(self, p_dim, run_device):
- super().__init__()
- self.p_dim = p_dim
- self.net = nn.Sequential(
- nn.Linear(p_dim, 2 * p_dim),
- nn.Tanh(),
- nn.Linear(2 * p_dim, p_dim),
- )
- for m in self.net.modules():
- if isinstance(m, nn.Linear):
- nn.init.normal_(m.weight, mean=0.0, std=0.1)
- nn.init.constant_(m.bias, val=0.0)
- def forward(self, t, y):
- indicator = (y > 0).int()
- return torch.mul(self.net(y), indicator)
- def set_seed(seed):
- torch.manual_seed(seed)
- if torch.cuda.is_available():
- torch.cuda.manual_seed_all(seed)
- np.random.seed(seed)
- random.seed(seed)
- torch.backends.cudnn.deterministic = True
- torch.backends.cudnn.benchmark = False
- def evaluate_full_validation_set(model, val_dataset, timepoints, run_device, output_dir, fold_idx):
- model.eval()
- predictions = []
- val_targets = []
- with torch.no_grad():
- for i in range(len(val_dataset)):
- val_input, val_output = val_dataset[i]
- val_input = val_input.to(run_device).float()
- val_output = val_output.to(run_device)
- pred_val_y = odeint(model, val_input.unsqueeze(0), timepoints)[:, 0, :] # [T, p]
- predictions.append(pred_val_y.cpu().numpy())
- val_targets.append(val_output.cpu().numpy())
- pred_val_y_file_path = os.path.join(
- output_dir, f"pred_val_y_fold_{fold_idx}_individual_{i}.txt"
- )
- np.savetxt(pred_val_y_file_path, pred_val_y.cpu().numpy(), fmt="%f")
- predictions = np.stack(predictions, axis=0)
- val_targets = np.stack(val_targets, axis=0)
- if predictions.shape != val_targets.shape:
- raise ValueError(
- f"Shape mismatch in validation: predictions {predictions.shape} vs targets {val_targets.shape}"
- )
- rmse = np.sqrt(np.mean((val_targets - predictions) ** 2))
- relative_rmse = rmse / np.sqrt(np.mean(val_targets ** 2))
- return relative_rmse
- def train_and_evaluate(train_data, val_data, run_device, batch_size, output_dir, fold_idx, timepoints, p_dim):
- set_seed(1)
- if not isinstance(train_data, torch.Tensor):
- train_data = torch.tensor(train_data, dtype=torch.float32)
- if not isinstance(val_data, torch.Tensor):
- val_data = torch.tensor(val_data, dtype=torch.float32)
- train_dataset = CustomDataset(train_data)
- val_dataset = CustomDataset(val_data)
- train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
- model = ODEFunc(p_dim, run_device).to(run_device)
- optimizer = optim.Adam(model.parameters(), lr=learning_rate)
- best_model = None
- best_loss = float("inf")
- loss_history = []
- avg_loss_file = os.path.join(output_dir, f"average_loss_fold_{fold_idx}.txt")
- with open(avg_loss_file, "w", encoding="utf-8") as file:
- file.write("")
- for epoch in range(num_epochs):
- epoch_losses = []
- for input_data, output_data in train_loader:
- input_data = input_data.to(run_device).float()
- output_data = output_data.to(run_device)
- optimizer.zero_grad()
- pred_y = odeint(model, input_data, timepoints)
- pred_y = pred_y.transpose(1, 0)
- loss = loss_fn(pred_y, output_data)
- loss.backward()
- optimizer.step()
- epoch_losses.append(loss.item())
- if loss.item() < best_loss:
- best_loss = deepcopy(loss.item())
- best_model = deepcopy(model.state_dict())
- avg_loss = np.mean(epoch_losses)
- with open(avg_loss_file, "a", encoding="utf-8") as file:
- file.write(f"Epoch [{epoch + 1}/{num_epochs}], Average Loss: {avg_loss:.4f}\n")
- loss_history.extend(epoch_losses)
- if best_model is None:
- raise RuntimeError(f"Fold {fold_idx}: best_model was never set.")
- model_path = os.path.join(output_dir, f"best_model_fold_{fold_idx}.pth")
- torch.save(best_model, model_path)
- loss_file_path = os.path.join(output_dir, f"loss_history_fold_{fold_idx}.txt")
- np.savetxt(loss_file_path, loss_history, fmt="%f")
- model.load_state_dict(best_model)
- relative_rmse = evaluate_full_validation_set(
- model, val_dataset, timepoints, run_device, output_dir, fold_idx
- )
- print(f"Fold {fold_idx} trained successfully.")
- return fold_idx, relative_rmse
- def k_fold_cross_validation(data, num_folds, run_device, batch_size, output_dir, timepoints, p_dim):
- kf = KFold(n_splits=num_folds, shuffle=True, random_state=1)
- rmses = [None] * num_folds
- with ProcessPoolExecutor(max_workers=5) as executor:
- futures = []
- for fold_idx, (train_index, val_index) in enumerate(kf.split(data)):
- train_data = data[train_index]
- val_data = data[val_index]
- futures.append(
- executor.submit(
- train_and_evaluate,
- train_data,
- val_data,
- run_device,
- batch_size,
- output_dir,
- fold_idx,
- timepoints,
- p_dim,
- )
- )
- for future in futures:
- fold_idx, relative_rmse = future.result()
- rmses[fold_idx] = relative_rmse
- rmses_file_path = os.path.join(output_dir, "k_fold_rrmses.txt")
- np.savetxt(rmses_file_path, rmses, fmt="%f")
- avg_rmse = np.mean(rmses)
- return avg_rmse
- def main():
- parser = argparse.ArgumentParser()
- parser.add_argument("--p", type=int, default=10)
- parser.add_argument("--sparsity_label", type=str, required=True)
- parser.add_argument("--s_label", type=str, required=True)
- parser.add_argument("--t_label", type=str, required=True)
- parser.add_argument("--input_root", type=str, required=True)
- parser.add_argument("--output_root", type=str, required=True)
- parser.add_argument("--iter_start", type=int, default=1)
- parser.add_argument("--iter_end", type=int, default=10)
- args = parser.parse_args()
- p_dim = args.p
- if args.t_label not in timepoint_map:
- raise ValueError(f"Unsupported t_label: {args.t_label}")
- timepoints = timepoint_map[args.t_label].to(device)
- for iter_num in range(args.iter_start, args.iter_end + 1):
- input_file_path = os.path.join(
- args.input_root, f"p{p_dim}", args.s_label, args.t_label, f"iter{iter_num}"
- )
- output_dir_path = os.path.join(
- args.output_root,
- f"p{p_dim}",
- "training",
- args.s_label,
- args.t_label,
- f"iter{iter_num}",
- )
- os.makedirs(output_dir_path, exist_ok=True)
- data_file = os.path.join(input_file_path, "true_initial_state.h5")
- if not os.path.exists(data_file):
- raise FileNotFoundError(f"Missing input file: {data_file}")
- with h5py.File(data_file, "r") as hdf:
- data = hdf["true_initial_state"][:]
- tensor_data = torch.tensor(data, dtype=torch.float32).permute(0, 2, 1)
- num_folds = 5
- batch_size = max(1, int(tensor_data.shape[0] * 0.2))
- avg_rmse = k_fold_cross_validation(
- tensor_data,
- num_folds,
- device,
- batch_size,
- output_dir_path,
- timepoints,
- p_dim,
- )
- print(
- f"sparsity={args.sparsity_label}, subject={args.s_label}, "
- f"time={args.t_label}, iter={iter_num}, "
- f"Average Relative RMSE: {avg_rmse:.4f}"
- )
- avg_rmse_file_path = os.path.join(output_dir_path, "average_relative_rmse.txt")
- with open(avg_rmse_file_path, "w", encoding="utf-8") as file:
- file.write(f"Average Relative RMSE: {avg_rmse:.4f}\n")
- if __name__ == "__main__":
- main()
NODE_cross_validation.py at commit 7a9e194, under GPL-3.0 · at the source
Overview
- Shanghai-MOST Key Laboratory of Health and Disease Genomics, Shanghai Institute for Biomedical and Pharmaceutical Technologies, Shanghai, China
- Department of Bioinformatics and Biostatistics, School of Life Sciences and Biotechnology, Shanghai Jiao Tong University, Shanghai, China
- Department of Statistics and MOE-LSC and CMA-Shanghai, School of Mathematical Sciences, Shanghai Jiao Tong University, Shanghai, China
- SJTU-Yale Joint Center for Biostatistics and Data Science, National Center for Translational Medicine, Shanghai Jiao Tong University, Shanghai, China
Abstract
Background: The human gut microbiota is a highly complex ecological system closely linked to host health, yet the functional mechanisms underlying its dynamic behavior remain poorly understood. Accurate modeling of microbial community dynamics is essential for elucidating these mechanisms. However, most existing approaches rely on densely sampled time-series data and often lack biological interpretability.
Methods: To address these challenges, we propose gNODE, a framework that integrates the generalized Lotka-Volterra (gLV) model with neural ordinary differential equations (NeuralODEs) to jointly predict microbial community dynamics, infer species interactions, and quantify the functional contributions of key taxa. By embedding ecological equations into a neural architecture, gNODE incorporates biological constraints directly into its model structure, enabling biologically meaningful parameter estimation and accurate inference even under sparse temporal sampling.
Results: Through simulations and real datasets, gNODE demonstrates superior performance in parameter estimation, trajectory prediction, and perturbation response modeling compared with existing methods. In a Clostridioides difficile infection dataset, gNODE accurately captured post-infection community trajectories and identified key inhibitory taxa, highlighting its potential to discover microbes that suppress pathogens. In a probiotic cocktail colonization dataset, gNODE identified diet-specific keystone species, underscoring its utility for assessing perturbation responses and guiding the design of probiotic consortia.
Conclusion: gNODE provides a robust and interpretable framework for modeling complex microbial community dynamics, offering new mechanistic and functional insights into the ecological processes that shape host-associated microbiomes.
Reproduced under the paper's license (CC BY), from the paper cited above.
Repository
Its files are read in the Code ↔ Paper reader above.
tanxiaoxiu/gNODE
7a9e19475f8391ad629284fea8dbffb794fea6b5, 30 April 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
9 files
- code/
NODE_cross_validation.py — Python, 291 lines - code/
gNODE_cross_validation.p — Python, 302 linesy - code/
pNODE_cross_validation.p — Python, 347 linesy - code/
train_NODE.py — Python, 186 lines - code/
train_gNODE.py — Python, 216 lines - code/
train_pNODE.py — Python, 229 lines - simulation/
generation_data/ — R, 225 linessimulation_data.R - LICENSE — License, 674 lines
- README.md — Text, 12 lines
The paper's code and data availability statement is in the Data section.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 7 scripts, each with its path and the digest of its content;
- no match between paragraphs and code yet;
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
No dataset and no data link were found in the paper.
Data availability statement
Publicly available datasets were analyzed in this study. We applied gNODE to two real datasets. The Clostridioides difficile infection dataset and the probiotic cocktail colonization dataset were obtained from publicly available data (Bucci et al., 2016). The data and source code used in this study are deposited in the GitHub repository, available at: https://
Reproduced under the paper's license (CC BY), from the paper cited above.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 2, 28 September 2026
- Funding: added National Natural Science Foundation of China: 12331009, 12571306; Shanghai Jiao Tong University: 24JS2840300; Fundamental Research Funds for the Central Universities
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, pages, dates, 4 authors, 5 keywords, 5 MeSH terms, 45 references.
Cite
This paper
Tan, X., Xue, F., Xie, L., & Wang, T. (2026). gNODE: gLV model-informed neural ordinary differential equations for modeling microbial community dynamics. Frontiers in cellular and infection microbiology, 16, 1785750. https://
BibTeX
@article{tan2026gnode,
author = {Tan, Xiaoxiu and Xue, Feng and Xie, Lu and Wang, Tao},
title = {{gNODE: gLV model-informed neural ordinary differential equations for modeling microbial community dynamics}},
journal = {Frontiers in cellular and infection microbiology},
year = {2026},
month = jul,
volume = {16},
pages = {1785750},
publisher = {Frontiers Media SA},
issn = {2235-2988},
doi = {10.3389/
url = {https://
pmid = {42518852},
pmcid = {PMC13381248}
}
RIS
TY - JOUR
AU - Tan, Xiaoxiu
AU - Xue, Feng
AU - Xie, Lu
AU - Wang, Tao
TI - gNODE: gLV model-informed neural ordinary differential equations for modeling microbial community dynamics
T2 - Frontiers in cellular and infection microbiology
J2 - Front Cell Infect Microbiol
PY - 2026
DA - 2026/
VL - 16
SP - 1785750
SN - 2235-2988
PB - Frontiers Media SA
DO - 10.3389/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.3389/
"type": "article-journal",
"title": "gNODE: gLV model-informed neural ordinary differential equations for modeling microbial community dynamics",
"container-title": "Frontiers in cellular and infection microbiology",
"author": [
{
"family": "Tan",
"given": "Xiaoxiu"
},
{
"family": "Xue",
"given": "Feng"
},
{
"family": "Xie",
"given": "Lu"
},
{
"family": "Wang",
"given": "Tao"
}
],
"container-title-short":
"volume": "16",
"page": "1785750",
"DOI": "10.3389/
"PMID": "42518852",
"PMCID": "PMC13381248",
"ISSN": "2235-2988",
"publisher": "Frontiers Media SA",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
6
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1126/sciadv.aee9425 [code]
- Probabilistic inference of homonymous and heteronymous recurrent inhibition in human muscles from large-scale motor neuron recordings.Journal: Science advancesIn common: h5py, PyTorch, tidyverse, 2 other tools
- [2] doi:10.1093/nar/gkag706 [code]
- scDifformer: diffusion-based post-training for virtual cell modeling across large-scale single-cell data.Journal: Nucleic acids researchIn common: h5py, PyTorch, tidyverse, 2 other tools
- [3] doi:10.1016/j.xcrm.2026.102904 [code]
- High-dose furmonertinib as first-line treatment for untreated EGFR-mutated advanced NSCLC with central nervous system metastases: A phase 2 trial.Journal: Cell reports. MedicineIn common: h5py, PyTorch, tidyverse, 2 other tools
- [4] doi:10.1038/s41467-026-73996-z [code]
- Genetic architecture of white matter microstructure captured by unsupervised deep representation learning of fractional anisotropy maps.Journal: Nature communicationsIn common: h5py, PyTorch, tidyverse, 2 other tools
- [5] doi:10.1371/journal.pcbi.1014327 [code]
- Supervised deep learning with gene functional annotation for cell classification.Journal: PLoS computational biologyIn common: h5py, PyTorch, tidyverse, 2 other tools
- [6] doi:10.1016/j.isci.2026.116055 [code]
- Mapping the transcriptional diversity of calcium signaling in the mouse and human brain.Journal: iScienceIn common: h5py, PyTorch, tidyverse, 2 other tools
- [7] doi:10.1371/journal.pcbi.1014364 [code]
- A comparative study of simulation-based inference methods for epidemic models with identifiability considerations.Journal: PLoS computational biologyIn common: h5py, PyTorch, scikit-learn, 1 other tool, computational modeling (no new data)
- [8] doi:10.1038/s41467-026-76939-w [code]
- HIPPIE: a generative model for electrophysiological analysis across species, technologies, and modalities.Journal: Nature communicationsIn common: h5py, PyTorch, tidyverse, 2 other tools
- [9] doi:10.21203/rs.3.rs-9676637/v1 [code]
- A Comprehensive Benchmarking of Spatial Deconvolution and Domain Detection Methods across Diverse Tissues and Spatial Transcriptomic TechnologiesJournal: Research Square (preprint)In common: h5py, PyTorch, tidyverse, 2 other tools
- [10] doi:10.1038/s42256-026-01254-4 [code]
- Neural sampling from cognitive maps enables goal-directed imagination and planning.Journal: Nature machine intelligenceIn common: h5py, PyTorch, scikit-learn, 1 other tool, computational modeling (no new data)
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 7 scripts, and 0 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:f6aade6539a385eb…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
Request its removal
To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).
Discussion, reproductions, activity
Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.
Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
