Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions monai/transforms/croppad/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,8 @@ def pad_nd(
return _np_pad(img, pad_width=to_pad, mode=mode, **kwargs)
try:
_pad = _np_pad
if mode in {"constant", "reflect", "edge", "replicate", "wrap", "circular"} and img.dtype not in {
torch.int16,
torch.int64,
torch.bool,
torch.uint8,
}:
if mode in {"constant", "reflect", "edge", "replicate", "wrap", "circular"}:
# Try PyTorch pad for these modes; fallback to NumPy on error.
_pad = _pt_pad
return _pad(img, pad_width=to_pad, mode=mode, **kwargs)
except (ValueError, TypeError, RuntimeError) as err:
Expand Down
58 changes: 58 additions & 0 deletions tests/transforms/croppad/test_pad_nd_dtypes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from __future__ import annotations

from unittest.mock import Mock, patch

import pytest
import torch

import monai.transforms.croppad.functional as F
from monai.transforms.croppad.functional import pad_nd

Comment on lines +1 to +22
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Add module docstring.

Per coding guidelines, all modules should have docstrings describing their purpose.

🔎 Suggested module docstring
 # limitations under the License.
 
+"""
+Tests for pad_nd dtype support and backend selection.
+Validates PyTorch padding preference and NumPy fallback behavior.
+"""
 
 from __future__ import annotations

As per coding guidelines, docstrings are required for all definitions.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
from unittest.mock import Mock, patch
import pytest
import torch
import monai.transforms.croppad.functional as F
from monai.transforms.croppad.functional import pad_nd
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Tests for pad_nd dtype support and backend selection.
Validates PyTorch padding preference and NumPy fallback behavior.
"""
from __future__ import annotations
from unittest.mock import Mock, patch
import pytest
import torch
import monai.transforms.croppad.functional as F
from monai.transforms.croppad.functional import pad_nd
🤖 Prompt for AI Agents
In tests/transforms/croppad/test_pad_nd_dtypes.py lines 1 to 22, the module is
missing a top-level docstring; add a concise module-level docstring at the very
top (immediately after the future import or before any imports if preferred)
that states the test module’s purpose (e.g., verifies pad_nd behavior across
dtypes), any important context, and optionally references related functions
under test; keep it short, one or two sentences, and follow project docstring
style.


def test_pad_uses_pt_for_bool():
img = torch.ones((1, 4, 4), dtype=torch.bool)
to_pad = [(0, 0), (1, 1), (2, 2)]
with patch.object(F, "_pt_pad", wraps=F._pt_pad) as mock_pt, patch.object(F, "_np_pad", wraps=F._np_pad) as mock_np:
out = pad_nd(img, to_pad, mode="constant", value=0)

assert mock_pt.called
assert not mock_np.called
assert out.dtype == img.dtype
Comment on lines +24 to +32
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Add function docstring.

Per coding guidelines, test functions should have docstrings describing what they test.

🔎 Suggested docstring
 def test_pad_uses_pt_for_bool():
+    """Test that pad_nd uses PyTorch backend for bool dtype in constant mode."""
     img = torch.ones((1, 4, 4), dtype=torch.bool)

As per coding guidelines, docstrings are required for all definitions.

🤖 Prompt for AI Agents
In tests/transforms/croppad/test_pad_nd_dtypes.py around lines 24 to 32, the
test function test_pad_uses_pt_for_bool lacks a docstring; add a one-line
docstring immediately below the def line that succinctly states what the test
verifies (e.g., that padding boolean tensors uses the PyTorch implementation and
preserves dtype) so it follows the project's docstring guideline for test
functions.



def test_pad_falls_back_to_np_if_pt_raises():
img = torch.ones((1, 4, 4), dtype=torch.bool)
to_pad = [(0, 0), (1, 1), (2, 2)]
with (
patch.object(F, "_pt_pad", new=Mock(side_effect=NotImplementedError("no"))) as mock_pt,
patch.object(F, "_np_pad", wraps=F._np_pad) as mock_np,
):
out = pad_nd(img, to_pad, mode="constant", value=0)

assert mock_pt.called
assert mock_np.called
assert out.dtype == img.dtype
Comment on lines +35 to +46
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Add function docstring.

Per coding guidelines, test functions should have docstrings.

🔎 Suggested docstring
 def test_pad_falls_back_to_np_if_pt_raises():
+    """Test that pad_nd falls back to NumPy when PyTorch raises NotImplementedError."""
     img = torch.ones((1, 4, 4), dtype=torch.bool)

As per coding guidelines, docstrings are required for all definitions.

🤖 Prompt for AI Agents
In tests/transforms/croppad/test_pad_nd_dtypes.py around lines 35 to 46, the
test function test_pad_falls_back_to_np_if_pt_raises is missing a docstring; add
a concise one-line docstring immediately under the def line that explains the
purpose of the test (e.g., that PyTorch padding fallback to NumPy is exercised
and dtype is preserved), keeping it brief and following project docstring style.



@pytest.mark.parametrize(
"dtype", [torch.bool, torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.float32]
)
def test_pad_dtype_no_error_and_dtype_preserved(dtype):
img = torch.ones((1, 4, 4), dtype=dtype)
to_pad = [(0, 0), (1, 1), (2, 2)]
out = pad_nd(img, to_pad, mode="constant", value=0)

assert out.shape == (1, 6, 8)
assert out.dtype == img.dtype
Comment on lines +49 to +58
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Add function docstring.

Per coding guidelines, test functions should have docstrings.

🔎 Suggested docstring
 @pytest.mark.parametrize(
     "dtype", [torch.bool, torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.float32]
 )
 def test_pad_dtype_no_error_and_dtype_preserved(dtype):
+    """Test that pad_nd handles various dtypes without error and preserves dtype."""
     img = torch.ones((1, 4, 4), dtype=dtype)

As per coding guidelines, docstrings are required for all definitions.

🤖 Prompt for AI Agents
In tests/transforms/croppad/test_pad_nd_dtypes.py around lines 49 to 58, the
test function test_pad_dtype_no_error_and_dtype_preserved is missing a
docstring; add a concise one-line docstring immediately beneath the def that
states the test verifies pad_nd accepts various dtypes without error and
preserves the input dtype and shape (e.g., "Verify pad_nd does not error for
various dtypes and preserves dtype and output shape.").

Loading