Temporarily set all MapTransforms to not throw an error if keys are missing. After, revert to original states. Args: transform: either MapTransform or a Compose Example: .. code-block:: python data = {"image": np.arange(16, dtype=float).reshape(1, 4, 4)} t = S
(transform: MapTransform | Compose | tuple[MapTransform] | tuple[Compose])
| 1718 | |
| 1719 | @contextmanager |
| 1720 | def allow_missing_keys_mode(transform: MapTransform | Compose | tuple[MapTransform] | tuple[Compose]): |
| 1721 | """Temporarily set all MapTransforms to not throw an error if keys are missing. After, revert to original states. |
| 1722 | |
| 1723 | Args: |
| 1724 | transform: either MapTransform or a Compose |
| 1725 | |
| 1726 | Example: |
| 1727 | |
| 1728 | .. code-block:: python |
| 1729 | |
| 1730 | data = {"image": np.arange(16, dtype=float).reshape(1, 4, 4)} |
| 1731 | t = SpatialPadd(["image", "label"], 10, allow_missing_keys=False) |
| 1732 | _ = t(data) # would raise exception |
| 1733 | with allow_missing_keys_mode(t): |
| 1734 | _ = t(data) # OK! |
| 1735 | """ |
| 1736 | # If given a sequence of transforms, Compose them to get a single list |
| 1737 | if issequenceiterable(transform): |
| 1738 | transform = Compose(transform) |
| 1739 | |
| 1740 | # Get list of MapTransforms |
| 1741 | transforms = [] |
| 1742 | if isinstance(transform, MapTransform): |
| 1743 | transforms = [transform] |
| 1744 | elif isinstance(transform, Compose): |
| 1745 | # Only keep contained MapTransforms |
| 1746 | transforms = [t for t in transform.flatten().transforms if isinstance(t, MapTransform)] |
| 1747 | if len(transforms) == 0: |
| 1748 | raise TypeError( |
| 1749 | "allow_missing_keys_mode expects either MapTransform(s) or Compose(s) containing MapTransform(s)" |
| 1750 | ) |
| 1751 | |
| 1752 | # Get the state of each `allow_missing_keys` |
| 1753 | orig_states = [t.allow_missing_keys for t in transforms] |
| 1754 | |
| 1755 | try: |
| 1756 | # Set all to True |
| 1757 | for t in transforms: |
| 1758 | t.allow_missing_keys = True |
| 1759 | yield |
| 1760 | finally: |
| 1761 | # Revert |
| 1762 | for t, o_s in zip(transforms, orig_states): |
| 1763 | t.allow_missing_keys = o_s |
| 1764 | |
| 1765 | |
| 1766 | _interp_modes = list(InterpolateMode) + list(GridSampleMode) |
searching dependent graphs…