Last active
September 21, 2022 15:53
-
-
Save jstorrs/4d8e22b53cbb6412e5355e0c7754efee to your computer and use it in GitHub Desktop.
A decorator to trace pydicom.dataset.Dataset's walk()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pydicom import DataElement, Dataset | |
def trace_sequences(walk_callback): | |
stacks = {} | |
contexts = [] | |
def add_items(parent: Dataset, elem: DataElement) -> None: | |
for item in range(elem.VM): | |
contexts.append((parent, elem, item)) | |
def add_dataset(ds: Dataset) -> None: | |
if stacks: | |
if id(ds) not in stacks: | |
context = contexts.pop(0) | |
parent_stack = stacks[id(context[0])] | |
if parent_stack: | |
stack = (*parent_stack, context) | |
else: | |
stack = (context,) | |
stacks[id(ds)] = stack | |
else: | |
stacks[id(ds)] = None | |
def trace_walk(ds: Dataset, elem: DataElement): | |
add_dataset(ds) | |
if elem.VR == 'SQ': | |
add_items(ds, elem) | |
trace = stacks[id(ds)] | |
walk_callback(ds, elem, trace) | |
return trace_walk |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example use: