BraMARS: An Interpretable Histopathology-Driven Deep Learning Model for Brain Metastasis Risk Stratification in Surgically Resected Limited-Stage SCLC.
The 3 matches
- [1] § Materials and Methods › Implementation Details ↔ train.py, lines 144–267 · score 0.90 · cosine annealing, AdamW, BCEWithLogitsLoss, weight decay, schedule, optimization
- [2] § Results › Performance of BraMARS for BM Risk Prediction ↔ train.py, lines 144–267 · score 0.62 · internal validation, external validation, AUC, trained, curve, threshold
- [3] § Materials and Methods › Feature Encoding With S4 ↔ S4MIL.py, lines 94–142 · score 0.59 · state space, FFT, convolutions, Kernel, S4D, SSM
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 · 284 lines · 12 KB · no license · 2 matches
- import torch
- import sys
- import numpy as np
- import os
- import pandas as pd
- from datasets import FeatureDataset
- from torch.optim.lr_scheduler import CosineAnnealingLR
- import warnings
- import random
- from torch.utils.data import DataLoader
- from torch import nn
- from pathlib import Path
- from tqdm import tqdm
- from warmup_scheduler import GradualWarmupScheduler
- import torch.backends.cudnn as cudnn
- from sklearn.metrics import roc_auc_score, roc_curve
- import argparse
- from sklearn.model_selection import StratifiedKFold
- from lifelines.statistics import multivariate_logrank_test
- from lifelines import CoxPHFitter
- import lifelines
- from S4MIL import S4Model
- warnings.filterwarnings("ignore")
- os.environ['CUDA_VISIBLE_DEVICES'] = '0'
- def calculate_acc(data_loader):
- pred_list = data_loader['PREDS'].tolist()
- label_list = data_loader['LABELS'].tolist()
- acc = 0
- for idx_ in range(len(pred_list)):
- if pred_list[idx_] == label_list[idx_]:
- acc += 1
- acc = acc / len(pred_list)
- return acc
- def setup_seed(seed):
- torch.manual_seed(seed)
- os.environ['PYTHONHASHSEED'] = str(seed)
- torch.cuda.manual_seed_all(seed)
- torch.cuda.manual_seed(seed)
- np.random.seed(seed)
- random.seed(seed)
- cudnn.deterministic = True
- cudnn.benchmark = False
- cudnn.enabled = False
- def get_args(lr, wd):
- parser = argparse.ArgumentParser(description='BM invasion prediction')
- parser.add_argument('--workers', default=4, type=int, metavar='N',
- help='number of data loader workers')
- parser.add_argument('--epochs', default=200, type=int, metavar='N',
- help='number of total epochs to run')
- parser.add_argument('--batch_size', default=64, type=int, metavar='N',
- help='mini-batch size')
- parser.add_argument('--checkpoint-dir', default='', type=Path,
- metavar='DIR', help='path to checkpoint directory')
- parser.add_argument('--lr', default=lr)
- parser.add_argument('--wd', default=wd)
- parser.add_argument('--T_max', default=10)
- args = parser.parse_args()
- return args
- def calculate_metrics(model, data_loader, thresholds):
- with torch.no_grad():
- sigmoid = nn.Sigmoid()
- data = pd.DataFrame()
- model.eval()
- score = np.array([])
- label = []
- slides = []
- for step, (slide, slide_property) in enumerate(data_loader):
- slide = slide.cuda()
- slides = slides + slide_property['slide_name']
- pred_ = model(slide)
- score = np.append(score, (sigmoid(pred_).detach().cpu().numpy()))
- label = label + list(slide_property['label'].detach().cpu().numpy())
- auc = roc_auc_score(label, score)
- dfs_ = []
- os_ = []
- dfs_state = []
- os_tate = []
- for ik in slides:
- dfs_.append(dfs_os[ik]['DFS'])
- os_.append(dfs_os[ik]['OS'])
- dfs_state.append(dfs_os[ik]['DFS State'])
- os_tate.append(dfs_os[ik]['OS State'])
- preds = (score > thresholds).astype(float)
- Surival_Data = pd.DataFrame()
- Surival_Data['DFS'] = dfs_
- Surival_Data['Label'] = preds
- Surival_Data['DFS State'] = dfs_state
- Surival_Data['OS'] = os_
- Surival_Data['OS State'] = os_tate
- ##
- result0 = multivariate_logrank_test(Surival_Data['DFS'], Surival_Data['Label'], Surival_Data['DFS State'])
- logrank_p0_2ways = result0.p_value
- Surival_Data_High_Lows = Surival_Data.dropna(axis=0)
- try:
- cph = CoxPHFitter()
- cph.fit(Surival_Data_High_Lows[['DFS', 'DFS State', 'Label']], 'DFS', event_col='DFS State')
- except lifelines.exceptions.ConvergenceError:
- hr_values = 100
- data['SLIDES'] = list(slides)
- data['LABELS'] = list(label)
- data['SCORES'] = list(score)
- data['PREDS'] = list(preds)
- return auc, data, logrank_p0_2ways
- def collatte_fn(batch):
- max_len = max(len(features) for features, slide in batch)
- batch_features = []
- batch_labels = []
- batch_name = []
- for features, slide in batch:
- padded_features = torch.zeros((max_len, 768), dtype=torch.float32)
- padded_features[:len(features), :] = features
- name = slide['slide_name']
- label = slide['label']
- batch_features.append(padded_features)
- batch_labels.append(label)
- batch_name.append(name)
- batch_features = torch.stack(batch_features)
- slide_property = {}
- slide_property['slide_name'] = batch_name
- slide_property['label'] = torch.tensor(batch_labels)
- return batch_features, slide_property
- def train(lr, wd, warmup, seed):
- args = get_args(lr, wd)
- seed = seed
- setup_seed(seed)
- args.checkpoint_dir.mkdir(parents=True, exist_ok=True)
- '''读取数据集路径和构建dataloader'''
- # External validation set
- External_val_root = '' # External_val特征存放地址
- External_val_csv = pd.read_csv('') # 需要用到的External_val患者数据
- External_val_path = []
- External_val_label_path = []
- for i in range(len(External_val_csv)):
- External_val_path.append(External_val_root + str(External_val_csv['Name'][i]))
- External_val_label_path.append(External_val_csv['Label'][i])
- data_External_val = FeatureDataset(External_val_path, External_val_label_path, mode='test')
- data_External_val_loader = DataLoader(data_External_val, batch_size=1, shuffle=True, collate_fn=collatte_fn)
- # Train set and Internal validation set
- label_csv = pd.read_csv('') # 需要用到的Train_set患者数据
- root = '' # Train_set特征存放地址
- list_train_path = []
- label_train = []
- for i in range(len(label_csv)):
- list_train_path.append(root + str(label_csv['Name'][i]))
- label_train.append(label_csv['Label'][i])
- setup_seed(seed)
- skf = StratifiedKFold(n_splits=3, shuffle=True, random_state=seed)
- a, b, c = enumerate(skf.split(list_train_path, label_train))
- train_idx, val_idx = b[1][0], b[1][1]
- setup_seed(seed)
- fold_train, fold_val = [list_train_path[i] for i in train_idx], [list_train_path[i] for i in val_idx]
- fold_train_label, fold_val_label = [label_train[i] for i in train_idx], [label_train[i] for i in val_idx]
- model = S4Model(in_dim=768, n_classes=1, act='gelu', dropout=0).cuda()
- l_bce = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([6]).cuda())
- optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wd)
- scheduler = CosineAnnealingLR(optimizer, T_max=args.epochs - warmup)
- scheduler = GradualWarmupScheduler(optimizer, multiplier=1, total_epoch=warmup, after_scheduler=scheduler)
- data_train = FeatureDataset(fold_train, fold_train_label, mode='train')
- data_train_loader = torch.utils.data.DataLoader(data_train, batch_size=1, shuffle=True, collate_fn=collatte_fn)
- data_validation = FeatureDataset(fold_val, fold_val_label, mode='val')
- data_validation_loader = torch.utils.data.DataLoader(data_validation, batch_size=1, shuffle=False,
- collate_fn=collatte_fn)
- early_stop = 0
- auc_validation = 0
- epoch_validation = 0
- m = t = 0
- for epoch in range(args.epochs):
- early_stop = early_stop + 1
- if early_stop > 20:
- print('Early stop!')
- break
- LOSS = []
- score_ = np.array([])
- LABEL_ = []
- model.train()
- progress_bar = tqdm(total=len(data_train_loader), desc=" BM_invasion training")
- for step, (slide, slide_property) in enumerate(data_train_loader, start=epoch * len(data_train_loader)):
- optimizer.zero_grad()
- slide = slide.cuda()
- label = slide_property['label'].cuda().to(torch.float64)
- pred = model(slide)
- pred = pred.reshape(-1)
- sigmoid = nn.Sigmoid()
- score_ = np.append(score_, (sigmoid(pred).detach().cpu().numpy()))
- LABEL_ = LABEL_ + list(slide_property['label'].detach().cpu().numpy())
- loss1 = l_bce(pred, label)
- loss = loss1
- loss.backward()
- LOSS.append(loss.item())
- optimizer.step()
- progress_bar.update()
- progress_bar.close()
- train_auc = roc_auc_score(LABEL_, score_)
- fpr, tpr, thresholds = roc_curve(LABEL_, score_)
- for idx in range(len(thresholds)):
- if tpr[idx] - fpr[idx] > m:
- m = abs(-fpr[idx] + tpr[idx])
- t = thresholds[idx]
- print(f'thresholds:{t}')
- train_acc_list = (score_ > t).astype(float)
- acc_sum = 0
- for q in range(len(train_acc_list)):
- if train_acc_list[q] == LABEL_[q]:
- acc_sum += 1
- train_acc = acc_sum / len(train_acc_list)
- auc_validation_, data_validation, p_value = calculate_metrics(model, data_validation_loader, t)
- if auc_validation_ > auc_validation:
- auc_validation = auc_validation_
- epoch_validation = epoch
- early_stop = 0
- state = dict(epoch=epoch + 1, model=model.state_dict(), optimizer=optimizer.state_dict(), threshold=t)
- torch.save(state, args.checkpoint_dir / 'checkpoint_max_validation_auc.pth')
- data_validation.to_csv(args.checkpoint_dir / 'temp_report_validation.csv')
- print('Epoch: ' + str(epoch) + ' loss: ' + str(np.mean(LOSS)))
- print(f'Epoch: {epoch} train AUC: {train_auc} train ACC: {train_acc}')
- print(f'Epoch: {epoch} validation AUC: {auc_validation_} validation P: {p_value}')
- print(f'Current best validation AUC: {auc_validation} at epoch {epoch_validation}')
- auc_External_val, data_External_val, p_External_val = calculate_metrics(model, data_External_val_loader, t)
- print(f'Epoch: {epoch}, External_val AUC: {auc_External_val}, External_val P: {p_External_val}')
- print('-------------------------------------------------------------------------------------------')
- scheduler.step()
- model = S4Model(in_dim=768, n_classes=1, act='gelu', dropout=0).cuda()
- ckpt = torch.load(args.checkpoint_dir / f'checkpoint_max_validation_auc.pth', map_location='cuda:0')
- model.load_state_dict(ckpt['model'])
- auc_validation, data_validation, p_validation = calculate_metrics(model, data_validation_loader, ckpt['threshold'])
- auc_External_val, data_External_val, p_External_val = calculate_metrics(model, data_External_val_loader,
- ckpt['threshold'])
- th = ckpt['threshold']
- print(f'Epoch: {epoch} Validation AUC: {auc_validation}, External_val AUC: {auc_External_val}, threshold: {th}')
- data_validation.to_csv(args.checkpoint_dir / f'seed={seed}/temp_report_validation.csv')
- data_External_val.to_csv(args.checkpoint_dir / f'seed={seed}/temp_report_External_val.csv')
- print('Finish!')
- if __name__ == '__main__':
- survival = pd.read_csv('') # 患者临床信息
- dfs_os = {}
- for i in range(survival.shape[0]):
- row_data = survival.loc[i]
- dfs_os[str(row_data['Name'])] = row_data
- lrs = 1e-5
- wds = 1e-4
- warmups = 40
- seeds = 9197
- sys.stdout = open('log_root', 'w') # 日志存放地址
- print(f'lr {lrs}, wd {wds} , warmup {warmups} , seed {seeds} begin')
- train(lrs, wds, warmups, seeds)
- sys.stdout.close()
train.py at commit 14fc0c7, no license · at the source
Overview
- Institute of Genomic Medicine School of Biomedical Engineering Wenzhou Medical University Wenzhou People's Republic of China
- Department of Thoracic Radiation Oncology Harbin Medical University Cancer Hospital Harbin People's Republic of China
- Department of Pathology National Cancer Center/National Clinical Research Center for Cancer/Cancer Hospital Chinese Academy of Medical Sciences and Peking Union Medical College Beijing People's Republic of China
- AMG Nephrology Avera McKennan Hospital Sioux Falls South Dakota USA
Abstract
Brain metastasis (BM) is a major cause of mortality in limited‐stage small‐cell lung cancer (LS‐SCLC). Prophylactic cranial irradiation (PCI) reduces BM incidence but carries neurotoxicity and lacks individualized risk assessment. Here, we developed BraMARS, an explainable deep learning model that estimates future BM risk from routine H&
Reproduced under the paper's license (CC BY), from the paper cited above.
Repository
Its files are read in the Code ↔ Paper reader above, with 3 matches between paragraphs and lines of code.
ZhoulabCPH/BraMARS
14fc0c761c03ae2cc94f875ead8d67da15b6f956, 2 December 2025Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
8 files
- S4MIL.py, Python, 182 lines, 1 match
- datasets.py, Python, 23 lines
- extractor/
ctran.py , Python, 48 lines - extractor/
get_features_CTransPath. , Python, 78 linespy - main.py, Python, 103 lines
- patch/
cut_patch.py , Python, 27 lines - train.py, Python, 284 lines, 2 matches
- README.md, Text, 8 lines
Code Availability Statement
The code of this work is available at https://
Reproduced under the paper's license (CC BY), from the paper cited above.
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;
- 3 matches between paragraphs of the paper and lines of the code (method lexical-v1);
- 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
Datasets cited
- ngdc.cncb.ac.cn/
omix , at ngdc.cncb.ac.cn; found in “Data Availability Statement”
Data Availability Statement
The whole‐slide histopathology images and associated clinical data generated and analyzed during this study are not publicly available due to patient privacy concerns and institutional data protection policies. These data may be made available to qualified researchers for non‐commercial research purposes upon reasonable request to the corresponding author, Dr. Lin Yang and Dr. Shilong Liu, subject to institutional data transfer agreement and ethical approval. The mass spectrometry proteomics data have been deposited in the OMIX database (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 1, 27 September 2026: the first record
Recorded: type, language, journal, pages, dates, 11 authors, 4 keywords, 2 funders, 41 references.
Cite
This paper
Yang, Z., Wang, T., Liu, S., Zhang, Z., Zhang, Y., Yang, F., Yu, B., Gao, S., Chen, Y., Yang, L., & Zhou, M. (2026). BraMARS: An Interpretable Histopathology-Driven Deep Learning Model for Brain Metastasis Risk Stratification in Surgically Resected Limited-Stage SCLC. Advanced science (Weinheim, Baden-Wurttemberg, Germany), e77075. https://
BibTeX
@article{yang2026bramars
author = {Yang, Zijian and Wang, Taolue and Liu, Shilong and Zhang, Zicheng and Zhang, Yibo and Yang, Fan and Yu, Bo and Gao, Shuaishuai and Chen, Yu and Yang, Lin and Zhou, Meng},
title = {{BraMARS: An Interpretable Histopathology-Driven Deep Learning Model for Brain Metastasis Risk Stratification in Surgically Resected Limited-Stage SCLC}},
journal = {Advanced science (Weinheim, Baden-Wurttemberg, Germany)},
year = {2026},
month = aug,
pages = {e77075},
publisher = {Wiley},
issn = {2198-3844},
doi = {10.1002/
url = {https://
pmid = {42598747},
pmcid = {PMC13474182}
}
RIS
TY - JOUR
AU - Yang, Zijian
AU - Wang, Taolue
AU - Liu, Shilong
AU - Zhang, Zicheng
AU - Zhang, Yibo
AU - Yang, Fan
AU - Yu, Bo
AU - Gao, Shuaishuai
AU - Chen, Yu
AU - Yang, Lin
AU - Zhou, Meng
TI - BraMARS: An Interpretable Histopathology-Driven Deep Learning Model for Brain Metastasis Risk Stratification in Surgically Resected Limited-Stage SCLC
T2 - Advanced science (Weinheim, Baden-Wurttemberg, Germany)
J2 - Adv Sci (Weinh)
PY - 2026
DA - 2026/
SP - e77075
SN - 2198-3844
PB - Wiley
DO - 10.1002/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1002/
"type": "article-journal",
"title": "BraMARS: An Interpretable Histopathology-Driven Deep Learning Model for Brain Metastasis Risk Stratification in Surgically Resected Limited-Stage SCLC",
"container-title": "Advanced science (Weinheim, Baden-Wurttemberg, Germany)",
"author": [
{
"family": "Yang",
"given": "Zijian"
},
{
"family": "Wang",
"given": "Taolue"
},
{
"family": "Liu",
"given": "Shilong"
},
{
"family": "Zhang",
"given": "Zicheng"
},
{
"family": "Zhang",
"given": "Yibo"
},
{
"family": "Yang",
"given": "Fan"
},
{
"family": "Yu",
"given": "Bo"
},
{
"family": "Gao",
"given": "Shuaishuai"
},
{
"family": "Chen",
"given": "Yu"
},
{
"family": "Yang",
"given": "Lin"
},
{
"family": "Zhou",
"given": "Meng"
}
],
"container-title-short":
"page": "e77075",
"DOI": "10.1002/
"PMID": "42598747",
"PMCID": "PMC13474182",
"ISSN": "2198-3844",
"publisher": "Wiley",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
8,
14
]
]
}
}
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.1186/s11658-026-00957-1
- Lactate-activated astrocytes promote NSCLC brain metastasis through extracellular vesicle-mediated miR-8085/
TRIM67/ ELK1 signaling axis. Journal: Cellular & molecular biology lettersIn common: ngdc.cncb.ac.cn/omix, other condition, 2 references - [2] doi:10.1002/cnr2.70625 [code]
- Machine Learning-Based Prediction of Brain Metastasis at Initial Diagnosis in Small-Cell Lung Cancer: Model Development and SHAP Interpretation Study.Journal: Cancer reports (Hoboken, N.J.)In common: clinical / translational, other condition, 3 references
- [3] doi:10.1038/s41598-026-61605-4 [code]
- Learning precise segmentation of neurofibrillary tangles from rapid manual point annotations.Journal: Scientific reportsIn common: Pillow, PyTorch, scikit-learn, 2 other tools, histology / microscopy, other condition
- [4] doi:10.1002/alz.71649 [code]
- Postmortem brain MRI reveals differential associations of subcortical and limbic volumes with cortical thinning and neurodegenerative pathologies.Journal: Alzheimer's & dementia : the journal of the Alzheimer's AssociationIn common: Pillow, PyTorch, scikit-learn, 2 other tools, histology / microscopy, other condition
- [5] doi:10.1038/s41398-026-03965-z [code]
- Disentangling individual heterogeneity reveals robust network and molecular signatures of major depressive disorder with suicidal ideation.Journal: Translational psychiatryIn common: Pillow, PyTorch, scikit-learn, 2 other tools, 1 reference
- [6] doi:10.1038/s41598-026-57519-w [code]
- Automated segmentation of neurons and spinal cord structures in immunofluorescence images using SpineDL.Journal: Scientific reportsIn common: Pillow, PyTorch, scikit-learn, 2 other tools, histology / microscopy, other condition
- [7] doi:10.1371/journal.pcbi.1013499 [code]
- VesiclePy: A machine learning vesicle analysis toolbox for volume electron microscopy.Journal: PLoS computational biologyIn common: Pillow, PyTorch, scikit-learn, 2 other tools, histology / microscopy
- [8] doi:10.1038/s41746-026-02651-0 [code]
- AI Augmented Confocal Laser Endomicroscopy for Rapid Intraoperative Diagnosis of Brain Tumors.Journal: NPJ digital medicineIn common: Pillow, PyTorch, pandas, 1 other tool, histology / microscopy, clinical / translational, other condition
- [9] doi:10.1038/s41593-026-02388-9 [code]
- Hippocampal CA3 connectomics reveals a gradient of mossy fiber inputs and selective feedforward inhibition onto pyramidal cells.Journal: Nature neuroscienceIn common: Pillow, PyTorch, scikit-learn, 2 other tools, histology / microscopy
- [10] doi:10.1038/s41598-026-43798-w [code]
- A Machine learning pipeline to investigate tissue ingrowth in cerebral aneurysms using preclinical animal models.Journal: Scientific reportsIn common: Pillow, PyTorch, scikit-learn, 2 other tools, histology / microscopy
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 3 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:8a953ae7fcba2c01…
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.
