OSCR

ER-associated biogenesis of PINK1 preprotein for neuronal mitophagy.

Code ↔ Paper

1 match 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.

One block of code here has 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 1 match
  1. [1] § Methods › Cryo-electron tomography ↔ harbauer_paper/mask_creator_live_20251203_fluor_selected_selection_mito.py, lines 966 to 1041 · score 0.52 · EMBL, Mattei, IsoNet, MemBrain, reconstructed, organelles · block oscr:b:KJGP97KKTC7T4-Q · 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 · 1,057 lines · 40 KB · MIT · 1 match

  1. #!/usr/bin/env python3
  2. # =============================================================================
  3. # COPYRIGHT, ATTRIBUTION, AND LICENSE NOTICE
  4. # =============================================================================
  5. #
  6. # Copyright (c) 2026 Mattei Team, Imaging Centre and Molecular Systems Biology Unit,
  7. # European Molecular Biology Laboratory (EMBL).
  8. #
  9. # SOFTWARE DEVELOPMENT:
  10. # This script was developed by the Mattei Team at the Imaging Centre and Molecular Systems Biology Unit,
  11. # European Molecular Biology Laboratory (EMBL), with the assistance of
  12. # Artificial Intelligence (AI) tools for code development, optimization,
  13. # and documentation.
  14. #
  15. # OPEN-SOURCE AVAILABILITY:
  16. # This software is released as open-source software under the MIT License
  17. # to support scientific research, reproducibility, and collaboration.
  18. #
  19. # Users are permitted to use, copy, modify, merge, publish, distribute,
  20. # sublicense, and/or sell copies of this software, subject to the terms
  21. # of the MIT License provided below.
  22. #
  23. # ATTRIBUTION AND CITATION:
  24. # When using, modifying, adapting, or redistributing this software,
  25. # users must retain the original copyright and license notices as
  26. # required by the MIT License.
  27. #
  28. # When this software contributes to scientific publications,
  29. # presentations, or other research outputs, users are kindly requested
  30. # to acknowledge the original developers as:
  31. #
  32. # "Mattei Team, Imaging Centre and Molecular Systems Biology Unit,
  33. # European Molecular Biology Laboratory (EMBL)."
  34. #
  35. # Scientific citation and acknowledgment are strongly encouraged
  36. # to recognize the contributions of the original developers.
  37. #
  38. # =============================================================================
  39. # MIT LICENSE
  40. # =============================================================================
  41. #
  42. # Permission is hereby granted, free of charge, to any person obtaining a
  43. # copy of this software and associated documentation files (the "Software"),
  44. # to deal in the Software without restriction, including without limitation
  45. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  46. # and/or sell copies of the Software, and to permit persons to whom the
  47. # Software is furnished to do so, subject to the following conditions:
  48. #
  49. # The above copyright notice and this permission notice shall be included
  50. # in all copies or substantial portions of the Software.
  51. #
  52. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  53. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  54. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  55. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  56. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  57. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  58. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  59. #
  60. # =============================================================================
  61. from qtpy.QtWidgets import (
  62. QWidget, QFormLayout, QVBoxLayout, QSpinBox, QDoubleSpinBox,
  63. QComboBox, QPushButton, QLabel, QCheckBox,QHBoxLayout, QLineEdit, QListWidget, QListWidgetItem
  64. )
  65. from qtpy.QtCore import Qt, QTimer, Signal
  66. from napari.qt.threading import thread_worker
  67. import math
  68. import os
  69. import numpy as np
  70. import mrcfile
  71. import napari
  72. from scipy.ndimage import label
  73. import matplotlib.pyplot as plt
  74. from skimage.morphology import remove_small_objects
  75. from skimage.segmentation import relabel_sequential
  76. from pathlib import Path
  77. import re
  78. #----------------------Tomo Mask Generator Widget---------------------
  79. def make_tilted_slab_mask(
  80. nx: int = 682,
  81. ny: int = 682,
  82. nz: int = 292,
  83. thickness: int = 20,
  84. center_z: float = None,
  85. tilt_xz_deg: float = 0.0, # rotation about Y (tilt in XZ)
  86. tilt_yz_deg: float = 0.0, # rotation about X (tilt in YZ)
  87. xy_margin: int = None,
  88. dtype=np.uint8,
  89. ):
  90. """
  91. Build a big rectangular slab (very large in X/Y, finite 'thickness' along its normal),
  92. tilt it in XZ and YZ, center it at (Xmid, Ymid, center_z), and rasterize into a (nz,ny,nx) mask.
  93. Array shape is (Z,Y,X) = (nz, ny, nx).
  94. """
  95. if center_z is None:
  96. center_z = (nz - 1) / 2.0
  97. if xy_margin is None:
  98. # Big enough to always cover; tweak if you like.
  99. xy_margin = max(nx, ny) # one extra volume width on each side
  100. # Half-extents of the slab in its own coordinate frame.
  101. hx = max(nx, ny, nz) + xy_margin
  102. hy = max(nx, ny, nz) + xy_margin
  103. hz = thickness / 2.0
  104. # Precompute 2D grids for X and Y (to keep memory small)
  105. x_coords = np.arange(nx, dtype=np.float32)
  106. y_coords = np.arange(ny, dtype=np.float32)
  107. Xv, Yv = np.meshgrid(x_coords, y_coords, indexing='xy') # shape (ny, nx)
  108. X0 = Xv - (nx - 1) / 2.0 # center in X at mid-volume
  109. Y0 = Yv - (ny - 1) / 2.0 # center in Y at mid-volume
  110. # Angles and their sines/cosines (radians)
  111. beta = math.radians(tilt_xz_deg) # about Y
  112. alpha = math.radians(tilt_yz_deg) # about X
  113. cosb, sinb = math.cos(beta), math.sin(beta)
  114. cosa, sina = math.cos(alpha), math.sin(alpha)
  115. mask = np.zeros((nz, ny, nx), dtype=dtype)
  116. # Loop over slices to keep memory reasonable
  117. for z in range(nz):
  118. z0 = float(z) - float(center_z)
  119. # Compute the three local coordinates for this z-slice
  120. Xp = cosb * X0 - sinb * z0
  121. Yp = (sinb * sina) * X0 + cosa * Y0 + (cosb * sina) * z0
  122. Zp = (sinb * cosa) * X0 - sina * Y0 + (cosb * cosa) * z0
  123. slab = (np.abs(Zp) <= hz) & (np.abs(Xp) <= hx) & (np.abs(Yp) <= hy)
  124. mask[z, :, :] = slab.astype(dtype)
  125. return mask
  126. # ---- Qt Dock Widget ----------------------------------------------------------
  127. class TiltedSlabWidget(QWidget):
  128. mask_updated = Signal(object)
  129. """Qt dock widget for generating a tilted slab mask (always shown as Labels)."""
  130. def __init__(self, napari_viewer: "napari.Viewer"):
  131. super().__init__()
  132. self.viewer = napari_viewer
  133. self.setWindowTitle("Tilted slab mask (Labels)")
  134. self._last_mask = None
  135. form = QFormLayout()
  136. # Volume size
  137. form.addRow(self._row_label("Volume size"))
  138. self.nx = QSpinBox(); self.nx.setRange(1, 10000); self.nx.setValue(682)
  139. self.ny = QSpinBox(); self.ny.setRange(1, 10000); self.ny.setValue(682)
  140. self.nz = QSpinBox(); self.nz.setRange(1, 10000); self.nz.setValue(292)
  141. form.addRow("nx", self.nx)
  142. form.addRow("ny", self.ny)
  143. form.addRow("nz", self.nz)
  144. # Slab geometry
  145. form.addRow(self._row_label("Slab geometry"))
  146. self.thickness = QSpinBox(); self.thickness.setRange(1, 10000); self.thickness.setValue(120)
  147. self.thickness.setSingleStep(1)
  148. form.addRow("thickness (px)", self.thickness)
  149. # center_z (always explicit; no checkbox)
  150. self.center_z = QDoubleSpinBox()
  151. self.center_z.setDecimals(3)
  152. self.center_z.setRange(-1e6, 1e6)
  153. self.center_z.setSingleStep(1)
  154. self.center_z.setValue((self.nz.value() - 1) / 2.0)
  155. form.addRow("center_z", self.center_z)
  156. # Tilts
  157. self.tilt_xz = QDoubleSpinBox(); self.tilt_xz.setRange(-180.0, 180.0); self.tilt_xz.setDecimals(3); self.tilt_xz.setValue(0.0)
  158. self.tilt_xz.setSingleStep(0.1)
  159. self.tilt_yz = QDoubleSpinBox(); self.tilt_yz.setRange(-180.0, 180.0); self.tilt_yz.setDecimals(3); self.tilt_yz.setValue(0.0)
  160. self.tilt_yz.setSingleStep(0.1)
  161. form.addRow("tilt_yz_deg (about X)", self.tilt_yz)
  162. form.addRow("tilt_xz_deg (about Y)", self.tilt_xz)
  163. # xy_margin (explicit)
  164. self.xy_margin = QSpinBox(); self.xy_margin.setRange(0, 100000); self.xy_margin.setValue(max(self.nx.value(), self.ny.value()))
  165. form.addRow("xy_margin", self.xy_margin)
  166. # Output
  167. form.addRow(self._row_label("Output"))
  168. # dtype is for internal mask creation; display will always be Labels
  169. self.dtype = QComboBox(); self.dtype.addItems(["uint8", "uint16", "bool"])
  170. form.addRow("compute dtype", self.dtype)
  171. self.layer_name = QComboBox(); self.layer_name.setEditable(True); self.layer_name.setEditText("Tilted slab mask")
  172. self._refresh_layer_name_choices()
  173. form.addRow("layer name", self.layer_name)
  174. # Live controls
  175. self.live = QCheckBox("Live update"); self.live.setChecked(True)
  176. self.update_delay = QSpinBox(); self.update_delay.setRange(0, 2000); self.update_delay.setValue(150)
  177. form.addRow("", self.live)
  178. form.addRow("Update delay (ms)", self.update_delay)
  179. # Generate button
  180. self.btn_generate = QPushButton("Generate mask")
  181. self.btn_generate.clicked.connect(self._start_generation_now)
  182. # USe mask button
  183. self._use_mask_state = False # mirror of the checkbox state that outlives Qt object
  184. self.use_mask = QCheckBox("Use mask in pipeline")
  185. self.use_mask.setChecked(self._use_mask_state)
  186. self.use_mask.toggled.connect(self._on_use_mask_toggled)
  187. form.addRow("", self.use_mask)
  188. # Layout
  189. v = QVBoxLayout(self)
  190. v.addLayout(form)
  191. v.addWidget(self.btn_generate, alignment=Qt.AlignRight)
  192. # Debounce + job tracking
  193. self._debounce = QTimer(self)
  194. self._debounce.setSingleShot(True)
  195. self._debounce.timeout.connect(self._start_generation_now)
  196. self._current_job_id = 0
  197. # Wire live updates
  198. for w in [self.nx, self.ny, self.nz, self.thickness, self.center_z,
  199. self.tilt_xz, self.tilt_yz, self.xy_margin]:
  200. w.valueChanged.connect(self._on_param_changed)
  201. self.dtype.currentTextChanged.connect(self._on_param_changed)
  202. # ---------- helpers ----------
  203. def _on_use_mask_toggled(self, checked: bool):
  204. self._use_mask_state = checked
  205. def get_mask(self):
  206. return self._last_mask if getattr(self, "_use_mask_state", False) else None
  207. def _row_label(self, text: str) -> QLabel:
  208. lab = QLabel(f"<b>{text}</b>")
  209. lab.setTextFormat(Qt.RichText)
  210. return lab
  211. def _refresh_layer_name_choices(self):
  212. suggested = "Tilted slab mask"
  213. names = [lyr.name for lyr in self.viewer.layers]
  214. if suggested not in names:
  215. self.layer_name.addItem(suggested)
  216. for n in names:
  217. self.layer_name.addItem(n)
  218. self.layer_name.setEditText(suggested)
  219. def _find_layer_by_name(self, name: str):
  220. for lyr in self.viewer.layers:
  221. if lyr.name == name:
  222. return lyr
  223. return None
  224. def _collect_params(self):
  225. dtype_map = {"uint8": np.uint8, "uint16": np.uint16, "bool": np.bool_}
  226. return dict(
  227. nx=int(self.nx.value()),
  228. ny=int(self.ny.value()),
  229. nz=int(self.nz.value()),
  230. thickness=int(self.thickness.value()),
  231. center_z=float(self.center_z.value()),
  232. tilt_xz_deg=float(self.tilt_xz.value()),
  233. tilt_yz_deg=float(self.tilt_yz.value()),
  234. xy_margin=int(self.xy_margin.value()),
  235. dtype=dtype_map[self.dtype.currentText()],
  236. )
  237. # ---------- live update wiring ----------
  238. def _on_param_changed(self, *args):
  239. if self.live.isChecked():
  240. self._debounce.start(self.update_delay.value())
  241. def _start_generation_now(self):
  242. params = self._collect_params()
  243. self._current_job_id += 1
  244. job_id = self._current_job_id
  245. @thread_worker
  246. def _compute():
  247. return make_tilted_slab_mask(**params)
  248. worker = _compute()
  249. worker.returned.connect(lambda mask: self._apply_mask(mask, job_id))
  250. worker.errored.connect(self._on_worker_error)
  251. worker.start()
  252. def _on_worker_error(self, exc):
  253. print("Error generating mask:", exc)
  254. # ---------- display always as Labels ----------
  255. def _show_as_labels(self, name: str, mask: np.ndarray):
  256. """
  257. Ensure display is a Labels layer:
  258. - convert to integer (uint8 for boolean, else uint32)
  259. - remove same-named non-Labels layer if present
  260. - update existing Labels layer in place when shape matches
  261. """
  262. if mask.dtype == np.bool_:
  263. mask_disp = mask.astype(np.uint8)
  264. else:
  265. mask_disp = mask.astype(np.uint32)
  266. existing = self._find_layer_by_name(name)
  267. if existing is not None and getattr(existing, "_type_string", "") != "labels":
  268. # Replace non-labels layer with labels
  269. try:
  270. self.viewer.layers.remove(existing)
  271. except Exception:
  272. pass
  273. existing = None
  274. if existing is not None and getattr(existing, "data", None) is not None and np.shape(existing.data) == mask_disp.shape:
  275. existing.data = mask_disp
  276. try:
  277. self.viewer.layers.selection = {existing}
  278. except Exception:
  279. pass
  280. else:
  281. lyr = self.viewer.add_labels(mask_disp, name=name)
  282. try:
  283. self.viewer.layers.selection = {lyr}
  284. except Exception:
  285. pass
  286. def _apply_mask(self, mask: np.ndarray, job_id: int):
  287. # Skip stale results
  288. if job_id != self._current_job_id:
  289. return
  290. self._last_mask = mask
  291. self.mask_updated.emit(mask if self._use_mask_state else None)
  292. name = (self.layer_name.currentText() or "Tilted slab mask").strip()
  293. self._show_as_labels(name, mask)
  294. if mask.ndim == 3:
  295. try:
  296. self.viewer.dims.set_point(0, mask.shape[0] // 2)
  297. except Exception:
  298. pass
  299. #-----------------------End Of Tomo Mask Generator--------------------
  300. #-----------------------Label Selection Widget--------------------
  301. def _format_id_count(label_id: int, count: int) -> str:
  302. # e.g. "ID 7 — 153,204 px"
  303. return f"ID {label_id} — {count:,} px"
  304. class SelectLabelsWidget(QWidget):
  305. """
  306. Napari dock widget to select subset of labels from an input Labels layer.
  307. - Choose a Labels layer (default: 'sorted_labels')
  308. - See list of label IDs (+ pixel counts), filter via search
  309. - Check the IDs you want to keep
  310. - Press 'Create filtered labels' to create a new Labels layer keeping only those IDs
  311. (others set to 0)
  312. Pipeline access:
  313. - widget.get_filtered_labels() -> np.ndarray or None (if toggle off or nothing created yet)
  314. - widget.filtered_labels_updated (Signal(object)) -> emits np.ndarray or None on creation
  315. """
  316. filtered_labels_updated = Signal(object) # np.ndarray OR None
  317. def __init__(self, napari_viewer: "napari.Viewer"):
  318. super().__init__()
  319. self.viewer = napari_viewer
  320. self.setWindowTitle("Select & Filter Labels")
  321. # -------- internal state (Qt-safe mirrors) --------
  322. self._use_filtered_state = True
  323. self._last_filtered = None
  324. self._all_ids = np.array([], dtype=np.int64)
  325. self._all_counts = np.array([], dtype=np.int64)
  326. # -------- UI --------
  327. form = QFormLayout()
  328. # Layer picker
  329. self.layer_combo = QComboBox()
  330. self._refresh_layer_combo()
  331. form.addRow("Labels layer", self.layer_combo)
  332. # Optional: target layer name for output
  333. self.output_name = QLineEdit("filtered_labels")
  334. form.addRow("Output layer name", self.output_name)
  335. # Search/filter box
  336. self.search = QLineEdit()
  337. self.search.setPlaceholderText("Filter IDs (e.g., '12', '1-5', '7,10,15-18')")
  338. form.addRow("Search / ranges", self.search)
  339. # IDs list (checkable)
  340. self.list_ids = QListWidget()
  341. self.list_ids.setSelectionMode(QListWidget.ExtendedSelection)
  342. form.addRow(QLabel("<b>Available label IDs</b>"))
  343. form.addRow(self.list_ids)
  344. # Buttons row
  345. btn_row = QHBoxLayout()
  346. self.btn_check_all = QPushButton("Check all")
  347. self.btn_uncheck_all = QPushButton("Uncheck all")
  348. self.btn_invert = QPushButton("Invert")
  349. btn_row.addWidget(self.btn_check_all)
  350. btn_row.addWidget(self.btn_uncheck_all)
  351. btn_row.addWidget(self.btn_invert)
  352. form.addRow(btn_row)
  353. # Live debounce + sampling (optional)
  354. live_row = QHBoxLayout()
  355. self.live_counts = QCheckBox("Auto-refresh IDs")
  356. self.live_counts.setChecked(True)
  357. self.refresh_delay = QSpinBox()
  358. self.refresh_delay.setRange(0, 2000)
  359. self.refresh_delay.setValue(150)
  360. live_row.addWidget(self.live_counts)
  361. live_row.addWidget(QLabel("Delay (ms)"))
  362. live_row.addWidget(self.refresh_delay)
  363. form.addRow(live_row)
  364. # Use in pipeline toggle (controls get_filtered_labels() & signal payload)
  365. self.use_in_pipeline = QCheckBox("Use filtered labels in pipeline")
  366. self.use_in_pipeline.setChecked(self._use_filtered_state)
  367. self.use_in_pipeline.toggled.connect(self._on_use_toggled)
  368. form.addRow("", self.use_in_pipeline)
  369. # Create button
  370. self.btn_create = QPushButton("Create filtered labels")
  371. form.addRow(self.btn_create)
  372. # Layout
  373. root = QVBoxLayout(self)
  374. root.addLayout(form)
  375. # -------- timers & connections --------
  376. self._debounce = QTimer(self)
  377. self._debounce.setSingleShot(True)
  378. self._debounce.timeout.connect(self._compute_unique_in_background)
  379. # Wiring
  380. self.layer_combo.currentTextChanged.connect(self._on_layer_changed)
  381. self.search.textChanged.connect(self._apply_filter_to_list)
  382. self.btn_check_all.clicked.connect(lambda: self._set_all_checked(True))
  383. self.btn_uncheck_all.clicked.connect(lambda: self._set_all_checked(False))
  384. self.btn_invert.clicked.connect(self._invert_checks)
  385. self.btn_create.clicked.connect(self._create_filtered_labels)
  386. # Initial populate
  387. self._schedule_refresh()
  388. # -------------------- Public API --------------------
  389. def get_filtered_labels(self):
  390. """Return latest filtered labels (np.ndarray) or None if disabled/none yet."""
  391. return self._last_filtered if getattr(self, "_use_filtered_state", False) else None
  392. # -------------------- Internal helpers --------------------
  393. def _on_use_toggled(self, checked: bool):
  394. self._use_filtered_state = checked
  395. def _refresh_layer_combo(self):
  396. self.layer_combo.clear()
  397. names = []
  398. for lyr in self.viewer.layers:
  399. # only Labels layers
  400. if getattr(lyr, "_type_string", "") == "labels":
  401. names.append(lyr.name)
  402. # Prefer "sorted_labels" if present
  403. if "sorted_labels" in names:
  404. names.remove("sorted_labels")
  405. names.insert(0, "sorted_labels")
  406. self.layer_combo.addItems(names)
  407. def _get_selected_labels_layer(self):
  408. name = self.layer_combo.currentText().strip()
  409. if not name:
  410. return None
  411. for lyr in self.viewer.layers:
  412. if lyr.name == name:
  413. return lyr
  414. return None
  415. def _schedule_refresh(self):
  416. if self.live_counts.isChecked():
  417. self._debounce.start(self.refresh_delay.value())
  418. else:
  419. self._compute_unique_in_background()
  420. def _on_layer_changed(self, _):
  421. self._schedule_refresh()
  422. def _compute_unique_in_background(self):
  423. layer = self._get_selected_labels_layer()
  424. if layer is None:
  425. self._set_id_list([], [])
  426. return
  427. data = layer.data # numpy integer array
  428. # Compute unique IDs (excluding 0) in a worker
  429. @thread_worker
  430. def _compute():
  431. ids, counts = np.unique(data, return_counts=True)
  432. # Drop background 0
  433. m = ids != 0
  434. return ids[m].astype(np.int64, copy=False), counts[m].astype(np.int64, copy=False)
  435. worker = _compute()
  436. worker.returned.connect(lambda tup: self._on_unique_ready(*tup))
  437. worker.errored.connect(lambda e: print("Unique compute error:", e))
  438. worker.start()
  439. def _on_unique_ready(self, ids: np.ndarray, counts: np.ndarray):
  440. self._all_ids = ids
  441. self._all_counts = counts
  442. self._populate_list(ids, counts)
  443. self._apply_filter_to_list() # respect current search text
  444. def _set_id_list(self, ids, counts):
  445. self._all_ids = np.asarray(ids, dtype=np.int64)
  446. self._all_counts = np.asarray(counts, dtype=np.int64)
  447. self._populate_list(self._all_ids, self._all_counts)
  448. def _populate_list(self, ids: np.ndarray, counts: np.ndarray):
  449. self.list_ids.blockSignals(True)
  450. self.list_ids.clear()
  451. for _id, cnt in zip(ids, counts):
  452. item = QListWidgetItem(_format_id_count(int(_id), int(cnt)))
  453. item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
  454. item.setCheckState(Qt.Unchecked)
  455. item.setData(Qt.UserRole, int(_id)) # store the raw label id
  456. self.list_ids.addItem(item)
  457. self.list_ids.blockSignals(False)
  458. def _apply_filter_to_list(self):
  459. """Filter visible items by search string; also tick ranges if typed (optional UX)."""
  460. text = self.search.text().strip()
  461. # Parse ranges like "1-5,7,10-12"
  462. targets = self._parse_ranges(text) if text else None
  463. for i in range(self.list_ids.count()):
  464. item = self.list_ids.item(i)
  465. label_id = item.data(Qt.UserRole)
  466. visible = True
  467. if text:
  468. # visible if it matches text OR in parsed targets
  469. visible = (str(label_id).find(text) != -1) or (targets and label_id in targets)
  470. item.setHidden(not visible)
  471. # Optionally, auto-check ranges the user typed:
  472. if targets:
  473. for i in range(self.list_ids.count()):
  474. item = self.list_ids.item(i)
  475. if item.data(Qt.UserRole) in targets:
  476. item.setCheckState(Qt.Checked)
  477. @staticmethod
  478. def _parse_ranges(s: str):
  479. """
  480. Turn "1-3,7,10-12" into a set{1,2,3,7,10,11,12}.
  481. Ignores malformed tokens.
  482. """
  483. result = set()
  484. for tok in re.split(r"[,\s]+", s):
  485. if not tok:
  486. continue
  487. if "-" in tok:
  488. try:
  489. a, b = tok.split("-")
  490. a, b = int(a), int(b)
  491. if a <= b:
  492. result.update(range(a, b + 1))
  493. else:
  494. result.update(range(b, a + 1))
  495. except Exception:
  496. pass
  497. else:
  498. try:
  499. result.add(int(tok))
  500. except Exception:
  501. pass
  502. return result
  503. def _set_all_checked(self, checked: bool):
  504. state = Qt.Checked if checked else Qt.Unchecked
  505. for i in range(self.list_ids.count()):
  506. self.list_ids.item(i).setCheckState(state)
  507. def _invert_checks(self):
  508. for i in range(self.list_ids.count()):
  509. item = self.list_ids.item(i)
  510. item.setCheckState(Qt.Unchecked if item.checkState() == Qt.Checked else Qt.Checked)
  511. def _gather_checked_ids(self):
  512. ids = []
  513. for i in range(self.list_ids.count()):
  514. item = self.list_ids.item(i)
  515. if item.checkState() == Qt.Checked:
  516. ids.append(int(item.data(Qt.UserRole)))
  517. return np.array(sorted(ids), dtype=np.int64)
  518. def _create_filtered_labels(self):
  519. layer = self._get_selected_labels_layer()
  520. if layer is None:
  521. print("No Labels layer selected.")
  522. self._emit_filtered(None)
  523. return
  524. keep_ids = self._gather_checked_ids()
  525. if keep_ids.size == 0:
  526. print("No IDs checked → emitting None and not creating a layer.")
  527. self._emit_filtered(None)
  528. return
  529. data = layer.data
  530. # Build filtered labels: keep selected IDs, others -> 0
  531. # Fast with np.isin
  532. mask = np.isin(data, keep_ids)
  533. filtered = np.where(mask, data, 0).astype(np.uint32, copy=False)
  534. # Create or update target layer
  535. out_name = (self.output_name.text().strip() or "filtered_labels")
  536. existing = self._find_layer_by_name(out_name)
  537. if existing is not None and getattr(existing, "_type_string", "") != "labels":
  538. # replace non-labels
  539. try: self.viewer.layers.remove(existing)
  540. except Exception: pass
  541. existing = None
  542. if existing is not None and getattr(existing, "data", None) is not None and np.shape(existing.data) == filtered.shape:
  543. existing.data = filtered
  544. else:
  545. self.viewer.add_labels(filtered, name=out_name)
  546. # Store & emit for pipeline
  547. self._last_filtered = filtered # store the actual array
  548. self._emit_filtered(filtered)
  549. def _emit_filtered(self, arr):
  550. payload = arr if self._use_filtered_state else None
  551. self.filtered_labels_updated.emit(payload)
  552. def _find_layer_by_name(self, name: str):
  553. for lyr in self.viewer.layers:
  554. if lyr.name == name:
  555. return lyr
  556. return None
  557. #-----------------End Of Label Selection Widget--------------------
  558. def make_tilted_slab_mask_old(
  559. nx: int = 682,
  560. ny: int = 682,
  561. nz: int = 292,
  562. thickness: int = 20,
  563. center_z: float = None,
  564. tilt_xz_deg: float = 0.0, # rotation about Y (tilt in XZ)
  565. tilt_yz_deg: float = 0.0, # rotation about X (tilt in YZ)
  566. xy_margin: int = None,
  567. dtype=np.uint8,
  568. ):
  569. """
  570. Build a big rectangular slab (very large in X/Y, finite 'thickness' along its normal),
  571. tilt it in XZ and YZ, center it at (Xmid, Ymid, center_z), and rasterize into a (nz,ny,nx) mask.
  572. Notes on conventions:
  573. - Array shape for MRC is (Z,Y,X) = (nz, ny, nx).
  574. - We treat 'height' as center_z (in pixel index units, 0..nz-1).
  575. - Positive tilt_xz_deg rotates about +Y (right-handed), i.e., tilts the slab in the XZ plane.
  576. - Positive tilt_yz_deg rotates about +X (right-handed), i.e., tilts the slab in the YZ plane.
  577. - The slab is huge in X and Y: half-widths default to max(nx, ny, nz) + xy_margin.
  578. """
  579. if center_z is None:
  580. center_z = (nz - 1) / 2.0
  581. if xy_margin is None:
  582. # Big enough to always cover; tweak if you like.
  583. xy_margin = max(nx, ny) # one extra volume width on each side
  584. # Half-extents of the slab in its own coordinate frame.
  585. hx = max(nx, ny, nz) + xy_margin
  586. hy = max(nx, ny, nz) + xy_margin
  587. hz = thickness / 2.0
  588. # Precompute 2D grids for X and Y (to keep memory small)
  589. x_coords = np.arange(nx, dtype=np.float32)
  590. y_coords = np.arange(ny, dtype=np.float32)
  591. Xv, Yv = np.meshgrid(x_coords, y_coords, indexing='xy') # shape (ny, nx)
  592. X0 = Xv - (nx - 1) / 2.0 # center in X at mid-volume
  593. Y0 = Yv - (ny - 1) / 2.0 # center in Y at mid-volume
  594. # Angles and their sines/cosines (radians)
  595. beta = math.radians(tilt_xz_deg) # about Y
  596. alpha = math.radians(tilt_yz_deg) # about X
  597. cosb, sinb = math.cos(beta), math.sin(beta)
  598. cosa, sina = math.cos(alpha), math.sin(alpha)
  599. # We want local slab coords u = R^T * v, where:
  600. # R = R_y(beta) @ R_x(alpha)
  601. # So R^T =
  602. # [[ cosb, 0, -sinb ],
  603. # [ sinb*sina, cosa, cosb*sina ],
  604. # [ sinb*cosa, -sina, cosb*cosa ]]
  605. #
  606. # Given v = [x0, y0, z0]^T, compute:
  607. # x' = cosb * x0 - sinb * z0
  608. # y' = (sinb*sina) * x0 + cosa * y0 + (cosb*sina) * z0
  609. # z' = (sinb*cosa) * x0 - sina * y0 + (cosb*cosa) * z0
  610. mask = np.zeros((nz, ny, nx), dtype=dtype)
  611. # Loop over slices to keep memory reasonable
  612. for z in range(nz):
  613. z0 = float(z) - float(center_z)
  614. # Compute the three local coordinates for this z-slice
  615. Xp = cosb * X0 - sinb * z0
  616. Yp = (sinb * sina) * X0 + cosa * Y0 + (cosb * sina) * z0
  617. Zp = (sinb * cosa) * X0 - sina * Y0 + (cosb * cosa) * z0
  618. slab = (np.abs(Zp) <= hz) & (np.abs(Xp) <= hx) & (np.abs(Yp) <= hy)
  619. mask[z, :, :] = slab.astype(dtype)
  620. return mask
  621. def save_mask_mrc(mask, out_path):
  622. # Write MRC: mrcfile expects shape (Z, Y, X)
  623. with mrcfile.new(out_path, overwrite=True) as mrc:
  624. mrc.set_data(mask)
  625. def load_tomogram(tomogram_path):
  626. with mrcfile.open(tomogram_path, permissive=True) as mrc:
  627. tomo = mrc.data.copy()
  628. return tomo
  629. def load_segmentation(segmentation_path):
  630. with mrcfile.open(segmentation_path, permissive=True) as mrc:
  631. data = mrc.data.copy()
  632. return data
  633. def component_printer(labeled_sorted):
  634. max_val = np.max(labeled_sorted)
  635. i = 1
  636. while i < max_val + 1:
  637. print(f"component {i}: size: {np.sum(labeled_sorted == i)}")
  638. i += 1
  639. def component_sorter(segmentation):
  640. binary_data = (segmentation > 0).astype(np.int32)
  641. labeled, num_features = label(binary_data)
  642. sizes = np.bincount(labeled.ravel())
  643. K = len(sizes) - 1
  644. if K <= 0:
  645. raise ValueError("No foreground components found.")
  646. # Indices 0..K-1 correspond to labels 1..K
  647. idx = np.arange(K)
  648. # Stable descending sort by size via negative sizes + mergesort (stable)
  649. order_idx = np.argsort(-sizes[1:], kind="mergesort") # values in 0..K-1
  650. order_labels = order_idx + 1 # convert to labels 1..K
  651. # --- Step 6: Build mapping (0 stays 0; largest -> 1; ...; smallest -> K) ---
  652. mapping = np.zeros(K + 1, dtype=np.int32) # length = max_label + 1
  653. mapping[order_labels] = np.arange(1, K + 1, dtype=np.int32)
  654. # Apply mapping
  655. labeled_sorted = mapping[labeled]
  656. return labeled_sorted
  657. def label_saver(labeled_sorted,
  658. output_path):
  659. with mrcfile.new(output_path, overwrite=True) as mrc_out:
  660. mrc_out.set_data(labeled_sorted.astype(np.int8))
  661. def threshold_finder(data):
  662. diffs = [data[i] - data[i + 1] for i in range(len(data) - 1)]
  663. # Find the position of the largest gap
  664. max_gap_index = diffs.index(max(diffs))
  665. threshold = (data[max_gap_index] + data[max_gap_index + 1]) / 2
  666. print("Threshold:", threshold)
  667. def plot_component_sizes(segmentation,title = None):
  668. """
  669. Plot histogram/bar chart of component sizes in a relabeled segmentation.
  670. Background (label 0) is ignored.
  671. """
  672. # Count pixels per label
  673. counts = np.bincount(segmentation.ravel())
  674. if len(counts) <= 1:
  675. print("No components found (only background).")
  676. return
  677. # Skip background count (index 0)
  678. labels = np.arange(1, len(counts))
  679. sizes = counts[1:]
  680. # Plot
  681. plt.figure(figsize=(8, 4))
  682. plt.bar(labels, sizes)
  683. plt.xlabel("Component label")
  684. plt.xticks(labels)
  685. plt.ylabel("Size (pixels)")
  686. if title is None:
  687. plt.title("Component sizes")
  688. else:
  689. plt.title(title)
  690. plt.tight_layout()
  691. plt.show()
  692. def loaded_segmentation_sorter(loaded_segmentation,
  693. threshold_size):
  694. labeled_sorted = component_sorter(loaded_segmentation)
  695. labeled_sorted = remove_small_objects_skimage(segmentation=labeled_sorted,
  696. size=threshold_size)
  697. return labeled_sorted
  698. def remove_small_objects_skimage(segmentation, size):
  699. # skimage's remove_small_objects supports labeled images if `mask is None`
  700. cleaned = remove_small_objects(segmentation, min_size=size, connectivity=1)
  701. relabeled, _, _ = relabel_sequential(cleaned) # makes labels contiguous
  702. return relabeled
  703. def get_roots_stripping_suffix(directory, suffix = "_mito.mrc"):
  704. roots = []
  705. for f in Path(directory).iterdir():
  706. if f.is_file() and f.name.endswith(suffix):
  707. root = f.name.removesuffix(suffix)
  708. roots.append(root)
  709. return roots
  710. def fuse_to_one(segmentation: np.ndarray, labels_to_fuse) -> np.ndarray:
  711. labels_to_fuse = np.asarray(list(labels_to_fuse), dtype=segmentation.dtype)
  712. mask = np.isin(segmentation, labels_to_fuse)
  713. return mask.astype(np.uint8) # 1 for fused, 0 otherwise
  714. def input_labels(prompt="Enter labels separated by space (to keep. They will be merged. (k) if no fusion is needed): "):
  715. raw = input(prompt)
  716. if raw.strip().lower() == 'k':
  717. return ["k"]
  718. else:
  719. return [int(x) for x in raw.split()]
  720. def sort_roots(name_core, roots):
  721. """
  722. Sort roots like 'corr_L_pace_<NN>_ts_<XXX>' numerically by NN and XXX.
  723. """
  724. def key_fn(root):
  725. # Extract the two numbers (NN and XXX)
  726. m = re.search(rf"{name_core}_(\d+)_ts_(\d+)", root)
  727. if m:
  728. return (int(m.group(1)), int(m.group(2)))
  729. return (float('inf'), float('inf')) # fallback if pattern missing
  730. return sorted(roots, key=key_fn)
  731. def napari_viewer_old(tomogram,
  732. segmentation,
  733. tomo_mask=None,
  734. tomogram_name="tomogram",
  735. segmentation_name="labels_sorted",
  736. tomo_mask_name="tomo_mask",
  737. tomo_visible = True,
  738. segmentation_visible = True,
  739. tomo_mask_visible = True):
  740. viewer = napari.Viewer()
  741. viewer.add_image(tomogram, name=tomogram_name, visible=tomo_visible)
  742. viewer.add_labels(segmentation, name=segmentation_name, visible=segmentation_visible)
  743. if tomo_mask is not None:
  744. viewer.add_labels(tomo_mask, name=tomo_mask_name, visible=tomo_mask_visible)
  745. viewer.dims.ndisplay = 2
  746. napari.run()
  747. def napari_viewer_tomo_mask_widget(tomo_loaded,
  748. labeled_sorted):
  749. viewer = napari.Viewer()
  750. viewer.add_image(tomo_loaded, name='tomo', visible=True)
  751. viewer.add_labels(labeled_sorted, name='seg', visible=True)
  752. w = TiltedSlabWidget(viewer)
  753. viewer.window.add_dock_widget(w, area="right")
  754. napari.run()
  755. mask = w.get_mask()
  756. return mask
  757. def napari_viewer_selection_widget(tomo_loaded,
  758. labeled_sorted):
  759. viewer = napari.Viewer()
  760. viewer.add_image(tomo_loaded, name='tomo', visible=True)
  761. viewer.add_labels(labeled_sorted, name="sorted_labels")
  762. w = SelectLabelsWidget(viewer)
  763. viewer.window.add_dock_widget(w, area="right")
  764. napari.run()
  765. filtered_labeled_sorted = w.get_filtered_labels() # returns np.ndarray or None (respects toggle)
  766. return filtered_labeled_sorted
  767. def binarize_labels(labels: np.ndarray) -> np.ndarray:
  768. return (labels > 0).astype(np.uint8)
  769. def main_function_widgets(membrain_segmentation,
  770. isonet_tomogram,
  771. tomo_root,
  772. threshold_size=10000,
  773. binarize = True,
  774. via_tomo_mask_generation = True,
  775. generate_tomo_mask_only = False):
  776. tomo = load_tomogram(tomogram_path=isonet_tomogram)
  777. segmentation = load_segmentation(segmentation_path=membrain_segmentation)
  778. filtered_labeled_sorted = None
  779. #1. Tomo Mask Creation
  780. if via_tomo_mask_generation:
  781. labeled_sorted = loaded_segmentation_sorter(loaded_segmentation=segmentation,
  782. threshold_size=threshold_size)
  783. plot_component_sizes(labeled_sorted, tomo_root)
  784. tomo_mask = napari_viewer_tomo_mask_widget(tomo,labeled_sorted)
  785. if tomo_mask is not None:
  786. labeled_sorted = tomo_mask*labeled_sorted
  787. labeled_sorted = loaded_segmentation_sorter(loaded_segmentation=labeled_sorted,
  788. threshold_size=threshold_size)
  789. else:
  790. print("No tomo mask needed")
  791. else:
  792. labeled_sorted = loaded_segmentation_sorter(loaded_segmentation=segmentation,
  793. threshold_size=threshold_size)
  794. tomo_mask = None
  795. # 2. Selection part
  796. if not generate_tomo_mask_only:
  797. filtered_labeled_sorted = napari_viewer_selection_widget(tomo,
  798. labeled_sorted)
  799. if filtered_labeled_sorted is not None:
  800. if binarize:
  801. filtered_labeled_sorted = binarize_labels(filtered_labeled_sorted)
  802. else:
  803. print("No labels layer selected.")
  804. return tomo_mask, labeled_sorted, filtered_labeled_sorted
  805. def ensure_dir_exists(path):
  806. if not os.path.exists(path):
  807. os.makedirs(path)
  808. def get_corr_roots(name_core, directory):
  809. """
  810. Return unique roots like 'corr_L_pace_<NN>_ts_<XXX>' for files whose names
  811. start with that pattern, ignoring any suffixes/extensions.
  812. """
  813. # look-ahead: next char is '_' or '.' or end-of-string
  814. pat = re.compile(rf"^({name_core}_(\d+)_ts_(\d+))(?=(?:[_\.]|$))", re.IGNORECASE)
  815. roots, seen = [], set()
  816. for p in Path(directory).iterdir():
  817. if not p.is_file():
  818. continue
  819. m = pat.match(p.name)
  820. if m:
  821. root = m.group(1)
  822. if root not in seen:
  823. seen.add(root)
  824. roots.append(root)
  825. return roots
  826. if __name__ == "__main__":
  827. dataset_id = 5
  828. tomo_id = 10
  829. via_tomo_mask_generation = True
  830. generate_tomo_mask_only = False
  831. if dataset_id == 5:
  832. name_core = 'mmm'
  833. path_to_reconstruction_dir = "/run/user/1000/gvfs/smb-share:server=mattei.embl.de,share=icem/bekbayev/selected_fluor"
  834. organelle_suffix = "_mito"
  835. organelle_folder_name = 'mito'
  836. existing_mito_folder = os.path.join(path_to_reconstruction_dir, 'masks', organelle_folder_name)
  837. if dataset_id == 5:
  838. if tomo_id == 1:
  839. tomo_roots_list = ['mmm142_ts_006']
  840. threshold_value = '-3.0'
  841. if tomo_id == 2:
  842. tomo_roots_list = ['mmm145_ts_002']
  843. threshold_value = '-2.0'
  844. if tomo_id == 3:
  845. tomo_roots_list = ['mmm156_ts_004']
  846. threshold_value = '-3.0'
  847. if tomo_id == 4:
  848. tomo_roots_list = ['mmm159_ts_005']
  849. threshold_value = '-3.0'
  850. if tomo_id == 5:
  851. tomo_roots_list = ['mmm164_ts_005']
  852. threshold_value = '-2.0'
  853. if tomo_id == 6:
  854. tomo_roots_list = ['mmm165_ts_007']
  855. threshold_value = '-2.0'
  856. if tomo_id == 7:
  857. tomo_roots_list = ['mmm167_ts_003']
  858. threshold_value = '-3.0'
  859. if tomo_id == 8:
  860. tomo_roots_list = ['mmm167_ts_004']
  861. threshold_value = '-2.0'
  862. if tomo_id == 9:
  863. tomo_roots_list = ['mmm175_ts_007']
  864. threshold_value = '-3.0'
  865. if tomo_id == 10:
  866. tomo_roots_list = ['mmm177_ts_003']
  867. threshold_value = '0.0'
  868. membrain_suffix = f'_3round.mrc'
  869. tomo_suffix = '_14.34Apx_corrected.mrc'
  870. membrain_dir = os.path.join(path_to_reconstruction_dir, 'masks', '3round')
  871. isonet_tomo_dir = os.path.join(path_to_reconstruction_dir, 'isonet/corrected_tomos')
  872. results_folder = os.path.join(path_to_reconstruction_dir, 'masks')
  873. ensure_dir_exists(results_folder)
  874. organelle_folder = os.path.join(results_folder, organelle_folder_name)
  875. ensure_dir_exists(organelle_folder)
  876. if dataset_id == 4:
  877. already_processed = get_roots_stripping_suffix(os.path.join(path_to_reconstruction_dir, 'masks'),
  878. "_tomomoask.mrc")
  879. for tomo_root in tomo_roots_list:
  880. seg_path = os.path.join(membrain_dir, tomo_root + membrain_suffix)
  881. tomo_file = os.path.join(isonet_tomo_dir, tomo_root + tomo_suffix)
  882. tomo_mask, labeled_sorted, fused_labels = main_function_widgets(seg_path,
  883. tomo_file,
  884. tomo_root,
  885. via_tomo_mask_generation=via_tomo_mask_generation,
  886. generate_tomo_mask_only = generate_tomo_mask_only)
  887. ###outputs
  888. tomo_mask_out = os.path.join(results_folder, tomo_root + '_tomomoask' + '.mrc')
  889. labeled_sorted_out = os.path.join(results_folder, tomo_root + '_sorted_label' + '.mrc')
  890. fused_labels_out = os.path.join(organelle_folder, tomo_root + organelle_suffix + '.mrc')
  891. ###outputs end
  892. # WRITING
  893. if tomo_mask is not None:
  894. save_mask_mrc(tomo_mask, tomo_mask_out)
  895. print(f"Wrote {tomo_mask_out}")
  896. else:
  897. print(f"{tomo_root}: Tomo mask is not needed")
  898. label_saver(labeled_sorted, labeled_sorted_out)
  899. print(f"Wrote {labeled_sorted_out}")
  900. if fused_labels is not None:
  901. label_saver(fused_labels, fused_labels_out)
  902. print(f"Wrote {fused_labels_out}")
  903. else:
  904. print(f"{tomo_root}: No fused labels needed")

mask_creator_live_20251203_fluor_selected_selection_mito.py at commit d3eac27, under MIT · at the source

Overview

Authors: J. Tabitha Hees1, Inmaculada Segura1, Andrea Schneider1, Martina Schifferer2,3, Sultan Bekbayev4, Jana Lindner1, Simone Mattei4,5, Thomas Misgeld2,3,6, Angelika B. Harbauer1,3,6
  1. Max Planck Institute for Biological Intelligence,Martinsried, Germany
  2. German Center for Neurodegenerative Diseases,Munich, Germany
  3. Munich Cluster for Systems Neurology,Munich, Germany
  4. European Molecular Biology Laboratory, Molecular Systems Biology Unit,Heidelberg, Germany
  5. European Molecular Biology Laboratory, EMBL Imaging Centre,Heidelberg, Germany
  6. Technical University of Munich, School of Medicine and Health, Institute of Neuronal Cell Biology,Munich, Germany
Journal: Nature communications, volume 17, issue 1, article 11877
Dates: received 10 February 2026; accepted 28 October 2026; published online 20 November 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1038/s41467-026-79754-5 · PMID 43064719 · PMCID PMC13788209 · OpenAlex W4399934791
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: human (organism), mouse (organism), Parkinson's (population), cellular / molecular (subfield)
Methods: Statistics, Connectivity, Evoked potentials, fMRI & imaging, Smoothing, state filtering, decompositions
Keywords: Organelles, Cell death, Cellular neuroscience
MeSH: Endoplasmic Reticulum*, Mitophagy*, Neurons*, Protein Kinases*, Animals, HSP40 Heat-Shock Proteins, Humans, Mice, Mitochondria, Molecular Chaperones, Protein Biosynthesis, PTEN-Induced Putative Kinase, RNA, Messenger (* major topic)
Topic: Autophagy in Disease and Therapy (Cell Biology, Biochemistry, Genetics and Molecular Biology), according to OpenAlex
Funding: Deutsche Forschungsgemeinschaft (TRR353 – ID 471011418, SPP ID 541742535, EXC 2145 SyNergy – ID 390857198, SPP2453 project number 541626282, Mi 694/8-1, FOR Immunostroke (Mi 694/9-1/2 – ID 428663564, TRR 274/1 Projects C02, Z01, respectively (ID 408885537, INST95/1755-1 FUGG, ID 518284373); Max-Planck-Gesellschaft (Max Planck Society) (MPRGL Harbauer); European Research Council (ERC StG Project 101077138 — MitoPIP)
Citations: not cited yet (Europe PMC); 71 references in the paper

Abstract

Given the large size of neurons, local maintenance of mitochondria is crucial to counteract insults to this organelle in axons and dendrites. The Parkinson-related mitochondrial kinase PINK1 plays a central role in mitochondrial quality control, which in neurons requires the transport of Pink1 mRNA by mitochondrial hitch-hiking. However, how and where PINK1 is locally translated and processed has remained unclear. Using live-cell imaging, we trace local PINK1 translation sites and preprotein dynamics, revealing a concerted interplay between mitochondria and the ER, with endolysosomes frequently localized adjacent to the site of translation. Upon metabolically regulated untethering from mitochondria, Pink1 mRNA relocates to ribosomes in proximity to the ER and endolysosomes for translation of the PINK1 preprotein. The ER chaperone DNAJB6 shields the PINK1 preprotein in transit to mitochondria, following the post-translational ER-SURF pathway. Consequently, loss of DNAJB6 leads to persistent ER/endolysosome-associated PINK1 precursor stores and failure of mitophagy upon mitochondrial damage. Our findings reveal that neuronal PINK1 protein translation switches between mitochondrially anchored co-translational and ER-associated post-translational import states, with functional implications for mitochondrial quality control.

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 1 match between paragraphs and lines of code.

embl-ic/mattei-research

License: MIT
State: the link answers, verified on 23 November 2026
Evidence: files inventoried
Commit: d3eac27ea855339d69bbc29b77cc4ece7444c934, 18 November 2026
Languages: Python (3)
Size: 8 files, 3 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, license file
Not found: CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (2 files), Matplotlib (1 file), napari (1 file), pandas (1 file), Pillow (1 file), scikit-image (1 file), SciPy (1 file)
Availability: 1 check, the latest on 23 November 2026: the link answers
  • 23 November 2026: the link answers
5 files

Code availability

A custom software tool for organelle annotation was used and is available under

https://github.com/embl-ic/mattei-research/tree/main/harbauer_paper.

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;
  • 3 scripts, each with its path and the digest of its content;
  • 1 match 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

All data supporting the findings of this study are available within the article and Supplementary Information. Source data are provided with this paper. Microscopy data, constructs and unique reagents reported in this paper will be shared by the lead contact Angelika B. Harbauer upon reasonable request. Source data are provided with this paper.

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, 23 November 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 9 authors, 3 keywords, 13 MeSH terms, 3 funders, 71 references, 5 RRIDs.

Cite

This paper

Hees, J. T., Segura, I., Schneider, A., Schifferer, M., Bekbayev, S., Lindner, J., Mattei, S., Misgeld, T., & Harbauer, A. B. (2026). ER-associated biogenesis of PINK1 preprotein for neuronal mitophagy. Nature communications, 17(1), 11877. https://doi.org/10.1038/s41467-026-79754-5

BibTeX

@article{hees2026er,
author = {Hees, J. Tabitha and Segura, Inmaculada and Schneider, Andrea and Schifferer, Martina and Bekbayev, Sultan and Lindner, Jana and Mattei, Simone and Misgeld, Thomas and Harbauer, Angelika B.},
title = {{ER-associated biogenesis of PINK1 preprotein for neuronal mitophagy}},
journal = {Nature communications},
year = {2026},
month = nov,
volume = {17},
number = {1},
pages = {11877},
publisher = {Nature Publishing Group},
issn = {2041-1723},
doi = {10.1038/s41467-026-79754-5},
url = {https://doi.org/10.1038/s41467-026-79754-5},
pmid = {43064719},
pmcid = {PMC13788209}
}

RIS

TY - JOUR
AU - Hees, J. Tabitha
AU - Segura, Inmaculada
AU - Schneider, Andrea
AU - Schifferer, Martina
AU - Bekbayev, Sultan
AU - Lindner, Jana
AU - Mattei, Simone
AU - Misgeld, Thomas
AU - Harbauer, Angelika B.
TI - ER-associated biogenesis of PINK1 preprotein for neuronal mitophagy
T2 - Nature communications
J2 - Nat Commun
PY - 2026
DA - 2026/11/20
VL - 17
IS - 1
SP - 11877
SN - 2041-1723
PB - Nature Publishing Group
DO - 10.1038/s41467-026-79754-5
UR - https://doi.org/10.1038/s41467-026-79754-5
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41467-026-79754-5",
"type": "article-journal",
"title": "ER-associated biogenesis of PINK1 preprotein for neuronal mitophagy",
"container-title": "Nature communications",
"author": [
{
"family": "Hees",
"given": "J. Tabitha"
},
{
"family": "Segura",
"given": "Inmaculada"
},
{
"family": "Schneider",
"given": "Andrea"
},
{
"family": "Schifferer",
"given": "Martina"
},
{
"family": "Bekbayev",
"given": "Sultan"
},
{
"family": "Lindner",
"given": "Jana"
},
{
"family": "Mattei",
"given": "Simone"
},
{
"family": "Misgeld",
"given": "Thomas"
},
{
"family": "Harbauer",
"given": "Angelika B."
}
],
"container-title-short": "Nat Commun",
"volume": "17",
"issue": "1",
"page": "11877",
"DOI": "10.1038/s41467-026-79754-5",
"PMID": "43064719",
"PMCID": "PMC13788209",
"ISSN": "2041-1723",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41467-026-79754-5",
"language": "en",
"issued": {
"date-parts": [
[
2026,
11,
20
]
]
}
}

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.15252/embr.202256399 [code]
PARK15/FBXO7 is dispensable for PINK1/Parkin mitophagy in iNeurons and HeLa cell systems.
Journal: EMBO reports
In common: scikit-image, pandas, SciPy, 2 other tools, Parkinson's, cellular / molecular, 11 references
[2] doi:10.1073/pnas.2313540121 [code]
Tom20 gates PINK1 activity and mediates its tethering of the TOM and TIM23 translocases upon mitochondrial stress.
Journal: Proceedings of the National Academy of Sciences of the United States of America
In common: Parkinson's, cellular / molecular, 11 references
[3] doi:10.1038/s41556-024-01544-2 [code]
FMRP regulates MFF translation to locally direct mitochondrial fission in neurons.
Journal: Nature cell biology
In common: SciPy, Matplotlib, NumPy, mouse, cellular / molecular, 9 references
[4] doi:10.7554/elife.90565 [code]
Combining array tomography with electron tomography provides insights into leakiness of the blood-brain barrier in mouse cortex.
Journal: eLife
In common: mouse, 3 references, 2 authors
[5] doi:10.1038/s41593-025-02123-w
A fully iPS-cell-derived 3D model of the human blood-brain barrier for exploring neurovascular disease mechanisms and therapeutic interventions.
Journal: Nature neuroscience
In common: mouse, cellular / molecular, 2 references, 2 authors
[6] doi:10.1080/15548627.2022.2151294
Substitution of PINK1 Gly411 modulates substrate receptivity and turnover.
Journal: Autophagy
In common: Parkinson's, cellular / molecular, 7 references
[7] doi:10.26508/lsa.202603630 [code]
Locally synthesized glycyl aminoacyl-tRNA synthetase is important for local translation in neurons.
Journal: Life science alliance
In common: pandas, NumPy, mouse, cellular / molecular, 7 references
[8] doi:10.1083/jcb.202402169 [code]
CryoVesNet: A dedicated framework for synaptic vesicle segmentation in cryo-electron tomograms.
Journal: The Journal of cell biology
In common: napari, scikit-image, pandas, 3 other tools, cellular / molecular, 3 references
[9] doi:10.1038/s41593-025-02136-5 [code]
The stroke risk gene Foxf2 maintains brain endothelial cell function via Tie2 signaling.
Journal: Nature neuroscience
In common: pandas, SciPy, Matplotlib, 1 other tool, mouse, cellular / molecular, 1 reference, author Martina Schifferer
[10] doi:10.1038/s41467-024-55055-7 [code]
Localized molecular chaperone synthesis maintains neuronal dendrite proteostasis.
Journal: Nature communications
In common: scikit-image, Pillow, pandas, 3 other tools, mouse, cellular / molecular, 3 references

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.1038/s41467-026-79754-5.svg)](https://openscicode.org/badge/doi/10.1038/s41467-026-79754-5)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1038/s41467-026-79754-5.svg
   :target: https://openscicode.org/badge/doi/10.1038/s41467-026-79754-5
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1038/s41467-026-79754-5"><img src="https://openscicode.org/badge/doi/10.1038/s41467-026-79754-5.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.