OSCR

gNODE: gLV model-informed neural ordinary differential equations for modeling microbial community dynamics.

Code ↔ Paper

The paper beside its authors' code: matches between them have not been computed for this paper yet.

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

  1. import argparse
  2. import os
  3. import random
  4. from concurrent.futures import ProcessPoolExecutor
  5. from copy import deepcopy
  6. import h5py
  7. import numpy as np
  8. import torch
  9. import torch.nn as nn
  10. import torch.optim as optim
  11. from sklearn.model_selection import KFold
  12. from torch.utils.data import DataLoader, Dataset
  13. from torchdiffeq import odeint
  14. learning_rate = 0.001
  15. num_epochs = 500
  16. device = torch.device("cpu")
  17. t3 = torch.tensor([0, 12, 24], dtype=torch.float32)
  18. t5 = torch.tensor([0, 6, 12, 18, 24], dtype=torch.float32)
  19. t10 = torch.tensor([0, 1, 2, 3, 7, 10, 12, 15, 18, 24], dtype=torch.float32)
  20. t15 = torch.tensor([0, 1, 2, 3, 4, 6, 7, 9, 11, 13, 15, 17, 19, 21, 24], dtype=torch.float32)
  21. t20 = torch.tensor(
  22. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24],
  23. dtype=torch.float32,
  24. )
  25. t25 = torch.tensor(
  26. [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],
  27. dtype=torch.float32,
  28. )
  29. timepoint_map = {
  30. "t3": t3,
  31. "t5": t5,
  32. "t10": t10,
  33. "t15": t15,
  34. "t20": t20,
  35. "t25": t25,
  36. }
  37. class CustomDataset(Dataset):
  38. def __init__(self, tensor):
  39. self.tensor = tensor
  40. def __len__(self):
  41. return len(self.tensor)
  42. def __getitem__(self, idx):
  43. input_data = self.tensor[idx, 0, :]
  44. output_data = self.tensor[idx, :, :]
  45. return input_data, output_data
  46. def loss_fn(pred_y, y):
  47. return torch.mean((y - pred_y) ** 2)
  48. class ODEFunc(nn.Module):
  49. def __init__(self, p_dim, run_device):
  50. super().__init__()
  51. self.p_dim = p_dim
  52. self.net = nn.Sequential(
  53. nn.Linear(p_dim, 2 * p_dim),
  54. nn.Tanh(),
  55. nn.Linear(2 * p_dim, p_dim),
  56. )
  57. for m in self.net.modules():
  58. if isinstance(m, nn.Linear):
  59. nn.init.normal_(m.weight, mean=0.0, std=0.1)
  60. nn.init.constant_(m.bias, val=0.0)
  61. def forward(self, t, y):
  62. indicator = (y > 0).int()
  63. return torch.mul(self.net(y), indicator)
  64. def set_seed(seed):
  65. torch.manual_seed(seed)
  66. if torch.cuda.is_available():
  67. torch.cuda.manual_seed_all(seed)
  68. np.random.seed(seed)
  69. random.seed(seed)
  70. torch.backends.cudnn.deterministic = True
  71. torch.backends.cudnn.benchmark = False
  72. def evaluate_full_validation_set(model, val_dataset, timepoints, run_device, output_dir, fold_idx):
  73. model.eval()
  74. predictions = []
  75. val_targets = []
  76. with torch.no_grad():
  77. for i in range(len(val_dataset)):
  78. val_input, val_output = val_dataset[i]
  79. val_input = val_input.to(run_device).float()
  80. val_output = val_output.to(run_device)
  81. pred_val_y = odeint(model, val_input.unsqueeze(0), timepoints)[:, 0, :] # [T, p]
  82. predictions.append(pred_val_y.cpu().numpy())
  83. val_targets.append(val_output.cpu().numpy())
  84. pred_val_y_file_path = os.path.join(
  85. output_dir, f"pred_val_y_fold_{fold_idx}_individual_{i}.txt"
  86. )
  87. np.savetxt(pred_val_y_file_path, pred_val_y.cpu().numpy(), fmt="%f")
  88. predictions = np.stack(predictions, axis=0)
  89. val_targets = np.stack(val_targets, axis=0)
  90. if predictions.shape != val_targets.shape:
  91. raise ValueError(
  92. f"Shape mismatch in validation: predictions {predictions.shape} vs targets {val_targets.shape}"
  93. )
  94. rmse = np.sqrt(np.mean((val_targets - predictions) ** 2))
  95. relative_rmse = rmse / np.sqrt(np.mean(val_targets ** 2))
  96. return relative_rmse
  97. def train_and_evaluate(train_data, val_data, run_device, batch_size, output_dir, fold_idx, timepoints, p_dim):
  98. set_seed(1)
  99. if not isinstance(train_data, torch.Tensor):
  100. train_data = torch.tensor(train_data, dtype=torch.float32)
  101. if not isinstance(val_data, torch.Tensor):
  102. val_data = torch.tensor(val_data, dtype=torch.float32)
  103. train_dataset = CustomDataset(train_data)
  104. val_dataset = CustomDataset(val_data)
  105. train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
  106. model = ODEFunc(p_dim, run_device).to(run_device)
  107. optimizer = optim.Adam(model.parameters(), lr=learning_rate)
  108. best_model = None
  109. best_loss = float("inf")
  110. loss_history = []
  111. avg_loss_file = os.path.join(output_dir, f"average_loss_fold_{fold_idx}.txt")
  112. with open(avg_loss_file, "w", encoding="utf-8") as file:
  113. file.write("")
  114. for epoch in range(num_epochs):
  115. epoch_losses = []
  116. for input_data, output_data in train_loader:
  117. input_data = input_data.to(run_device).float()
  118. output_data = output_data.to(run_device)
  119. optimizer.zero_grad()
  120. pred_y = odeint(model, input_data, timepoints)
  121. pred_y = pred_y.transpose(1, 0)
  122. loss = loss_fn(pred_y, output_data)
  123. loss.backward()
  124. optimizer.step()
  125. epoch_losses.append(loss.item())
  126. if loss.item() < best_loss:
  127. best_loss = deepcopy(loss.item())
  128. best_model = deepcopy(model.state_dict())
  129. avg_loss = np.mean(epoch_losses)
  130. with open(avg_loss_file, "a", encoding="utf-8") as file:
  131. file.write(f"Epoch [{epoch + 1}/{num_epochs}], Average Loss: {avg_loss:.4f}\n")
  132. loss_history.extend(epoch_losses)
  133. if best_model is None:
  134. raise RuntimeError(f"Fold {fold_idx}: best_model was never set.")
  135. model_path = os.path.join(output_dir, f"best_model_fold_{fold_idx}.pth")
  136. torch.save(best_model, model_path)
  137. loss_file_path = os.path.join(output_dir, f"loss_history_fold_{fold_idx}.txt")
  138. np.savetxt(loss_file_path, loss_history, fmt="%f")
  139. model.load_state_dict(best_model)
  140. relative_rmse = evaluate_full_validation_set(
  141. model, val_dataset, timepoints, run_device, output_dir, fold_idx
  142. )
  143. print(f"Fold {fold_idx} trained successfully.")
  144. return fold_idx, relative_rmse
  145. def k_fold_cross_validation(data, num_folds, run_device, batch_size, output_dir, timepoints, p_dim):
  146. kf = KFold(n_splits=num_folds, shuffle=True, random_state=1)
  147. rmses = [None] * num_folds
  148. with ProcessPoolExecutor(max_workers=5) as executor:
  149. futures = []
  150. for fold_idx, (train_index, val_index) in enumerate(kf.split(data)):
  151. train_data = data[train_index]
  152. val_data = data[val_index]
  153. futures.append(
  154. executor.submit(
  155. train_and_evaluate,
  156. train_data,
  157. val_data,
  158. run_device,
  159. batch_size,
  160. output_dir,
  161. fold_idx,
  162. timepoints,
  163. p_dim,
  164. )
  165. )
  166. for future in futures:
  167. fold_idx, relative_rmse = future.result()
  168. rmses[fold_idx] = relative_rmse
  169. rmses_file_path = os.path.join(output_dir, "k_fold_rrmses.txt")
  170. np.savetxt(rmses_file_path, rmses, fmt="%f")
  171. avg_rmse = np.mean(rmses)
  172. return avg_rmse
  173. def main():
  174. parser = argparse.ArgumentParser()
  175. parser.add_argument("--p", type=int, default=10)
  176. parser.add_argument("--sparsity_label", type=str, required=True)
  177. parser.add_argument("--s_label", type=str, required=True)
  178. parser.add_argument("--t_label", type=str, required=True)
  179. parser.add_argument("--input_root", type=str, required=True)
  180. parser.add_argument("--output_root", type=str, required=True)
  181. parser.add_argument("--iter_start", type=int, default=1)
  182. parser.add_argument("--iter_end", type=int, default=10)
  183. args = parser.parse_args()
  184. p_dim = args.p
  185. if args.t_label not in timepoint_map:
  186. raise ValueError(f"Unsupported t_label: {args.t_label}")
  187. timepoints = timepoint_map[args.t_label].to(device)
  188. for iter_num in range(args.iter_start, args.iter_end + 1):
  189. input_file_path = os.path.join(
  190. args.input_root, f"p{p_dim}", args.s_label, args.t_label, f"iter{iter_num}"
  191. )
  192. output_dir_path = os.path.join(
  193. args.output_root,
  194. f"p{p_dim}",
  195. "training",
  196. args.s_label,
  197. args.t_label,
  198. f"iter{iter_num}",
  199. )
  200. os.makedirs(output_dir_path, exist_ok=True)
  201. data_file = os.path.join(input_file_path, "true_initial_state.h5")
  202. if not os.path.exists(data_file):
  203. raise FileNotFoundError(f"Missing input file: {data_file}")
  204. with h5py.File(data_file, "r") as hdf:
  205. data = hdf["true_initial_state"][:]
  206. tensor_data = torch.tensor(data, dtype=torch.float32).permute(0, 2, 1)
  207. num_folds = 5
  208. batch_size = max(1, int(tensor_data.shape[0] * 0.2))
  209. avg_rmse = k_fold_cross_validation(
  210. tensor_data,
  211. num_folds,
  212. device,
  213. batch_size,
  214. output_dir_path,
  215. timepoints,
  216. p_dim,
  217. )
  218. print(
  219. f"sparsity={args.sparsity_label}, subject={args.s_label}, "
  220. f"time={args.t_label}, iter={iter_num}, "
  221. f"Average Relative RMSE: {avg_rmse:.4f}"
  222. )
  223. avg_rmse_file_path = os.path.join(output_dir_path, "average_relative_rmse.txt")
  224. with open(avg_rmse_file_path, "w", encoding="utf-8") as file:
  225. file.write(f"Average Relative RMSE: {avg_rmse:.4f}\n")
  226. if __name__ == "__main__":
  227. main()

NODE_cross_validation.py at commit 7a9e194, under GPL-3.0 · at the source

Overview

Authors: Xiaoxiu Tan1, Feng Xue2, Lu Xie1, Tao Wang2,3,4
ORCID iDs: Lu Xie
  1. Shanghai-MOST Key Laboratory of Health and Disease Genomics, Shanghai Institute for Biomedical and Pharmaceutical Technologies, Shanghai, China
  2. Department of Bioinformatics and Biostatistics, School of Life Sciences and Biotechnology, Shanghai Jiao Tong University, Shanghai, China
  3. Department of Statistics and MOE-LSC and CMA-Shanghai, School of Mathematical Sciences, Shanghai Jiao Tong University, Shanghai, China
  4. SJTU-Yale Joint Center for Biostatistics and Data Science, National Center for Translational Medicine, Shanghai Jiao Tong University, Shanghai, China
Institutions: Shanghai Jiao Tong University (China)
Journal: Frontiers in cellular and infection microbiology, volume 16, article 1785750
Dates: received 12 January 2026; accepted 18 May 2026; published online 6 July 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.3389/fcimb.2026.1785750 · PMID 42518852 · PMCID PMC13381248 · OpenAlex W7167483479
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: computational modeling (no new data) (modality), human (organism)
Methods: Statistics, Machine learning, Connectivity
Keywords: dynamic modeling, microbiome, ordinary differential equations, species interactions, time-series data
MeSH: Gastrointestinal Microbiome*, Microbiota*, Models, Biological*, Computer Simulation, Humans (* major topic)
Topic: Gut microbiota and health (Molecular Biology, Biochemistry, Genetics and Molecular Biology), according to OpenAlex
Funding: National Natural Science Foundation of China (12331009, 12571306); School of Medicine, Shanghai Jiao Tong University (24JS2840300); Fundamental Research Funds for the Central Universities
Citations: not cited yet (Europe PMC); 45 references in the paper

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

License: GPL-3.0
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 7a9e19475f8391ad629284fea8dbffb794fea6b5, 30 April 2026
Languages: Python (6), R (1)
Size: 46 files, 7 scripts
Software Heritage: not archived
Found in: “Data availability statement”
Holds: README, license file
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: h5py (6 files), NumPy (6 files), PyTorch (6 files), scikit-learn (3 files), tidyverse (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
9 files

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://github.com/tanxiaoxiu/gNODE.

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://doi.org/10.3389/fcimb.2026.1785750

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/fcimb.2026.1785750},
url = {https://doi.org/10.3389/fcimb.2026.1785750},
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/07/06
VL - 16
SP - 1785750
SN - 2235-2988
PB - Frontiers Media SA
DO - 10.3389/fcimb.2026.1785750
UR - https://doi.org/10.3389/fcimb.2026.1785750
LA - en
ER -

CSL-JSON

{
"id": "10.3389/fcimb.2026.1785750",
"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": "Front Cell Infect Microbiol",
"volume": "16",
"page": "1785750",
"DOI": "10.3389/fcimb.2026.1785750",
"PMID": "42518852",
"PMCID": "PMC13381248",
"ISSN": "2235-2988",
"publisher": "Frontiers Media SA",
"URL": "https://doi.org/10.3389/fcimb.2026.1785750",
"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 advances
In 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 research
In 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. Medicine
In 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 communications
In 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 biology
In 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: iScience
In 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 biology
In 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 communications
In 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 Technologies
Journal: 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 intelligence
In 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.

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.