OSCR

DDSurfer: A Weakly-Supervised Dual-Stream Deep Learning Framework for Cortical Surface Reconstruction From Diffusion MRI.

Code ↔ Paper

9 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

7 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.

The 9 matches · 1 of them tie a paragraph to a whole file without given lines: a weak match, whose lines are not tinted
  1. [1] § Methods › DDSurfer Network › Subnetwork: DualStream–FuseNet ↔ model/ddsurfer.py, lines 20 to 69 · score 0.76 · cross stream gating, ReLU, refined, modulates, sigmoid, encoders · block oscr:b:Q4C6Y958E45KS-1 · Report a mismatch
  2. [2] § Methods › DDSurfer Network › Subnetwork: DualStream–FuseNet ↔ model/cmunext.py, lines 1 to 31 · score 0.69 · CMUNeXt, dual stream, lightweight, upsampled, convolution, block · block oscr:b:MFB6KJR5Q1ZMS-P · Report a mismatch
  3. [3] § Methods › DDSurfer Network › Subnetwork: DualStream–FuseNet ↔ model/ddsurfer.py, lines 76 to 187 · score 0.66 · cross stream fusion, dual stream, downsampled, upsampled, Skip, decoder · block oscr:b:QCTSA57WHKK6N-X · Report a mismatch
  4. [4] § Experimental Section › Datasets and Preprocessing › DMRI Preprocessing and DTI Parameter Computation ↔ pnlpipe_pipelines/epi.py, the whole file · a weak match · score 0.59 · EPI distortion correction, eddy, rigid, pipeline, masking, brain · block oscr:b:ZP2WFR2QHZ060-X · Report a mismatch
  5. [5] § Experimental Section › Ablation Studies ↔ model/cmunext.py, lines 1 to 31 · score 0.59 · SE Fusion, dual stream, block, channel, DDSurfer, Module · block oscr:b:MFB6KJR5Q1ZMS-P · Report a mismatch
  6. [6] § Methods › DDSurfer Network › Loss Function Design ↔ utils/loss.py, lines 1 to 8 · score 0.54 · boundary loss, Chamfer distance, training · block oscr:b:FHE8PFZ302C5Q-J · Report a mismatch
  7. [7] § Methods › DDSurfer Network › Subnetwork: DiffeoSurf–FlowNet ↔ model/ddsurfer.py, lines 318 to 455 · score 0.54 · velocity fields, stationary, SVFs, network, weighted, vertices · block oscr:b:2KVD7P71VK1MK-V · Report a mismatch
  8. [8] § Methods › Implementation Details and SlicerDDSurfer ↔ run_ddsurfer_pipeline.py, lines 111 to 189 · score 0.53 · post processing, native space, preprocessing, MNI, inference, predicted · block oscr:b:B07ES6D0AZQBP-8 · Report a mismatch
  9. [9] § Experimental Section › Ablation Studies ↔ model/ddsurfer.py, lines 76 to 187 · score 0.53 · dual stream, bottleneck, LKA, SE, encoder, block · block oscr:b:QCTSA57WHKK6N-X · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 455 lines · 24 KB · MIT · 4 matches

  1. """DDSurfer dual-stream temporal attention network."""
  2. from __future__ import annotations
  3. from functools import partial
  4. from typing import Sequence
  5. import torch
  6. from torch.utils.checkpoint import checkpoint
  7. import torch.nn as nn
  8. import torch.nn.functional as F
  9. from model.cmunext import (AttentionGate3D, CMUNeXtBlock3D, CMUNeXtSEBlock3D,
  10. ConvBlock3D, FusionBlock3D, UpsampleBlock3D)
  11. from model.attention import LKAAttention3D
  12. from model.refinement import (GeometryAwareLKA3D,
  13. ResidualGate, ResidualSkipGate3D,
  14. cross_gate_options, replace_batchnorm, resolve_refinement)
  15. # ------------------------- Building Blocks -------------------------
  16. class CrossStreamFusion(nn.Module):
  17. """Voxelwise cross-stream gating, optionally with bounded residual modulation."""
  18. def __init__(self, channels_a: int, channels_b: int, reduction: int = 4,
  19. residual: bool = False, min_hidden: int = 1,
  20. max_hidden: int | None = None, gain_init: float = 0.1,
  21. max_gain: float = 0.25) -> None:
  22. super().__init__()
  23. if reduction < 1 or min_hidden < 1 or (max_hidden is not None and max_hidden < min_hidden):
  24. raise ValueError("Invalid cross-stream gate hidden width configuration")
  25. self.residual = residual
  26. inter_channels_a = max(min_hidden, channels_a // reduction)
  27. inter_channels_b = max(min_hidden, channels_b // reduction)
  28. if max_hidden is not None:
  29. inter_channels_a = min(max_hidden, inter_channels_a)
  30. inter_channels_b = min(max_hidden, inter_channels_b)
  31. self.gate_generator_A = nn.Sequential(
  32. nn.Conv3d(channels_b, inter_channels_a, kernel_size=1),
  33. nn.ReLU(inplace=True),
  34. nn.Conv3d(inter_channels_a, channels_a, kernel_size=1),
  35. nn.Sigmoid(),
  36. )
  37. self.gate_generator_B = nn.Sequential(
  38. nn.Conv3d(channels_a, inter_channels_b, kernel_size=1),
  39. nn.ReLU(inplace=True),
  40. nn.Conv3d(inter_channels_b, channels_b, kernel_size=1),
  41. nn.Sigmoid(),
  42. )
  43. if residual:
  44. self.modulation_a = ResidualGate(gain_init, max_gain)
  45. self.modulation_b = ResidualGate(gain_init, max_gain)
  46. for generator in (self.gate_generator_A, self.gate_generator_B):
  47. nn.init.zeros_(generator[2].weight)
  48. nn.init.zeros_(generator[2].bias)
  49. def forward(self, features_a: torch.Tensor, features_b: torch.Tensor,
  50. return_streams: bool = False):
  51. weights_a = self.gate_generator_A(features_b)
  52. weights_b = self.gate_generator_B(features_a)
  53. if self.residual:
  54. refined_a = self.modulation_a(features_a, weights_a)
  55. refined_b = self.modulation_b(features_b, weights_b)
  56. else:
  57. refined_a = features_a * weights_a
  58. refined_b = features_b * weights_b
  59. if return_streams:
  60. # Encoder paths remain separate; avoid a full-resolution concat/split copy.
  61. return refined_a, refined_b
  62. return torch.cat((refined_a, refined_b), dim=1)
  63. # ------------------------- Velocity Field Backbone -------------------------
  64. class VelocityFieldNet(nn.Module):
  65. """Dual-stream CMUNeXt encoder-decoder that predicts cascaded velocity fields."""
  66. def __init__(
  67. self,
  68. input_channel: int = 5,
  69. dims: list[int] | tuple[int, ...] = (16, 32, 64, 128, 256),
  70. depths: list[int] | tuple[int, ...] = (1, 1, 1, 6, 3),
  71. kernels: list[int] | tuple[int, ...] = (3, 3, 7, 7, 7),
  72. M: int = 2,
  73. R: int = 3,
  74. kernel_size: int = 3,
  75. inshape: Sequence[int] = (112, 224, 176),
  76. refinement: dict | None = None,
  77. ) -> None:
  78. super().__init__()
  79. self.M, self.R = int(M), int(R)
  80. if len(dims) != 5 or len(depths) != 5 or len(kernels) != 5:
  81. raise ValueError("dims, depths and kernels must have five stages")
  82. if any(d < 3 or int(d) != d for d in dims) or any(n < 1 or int(n) != n for n in depths):
  83. raise ValueError("Widths must be integers >= 3 and depths positive integers")
  84. if any(k < 1 or k % 2 == 0 or int(k) != k for k in kernels):
  85. raise ValueError("Stage kernels must be positive odd integers")
  86. if input_channel < 2:
  87. raise ValueError("Dual streams require FA and at least one other channel")
  88. self.input_channel = input_channel
  89. self.activation_checkpointing = False
  90. self.inshape = tuple(inshape)
  91. self.encoder_fusion_enabled = refinement is not None and refinement["encoder_fusion"]
  92. if len(inshape) != 3 or any(s < 16 or s % 16 or int(s) != s for s in inshape):
  93. raise ValueError("Each spatial dimension must be a positive multiple of 16")
  94. encoder_block = CMUNeXtSEBlock3D if refinement is None or refinement["use_se"] else CMUNeXtBlock3D
  95. gate_policy = refinement["cross_gate_policy"] if refinement is not None else "standard"
  96. def fusion(channels_a, channels_b, stage):
  97. return CrossStreamFusion(
  98. channels_a, channels_b, residual=refinement is not None and refinement["residual_gates"],
  99. **cross_gate_options(gate_policy, stage))
  100. skip_gate = (partial(ResidualSkipGate3D, norm_type=refinement["norm_type"])
  101. if refinement is not None and refinement["residual_gates"] else AttentionGate3D)
  102. self.dims_A = [int(d * 0.4) for d in dims]
  103. self.dims_B = [d - a for d, a in zip(dims, self.dims_A)]
  104. # Encoder streams
  105. self.stem_A = ConvBlock3D(1, self.dims_A[0])
  106. self.encoder1_A = encoder_block(self.dims_A[0], self.dims_A[0], depth=depths[0], kernel_size=kernels[0])
  107. self.encoder2_A = encoder_block(self.dims_A[0], self.dims_A[1], depth=depths[1], kernel_size=kernels[1])
  108. self.encoder3_A = encoder_block(self.dims_A[1], self.dims_A[2], depth=depths[2], kernel_size=kernels[2])
  109. self.encoder4_A = encoder_block(self.dims_A[2], self.dims_A[3], depth=depths[3], kernel_size=kernels[3])
  110. self.encoder5_A = encoder_block(self.dims_A[3], self.dims_A[4], depth=depths[4], kernel_size=kernels[4])
  111. self.stem_B = ConvBlock3D(input_channel - 1, self.dims_B[0])
  112. self.encoder1_B = encoder_block(self.dims_B[0], self.dims_B[0], depth=depths[0], kernel_size=kernels[0])
  113. self.encoder2_B = encoder_block(self.dims_B[0], self.dims_B[1], depth=depths[1], kernel_size=kernels[1])
  114. self.encoder3_B = encoder_block(self.dims_B[1], self.dims_B[2], depth=depths[2], kernel_size=kernels[2])
  115. self.encoder4_B = encoder_block(self.dims_B[2], self.dims_B[3], depth=depths[3], kernel_size=kernels[3])
  116. self.encoder5_B = encoder_block(self.dims_B[3], self.dims_B[4], depth=depths[4], kernel_size=kernels[4])
  117. # Cross-stream fusion and bottleneck
  118. if refinement is None or self.encoder_fusion_enabled:
  119. # Cross-stream fusion before downsampling.
  120. for index in range(4):
  121. setattr(self, f"fusion{index + 1}", fusion(self.dims_A[index], self.dims_B[index], index + 1))
  122. self.fusion5 = fusion(self.dims_A[4], self.dims_B[4], 5)
  123. self.Maxpool = nn.MaxPool3d(kernel_size=2, stride=2)
  124. self.lka_attention = (GeometryAwareLKA3D(dims[4], [s // 16 for s in inshape], refinement["norm_type"])
  125. if refinement is not None and refinement["geometry_aware_lka"]
  126. else LKAAttention3D(d_model=dims[4]))
  127. # Decoder with attention gates
  128. self.Up5_A = UpsampleBlock3D(self.dims_A[4], self.dims_A[3])
  129. self.Up5_B = UpsampleBlock3D(self.dims_B[4], self.dims_B[3])
  130. self.Att5_A = skip_gate(self.dims_A[3], self.dims_A[3], self.dims_A[2])
  131. self.Att5_B = skip_gate(self.dims_B[3], self.dims_B[3], self.dims_B[2])
  132. self.Up_conv5_A = FusionBlock3D(self.dims_A[3] * 2, self.dims_A[3])
  133. self.Up_conv5_B = FusionBlock3D(self.dims_B[3] * 2, self.dims_B[3])
  134. self.decoder_fusion4 = fusion(self.dims_A[3], self.dims_B[3], 4)
  135. self.Up4_A = UpsampleBlock3D(self.dims_A[3], self.dims_A[2])
  136. self.Up4_B = UpsampleBlock3D(self.dims_B[3], self.dims_B[2])
  137. self.Att4_A = skip_gate(self.dims_A[2], self.dims_A[2], self.dims_A[1])
  138. self.Att4_B = skip_gate(self.dims_B[2], self.dims_B[2], self.dims_B[1])
  139. self.Up_conv4_A = FusionBlock3D(self.dims_A[2] * 2, self.dims_A[2])
  140. self.Up_conv4_B = FusionBlock3D(self.dims_B[2] * 2, self.dims_B[2])
  141. self.decoder_fusion3 = fusion(self.dims_A[2], self.dims_B[2], 3)
  142. self.Up3_A = UpsampleBlock3D(self.dims_A[2], self.dims_A[1])
  143. self.Up3_B = UpsampleBlock3D(self.dims_B[2], self.dims_B[1])
  144. self.Att3_A = skip_gate(self.dims_A[1], self.dims_A[1], self.dims_A[0])
  145. self.Att3_B = skip_gate(self.dims_B[1], self.dims_B[1], self.dims_B[0])
  146. self.Up_conv3_A = FusionBlock3D(self.dims_A[1] * 2, self.dims_A[1])
  147. self.Up_conv3_B = FusionBlock3D(self.dims_B[1] * 2, self.dims_B[1])
  148. self.decoder_fusion2 = fusion(self.dims_A[1], self.dims_B[1], 2)
  149. self.Up2_A = UpsampleBlock3D(self.dims_A[1], self.dims_A[0])
  150. self.Up2_B = UpsampleBlock3D(self.dims_B[1], self.dims_B[0])
  151. self.Att2_A = skip_gate(self.dims_A[0], self.dims_A[0], max(1, self.dims_A[0] // 2))
  152. self.Att2_B = skip_gate(self.dims_B[0], self.dims_B[0], max(1, self.dims_B[0] // 2))
  153. self.Up_conv2_A = FusionBlock3D(self.dims_A[0] * 2, self.dims_A[0])
  154. self.Up_conv2_B = FusionBlock3D(self.dims_B[0] * 2, self.dims_B[0])
  155. # Cascaded velocity heads
  156. self.flow1 = nn.Conv3d(dims[2], 3 * M, kernel_size=kernel_size, padding=kernel_size // 2)
  157. self.flow2 = nn.Conv3d(dims[1] + 3 * M, 3 * M, kernel_size=kernel_size, padding=kernel_size // 2)
  158. self.flow3 = nn.Conv3d(dims[0] + 3 * M, 3 * M, kernel_size=kernel_size, padding=kernel_size // 2)
  159. for conv in (self.flow1, self.flow2, self.flow3):
  160. nn.init.normal_(conv.weight, 0.0, 1e-5)
  161. nn.init.constant_(conv.bias, 0.0)
  162. self.up = nn.Upsample(scale_factor=2, mode="trilinear", align_corners=True)
  163. if refinement is not None:
  164. replace_batchnorm(self, refinement["norm_type"])
  165. def _fuse_encoder(self, stage, features_a, features_b):
  166. if not self.encoder_fusion_enabled:
  167. return features_a, features_b
  168. module = getattr(self, f"fusion{stage}")
  169. return self._run(lambda a, b: module(a, b, return_streams=True), features_a, features_b)
  170. def _run(self, function, *inputs):
  171. # Recompute intermediate activations when checkpointing is enabled.
  172. if self.activation_checkpointing and self.training and torch.is_grad_enabled():
  173. return checkpoint(function, *inputs, use_reentrant=False, preserve_rng_state=True)
  174. return function(*inputs)
  175. def forward(self, x: torch.Tensor, return_context: bool = False):
  176. if x.ndim != 5 or x.shape[0] != 1 or x.shape[1] != self.input_channel:
  177. raise ValueError("VF backbone requires [1,C_in,X,Y,Z]")
  178. if tuple(x.shape[2:]) != self.inshape:
  179. raise ValueError("VF input differs from its planned spatial shape")
  180. stream_a = x[:, 0:1]
  181. stream_b = x[:, 1:]
  182. x1_a = self._run(self.encoder1_A, self._run(self.stem_A, stream_a))
  183. x1_b = self._run(self.encoder1_B, self._run(self.stem_B, stream_b))
  184. x1_a, x1_b = self._fuse_encoder(1, x1_a, x1_b)
  185. x2_a = self._run(self.encoder2_A, self.Maxpool(x1_a))
  186. x2_b = self._run(self.encoder2_B, self.Maxpool(x1_b))
  187. x2_a, x2_b = self._fuse_encoder(2, x2_a, x2_b)
  188. x3_a = self._run(self.encoder3_A, self.Maxpool(x2_a))
  189. x3_b = self._run(self.encoder3_B, self.Maxpool(x2_b))
  190. x3_a, x3_b = self._fuse_encoder(3, x3_a, x3_b)
  191. x4_a = self._run(self.encoder4_A, self.Maxpool(x3_a))
  192. x4_b = self._run(self.encoder4_B, self.Maxpool(x3_b))
  193. x4_a, x4_b = self._fuse_encoder(4, x4_a, x4_b)
  194. x5_a = self._run(self.encoder5_A, self.Maxpool(x4_a))
  195. x5_b = self._run(self.encoder5_B, self.Maxpool(x4_b))
  196. bottleneck = self._run(self.lka_attention, self._run(self.fusion5, x5_a, x5_b))
  197. d5_a_in, d5_b_in = torch.split(bottleneck, [self.dims_A[4], self.dims_B[4]], dim=1)
  198. d5_a = self._run(self.Up5_A, d5_a_in)
  199. d5_b = self._run(self.Up5_B, d5_b_in)
  200. x4_a_att = self._run(self.Att5_A, d5_a, x4_a)
  201. x4_b_att = self._run(self.Att5_B, d5_b, x4_b)
  202. d4_a = self._run(self.Up_conv5_A, torch.cat([x4_a_att, d5_a], dim=1))
  203. d4_b = self._run(self.Up_conv5_B, torch.cat([x4_b_att, d5_b], dim=1))
  204. d4_fused = self._run(self.decoder_fusion4, d4_a, d4_b)
  205. d4_a_out, d4_b_out = torch.split(d4_fused, [self.dims_A[3], self.dims_B[3]], dim=1)
  206. d4_a_up = self._run(self.Up4_A, d4_a_out)
  207. d4_b_up = self._run(self.Up4_B, d4_b_out)
  208. x3_a_att = self._run(self.Att4_A, d4_a_up, x3_a)
  209. x3_b_att = self._run(self.Att4_B, d4_b_up, x3_b)
  210. d3_a = self._run(self.Up_conv4_A, torch.cat([x3_a_att, d4_a_up], dim=1))
  211. d3_b = self._run(self.Up_conv4_B, torch.cat([x3_b_att, d4_b_up], dim=1))
  212. d3_fused = self._run(self.decoder_fusion3, d3_a, d3_b)
  213. vf1_small = self._run(self.flow1, d3_fused)
  214. d3_a_out, d3_b_out = torch.split(d3_fused, [self.dims_A[2], self.dims_B[2]], dim=1)
  215. d3_a_up = self._run(self.Up3_A, d3_a_out)
  216. d3_b_up = self._run(self.Up3_B, d3_b_out)
  217. x2_a_att = self._run(self.Att3_A, d3_a_up, x2_a)
  218. x2_b_att = self._run(self.Att3_B, d3_b_up, x2_b)
  219. d2_a = self._run(self.Up_conv3_A, torch.cat([x2_a_att, d3_a_up], dim=1))
  220. d2_b = self._run(self.Up_conv3_B, torch.cat([x2_b_att, d3_b_up], dim=1))
  221. d2_fused = self._run(self.decoder_fusion2, d2_a, d2_b)
  222. vf1_medium = self.up(vf1_small)
  223. vf2_medium = vf1_medium + self._run(self.flow2, torch.cat([d2_fused, vf1_medium], dim=1))
  224. d2_a_out, d2_b_out = torch.split(d2_fused, [self.dims_A[1], self.dims_B[1]], dim=1)
  225. d2_a_up = self._run(self.Up2_A, d2_a_out)
  226. d2_b_up = self._run(self.Up2_B, d2_b_out)
  227. x1_a_att = self._run(self.Att2_A, d2_a_up, x1_a)
  228. x1_b_att = self._run(self.Att2_B, d2_b_up, x1_b)
  229. d1_a = self._run(self.Up_conv2_A, torch.cat([x1_a_att, d2_a_up], dim=1))
  230. d1_b = self._run(self.Up_conv2_B, torch.cat([x1_b_att, d2_b_up], dim=1))
  231. d1_fused = torch.cat([d1_a, d1_b], dim=1)
  232. vf2_full = self.up(vf2_medium)
  233. vf3_full = vf2_full + self._run(self.flow3, torch.cat([d1_fused, vf2_full], dim=1))
  234. vf1_full = self.up(vf1_medium)
  235. vf1 = vf1_full.reshape(self.M, 3, *vf1_full.shape[2:])
  236. vf2 = vf2_full.reshape(self.M, 3, *vf2_full.shape[2:])
  237. vf3 = vf3_full.reshape(self.M, 3, *vf3_full.shape[2:])
  238. if self.R == 3:
  239. fields = torch.cat([vf1, vf2, vf3], dim=0)
  240. elif self.R == 2:
  241. fields = torch.cat([vf2, vf3], dim=0)
  242. else:
  243. fields = vf3
  244. if return_context:
  245. return fields, F.adaptive_avg_pool3d(bottleneck, 1).flatten(1)
  246. return fields
  247. # ------------------------- Temporal Attention -------------------------
  248. class TemporalAttentionNet(nn.Module):
  249. """Temporal attention predictor for weighting stationary velocity fields."""
  250. def __init__(self, hidden_channels: int = 16, M: int = 2, R: int = 3,
  251. context_channels: int | None = None) -> None:
  252. super().__init__()
  253. self.context_channels = context_channels
  254. self.fc1 = nn.Linear(1, hidden_channels * 4)
  255. self.fc2 = nn.Linear(hidden_channels * 4, hidden_channels * 8)
  256. self.fc3 = nn.Linear(hidden_channels * 8, hidden_channels * 8)
  257. self.fc4 = nn.Linear(hidden_channels * 8, hidden_channels * 4)
  258. self.fc5 = nn.Linear(hidden_channels * 4, M * R)
  259. if context_channels is not None:
  260. self.context_film = nn.Sequential(nn.LayerNorm(context_channels),
  261. nn.Linear(context_channels, hidden_channels * 8))
  262. # Begin with the shared time policy; learn subject-specific corrections.
  263. nn.init.zeros_(self.context_film[1].weight)
  264. nn.init.zeros_(self.context_film[1].bias)
  265. def forward(self, t: torch.Tensor, context: torch.Tensor | None = None) -> torch.Tensor:
  266. out = F.leaky_relu(self.fc1(t), 0.2)
  267. if self.context_channels is not None:
  268. if context is None or context.shape != (1, self.context_channels):
  269. raise ValueError("Conditional attention requires one pooled image-feature vector")
  270. gamma, beta = self.context_film(context).chunk(2, dim=-1)
  271. out = out * (1.0 + 0.1 * gamma.tanh()) + 0.1 * beta.tanh()
  272. out = F.leaky_relu(self.fc2(out), 0.2)
  273. out = F.leaky_relu(self.fc3(out), 0.2)
  274. out = F.leaky_relu(self.fc4(out), 0.2)
  275. return F.softmax(self.fc5(out), dim=-1)
  276. # ------------------------- TANet -------------------------
  277. class TANet(nn.Module):
  278. """Temporal attention network with RK4 integration over stationary fields."""
  279. def __init__(
  280. self,
  281. C_in: int = 5,
  282. C_hid: Sequence[int] = (16, 32, 64, 128, 256),
  283. inshape: Sequence[int] = (112, 224, 176),
  284. depths: Sequence[int] = (1, 1, 1, 6, 3),
  285. kernels: Sequence[int] = (3, 3, 7, 7, 7),
  286. step_size: float = 0.02,
  287. M: int = 2,
  288. R: int = 3,
  289. device: str = "cuda:0",
  290. refinement: dict | None = None,
  291. ) -> None:
  292. super().__init__()
  293. self.M = int(M)
  294. self.R = int(R)
  295. if not 0 < step_size <= 1 or abs(round(1.0 / step_size) * step_size - 1.0) > 1e-6:
  296. raise ValueError("step_size must divide the integration interval [0,1]")
  297. if R not in (1, 2, 3) or M < 1 or int(M) != M:
  298. raise ValueError("Expected M >= 1 and R in (1,2,3)")
  299. self.inshape = tuple(inshape)
  300. self.refinement = resolve_refinement(refinement)
  301. self.conditioned_attention = self.refinement is not None and self.refinement["conditioned_attention"]
  302. self.rk4_stage_time = self.refinement is not None and self.refinement["rk4_stage_time"]
  303. self.vf_net = VelocityFieldNet(C_in, C_hid, depths, kernels, M=self.M, R=self.R,
  304. inshape=inshape, refinement=self.refinement)
  305. self.att_net = TemporalAttentionNet(hidden_channels=16, M=self.M, R=self.R,
  306. context_channels=C_hid[-1] if self.conditioned_attention else None)
  307. self.h = float(step_size)
  308. self.num_steps = max(1, int(round(1.0 / self.h)))
  309. # Nonpersistent buffers preserve strict loading of release state_dicts.
  310. times = (torch.arange(2 * self.num_steps + 1)[:, None] * (self.h / 2)
  311. if self.rk4_stage_time else torch.arange(self.num_steps)[:, None] * self.h)
  312. self.register_buffer("timesteps", times, persistent=False)
  313. self.register_buffer("scale", torch.as_tensor(inshape, dtype=torch.float32)[None, None, :] - 1.0, persistent=False)
  314. def forward(self, vertices: torch.Tensor, volumes: torch.Tensor, return_extras: bool = False):
  315. if vertices.ndim != 3 or vertices.shape[-1] != 3 or volumes.ndim != 5:
  316. raise ValueError("Expected vertices [1,N,3] and volumes [1,C,X,Y,Z]")
  317. if vertices.shape[0] != 1 or volumes.shape[0] != 1:
  318. raise ValueError("DDSurfer TANet requires batch_size=1")
  319. if tuple(volumes.shape[2:]) != self.inshape:
  320. raise ValueError("Volume shape does not match the model's crop-voxel geometry")
  321. context = None
  322. if self.conditioned_attention:
  323. svfs_all, context = self.vf_net(volumes, return_context=True)
  324. else:
  325. svfs_all = self.vf_net(volumes)
  326. expected = self.M * self.R
  327. if svfs_all.dim() != 5:
  328. msg = f"vf_net output expects 5D, got {svfs_all.shape}"
  329. raise RuntimeError(msg)
  330. if svfs_all.shape[0] == 3 and svfs_all.shape[-1] == expected:
  331. svfs_all = svfs_all.permute(4, 0, 1, 2, 3).contiguous()
  332. elif svfs_all.shape[0] != expected or svfs_all.shape[1] != 3:
  333. msg = f"Unexpected SVF shape {svfs_all.shape}, expect [MR,3,X,Y,Z] with MR={expected}"
  334. raise RuntimeError(msg)
  335. # Keep velocity interpolation and all 50 RK4 steps in FP32 under AMP.
  336. with torch.autocast(device_type=volumes.device.type, enabled=False):
  337. return self._integrate(vertices.float(), svfs_all.float(), return_extras,
  338. context.float() if context is not None else None)
  339. def _integrate(self, vertices: torch.Tensor, svfs_all: torch.Tensor, return_extras: bool,
  340. context: torch.Tensor | None = None):
  341. attention = self.att_net(self.timesteps.float(), context)[..., None, None]
  342. current_vertices = vertices
  343. trajectory_stats = [] if return_extras else None
  344. for step in range(self.num_steps):
  345. weights = attention[2 * step if self.rk4_stage_time else step]
  346. middle_weights = attention[2 * step + 1] if self.rk4_stage_time else weights
  347. end_weights = attention[2 * step + 2] if self.rk4_stage_time else weights
  348. def sample_field(sample_vertices: torch.Tensor, stage_weights: torch.Tensor) -> torch.Tensor:
  349. raw = self.interpolate(sample_vertices, svfs_all)
  350. return (stage_weights.view(-1, 1, 1) * raw).sum(0, keepdim=True)
  351. k1 = sample_field(current_vertices, weights)
  352. k2 = sample_field(current_vertices + self.h * 0.5 * k1, middle_weights)
  353. k3 = sample_field(current_vertices + self.h * 0.5 * k2, middle_weights)
  354. k4 = sample_field(current_vertices + self.h * k3, end_weights)
  355. velocity = (k1 + 2 * k2 + 2 * k3 + k4) / 6.0
  356. current_vertices = current_vertices + self.h * velocity
  357. if return_extras:
  358. speed = torch.linalg.vector_norm(velocity[0], dim=-1)
  359. trajectory_stats.append(
  360. {
  361. "t": float((step + 1) * self.h),
  362. "speed_mean": float(speed.mean()),
  363. "speed_p95": float(torch.quantile(speed, 0.95)),
  364. "speed_max": float(speed.max()),
  365. }
  366. )
  367. if not return_extras:
  368. return current_vertices
  369. per_level = {}
  370. offset = 0
  371. for level in range(self.R):
  372. per_level[f"vf{4 - self.R + level}"] = svfs_all[offset : offset + self.M].detach()
  373. offset += self.M
  374. extras = {
  375. "svfs_all": svfs_all.detach(),
  376. "per_level": per_level,
  377. "att_weights": attention.squeeze(-1).squeeze(-1).detach(),
  378. "att_times": self.timesteps.detach(),
  379. "gate_stats": {name: module.last_gate_stats for name, module in self.named_modules()
  380. if isinstance(module, ResidualGate) and module.collect_diagnostics},
  381. "traj_stats": trajectory_stats,
  382. }
  383. return current_vertices, extras
  384. def enable_activation_checkpointing(self, enabled: bool = True):
  385. if enabled and any(isinstance(module, nn.BatchNorm3d) for module in self.vf_net.modules()):
  386. raise ValueError("Checkpoint recomputation must not double-update BatchNorm running statistics")
  387. self.vf_net.activation_checkpointing = enabled
  388. def set_gate_diagnostics(self, enabled: bool = True):
  389. """Enable scalar gate statistics only during debugging, not each training step."""
  390. for module in self.modules():
  391. if isinstance(module, ResidualGate):
  392. module.collect_diagnostics = enabled
  393. module.last_gate_stats = None
  394. def interpolate(self, vertices: torch.Tensor, fields: torch.Tensor) -> torch.Tensor:
  395. coords = 2.0 * vertices / self.scale - 1.0
  396. coords = coords.repeat(fields.shape[0], 1, 1)
  397. coords = coords[:, :, None, None].flip(-1)
  398. sampled = F.grid_sample(fields, coords, mode="bilinear", padding_mode="border", align_corners=True)
  399. return sampled[..., 0, 0].permute(0, 2, 1)

ddsurfer.py at commit 8a8699c, under MIT · at the source

Overview

Authors: Chengjin Li1, Wei Zhang1, Xi Zhu1, Yuqian Chen2, Nir A Sochen3, Jarrett Rushmore2,4, Carl‐Fredrik Westin2, Yogesh Rathi2, Lauren J O'Donnell2, Ofer Pasternak2, Fan Zhang1
  1. University of Electronic Science and Technology of China, Chengdu, China
  2. Brigham and Women's Hospital, Harvard Medical School, Boston, Massachusetts, USA
  3. School of Mathematical Sciences, University of Tel Aviv, Tel Aviv, Israel
  4. Department of Anatomy and Neurobiology, Boston University School of Medicine, Boston, Massachusetts, USA
Dates: received 27 January 2026; accepted 3 July 2026; published online 23 July 2026; in print July 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1002/advs.76596 · PMID 42489305 · PMCID PMC13393330 · OpenAlex W7170170346
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: structural MRI / diffusion (modality), methods / tools (subfield)
Methods: Connectivity, Machine learning, fMRI & imaging, Preprocessing
Keywords: cortical surface reconstruction, deep learning, diffusion MRI, neuroimaging, weakly supervised learning
Topic: Advanced Neuroimaging Techniques and Applications (Radiology, Nuclear Medicine and Imaging, Medicine), according to OpenAlex
Funding: National Natural Science Foundation of China (62371107); National Key Research and Development Program of China (2023YFE0118600); Science and Technology Department of Sichuan Province (2026YFHZ0045)
Citations: not cited yet (Europe PMC); 75 references in the paper

Abstract

Cortical surface reconstruction of white matter and pial surfaces from diffusion MRI (dMRI) is critical for neuroimaging analyses, including tractography, connectomics, and multimodal data integration. However, obtaining these surfaces from dMRI data is inherently challenged by its low spatial resolution and poor tissue contrast. Currently, this relies on T1‐weighted images, from which the surfaces are reconstructed and then registered to the dMRI space—a process affected by inaccurate inter‐modality registration. This study introduces DDSurfer, an end‐to‐end deep learning framework that directly generates high‐fidelity cortical surfaces from dMRI data. DDSurfer leverages a novel dual‐stream architecture that processes and synergistically fuses complementary microstructural features from dMRI, learning a diffeomorphic transformation for subject‐specific surface reconstruction. The model is trained using a robust weakly‐supervised strategy with automatically generated pseudo‐ground‐truth surfaces. Extensive evaluations on diverse datasets demonstrate that DDSurfer surpasses traditional methods in geometric accuracy, morphological consistency, and generalization. By providing a computationally efficient and robust T1‐weighted‐independent solution, DDSurfer overcomes a major bottleneck in dMRI, delivering a practical tool to advance accurate dMRI‐centric connectomics and surface‐based investigations. Source code and implementation as an interactive 3D Slicer module are publicly available at: https://github.com/ChengjinLii/DDSurfer.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 9 matches between paragraphs and lines of code.

ChengjinLii/DDSurfer

License: MIT
State: the link answers, verified on 28 October 2026
Evidence: files inventoried
Commit: 8a8699c0fda32be7e0a3cbca2903680b9f0c950b, 23 October 2026
Languages: Python (71), Shell (4)
Size: 111 files, 75 scripts
Software Heritage: not archived
Found in: the text, “Introduction”
Holds: README, environment (dti_processing/environment.yml, dti_processing/requirements.txt)
Not found: license file, CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (14 files), NiBabel (9 files), PyTorch (8 files), SciPy (2 files), SimpleITK (2 files)
Availability: 2 checks, the latest on 28 October 2026: the link answers
  • 28 October 2026: the link answers
  • 27 September 2026: the link answers
77 files

pnlbwh/pnlpipe

License: other
State: the link answers, verified on 27 October 2026
Evidence: files inventoried
Commit: 13545b03effe3cbcca828688bbf808e1958b25d8, 12 March 2025
Languages: Python (61), Shell (4), R (1)
Size: 107 files, 66 scripts
Software Heritage: archived
Found in: the text, “DMRI Preprocessing and DTI Parameter Computation”
Holds: README, license file, environment (python_env/environment36.yml, python_env/environment36_gpu.yml, python_env/requirements.txt, pnlpipe_cli/pipecmd/setup.py), tests, 1 notebook
Not found: CITATION.cff, continuous integration, documentation
Tools: pandas (7 files), NumPy (6 files), FreeSurfer (4 files), NiBabel (3 files), ANTs (2 files), data.table (1 file), SciPy (1 file)
Availability: 2 checks, the latest on 27 October 2026: the link answers
  • 27 October 2026: the link answers
  • 27 September 2026: the link answers
68 files

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:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 141 scripts, each with its path and the digest of its content;
  • 9 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

No dataset and no data link were found in the paper.

Data Availability Statement

The data that support the findings of this study are available on request from the corresponding author. The data are not publicly available due to privacy or ethical restrictions.

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, 5 keywords, 3 funders, 51 references.

Cite

This paper

Li, C., Zhang, W., Zhu, X., Chen, Y., Sochen, N. A., Rushmore, J., Westin, C., Rathi, Y., O'Donnell, L. J., Pasternak, O., & Zhang, F. (2026). DDSurfer: A Weakly-Supervised Dual-Stream Deep Learning Framework for Cortical Surface Reconstruction From Diffusion MRI. Advanced science (Weinheim, Baden-Wurttemberg, Germany), e76596. https://doi.org/10.1002/advs.76596

BibTeX

@article{li2026ddsurfer,
author = {Li, Chengjin and Zhang, Wei and Zhu, Xi and Chen, Yuqian and Sochen, Nir A and Rushmore, Jarrett and Westin, Carl‐Fredrik and Rathi, Yogesh and O'Donnell, Lauren J and Pasternak, Ofer and Zhang, Fan},
title = {{DDSurfer: A Weakly-Supervised Dual-Stream Deep Learning Framework for Cortical Surface Reconstruction From Diffusion MRI}},
journal = {Advanced science (Weinheim, Baden-Wurttemberg, Germany)},
year = {2026},
month = jul,
pages = {e76596},
publisher = {Wiley},
issn = {2198-3844},
doi = {10.1002/advs.76596},
url = {https://doi.org/10.1002/advs.76596},
pmid = {42489305},
pmcid = {PMC13393330}
}

RIS

TY - JOUR
AU - Li, Chengjin
AU - Zhang, Wei
AU - Zhu, Xi
AU - Chen, Yuqian
AU - Sochen, Nir A
AU - Rushmore, Jarrett
AU - Westin, Carl‐Fredrik
AU - Rathi, Yogesh
AU - O'Donnell, Lauren J
AU - Pasternak, Ofer
AU - Zhang, Fan
TI - DDSurfer: A Weakly-Supervised Dual-Stream Deep Learning Framework for Cortical Surface Reconstruction From Diffusion MRI
T2 - Advanced science (Weinheim, Baden-Wurttemberg, Germany)
J2 - Adv Sci (Weinh)
PY - 2026
DA - 2026/07/23
SP - e76596
SN - 2198-3844
PB - Wiley
DO - 10.1002/advs.76596
UR - https://doi.org/10.1002/advs.76596
LA - en
ER -

CSL-JSON

{
"id": "10.1002/advs.76596",
"type": "article-journal",
"title": "DDSurfer: A Weakly-Supervised Dual-Stream Deep Learning Framework for Cortical Surface Reconstruction From Diffusion MRI",
"container-title": "Advanced science (Weinheim, Baden-Wurttemberg, Germany)",
"author": [
{
"family": "Li",
"given": "Chengjin"
},
{
"family": "Zhang",
"given": "Wei"
},
{
"family": "Zhu",
"given": "Xi"
},
{
"family": "Chen",
"given": "Yuqian"
},
{
"family": "Sochen",
"given": "Nir A"
},
{
"family": "Rushmore",
"given": "Jarrett"
},
{
"family": "Westin",
"given": "Carl‐Fredrik"
},
{
"family": "Rathi",
"given": "Yogesh"
},
{
"family": "O'Donnell",
"given": "Lauren J"
},
{
"family": "Pasternak",
"given": "Ofer"
},
{
"family": "Zhang",
"given": "Fan"
}
],
"container-title-short": "Adv Sci (Weinh)",
"page": "e76596",
"DOI": "10.1002/advs.76596",
"PMID": "42489305",
"PMCID": "PMC13393330",
"ISSN": "2198-3844",
"publisher": "Wiley",
"URL": "https://doi.org/10.1002/advs.76596",
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
23
]
]
}
}

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.1038/s41598-026-54446-8 [code]
Deep learning-based Desikan-Killiany parcellation of the brain using diffusion MRI.
Journal: Scientific reports
In common: FreeSurfer, NiBabel, PyTorch, 2 other tools, methods / tools, structural MRI / diffusion, 16 references
[2] doi:10.1002/hbm.70041 [code]
Assessment of the Depiction of Superficial White Matter Using Ultra-High-Resolution Diffusion MRI.
Journal: Human brain mapping
In common: ANTs, FreeSurfer, NiBabel, 2 other tools, methods / tools, structural MRI / diffusion, 12 references, author Fan Zhang
[3] doi:10.1038/s41597-024-03624-2 [code]
A diffusion MRI tractography atlas for concurrent white matter mapping across Eastern and Western populations.
Journal: Scientific data
In common: ANTs, FreeSurfer, data.table, 4 other tools, methods / tools, structural MRI / diffusion, 10 references, author Fan Zhang
[4] doi:10.1016/j.neuroimage.2023.120086 [code]
Deep fiber clustering: Anatomically informed fiber clustering with self-supervised deep learning for fast and effective tractography parcellation.
Journal: NeuroImage
In common: NiBabel, PyTorch, pandas, 2 other tools, methods / tools, structural MRI / diffusion, 10 references, author Fan Zhang
[5] doi:10.1002/hbm.70071 [code]
Tractography-Based Automated Identification of Retinogeniculate Visual Pathway With Novel Microstructure-Informed Supervised Contrastive Learning.
Journal: Human brain mapping
In common: ANTs, FreeSurfer, NiBabel, 2 other tools, structural MRI / diffusion, 8 references, author Fan Zhang
[6] doi:10.3389/fnins.2024.1376570 [code]
A systematic review of automated methods to perform white matter tract segmentation.
Journal: Frontiers in neuroscience
In common: NiBabel, PyTorch, pandas, 2 other tools, methods / tools, structural MRI / diffusion, 10 references
[7] doi:10.1186/s40708-022-00155-7 [code]
Fast cortical surface reconstruction from MRI using deep learning.
Journal: Brain informatics
In common: SimpleITK, ANTs, FreeSurfer, 4 other tools, methods / tools, structural MRI / diffusion, 7 references
[8] doi:10.1162/imag_a_00353
Diffusion MRI with Machine Learning.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: methods / tools, structural MRI / diffusion, 11 references
[9] doi:10.1162/imag.a.1183 [code]
Learning-based segmentation of diffusion-weighted MR images with arbitrary &lt;i&gt;q&lt;/i&gt;-space samplings.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: NiBabel, PyTorch, pandas, 2 other tools, methods / tools, structural MRI / diffusion, 10 references
[10] doi:10.1016/j.nicl.2026.103979 [code]
Study of sex differences in the whole brain white matter using diffusion MRI tractography and suprathreshold fiber cluster statistics.
Journal: NeuroImage. Clinical
In common: NiBabel, pandas, SciPy, 1 other tool, structural MRI / diffusion, 7 references, author Fan Zhang

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.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1002/advs.76596.svg)](https://openscicode.org/badge/doi/10.1002/advs.76596)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1002/advs.76596.svg
   :target: https://openscicode.org/badge/doi/10.1002/advs.76596
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1002/advs.76596"><img src="https://openscicode.org/badge/doi/10.1002/advs.76596.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge 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: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.