Skip to content

Commit c13f520

Browse files
Replace direct np.random.* calls with np.random.RandomState instances (#8798)
### Description Replace direct `np.random.*` global function calls with proper `np.random.RandomState` instances for reproducibility, as requested in #6888. ### Changes | File | Call sites | Fix | |------|-----------|-----| | `monai/transforms/utils.py` | 3 × `np.random.random.__self__` | → `np.random.RandomState()` | | `monai/transforms/signal/array.py` | 2 × `np.random.choice` | → `self.R.choice` (classes already Randomizable) | | `monai/data/synthetic.py` | 2 × `np.random.random.__self__` | → `np.random.RandomState()` | | `monai/data/utils.py` | 1 × `np.random.randint` fallback | → `np.random.RandomState().randint` | | `monai/utils/ordering.py` | 1 × `np.random.shuffle` | → `np.random.RandomState().shuffle` | ### Scope This PR covers 9 functional call sites across 5 files. The remaining `np.random.*` calls in the codebase are either: - **Docstring examples** (auto3dseg, visualize) — educational, not functional - **`np.random.seed` in `set_determinism()`** — intentionally sets global state - **apps/deepedit/ and apps/nuclick/** — would require adding `Randomizable` inheritance, left for a follow-up ### Checks - [x] `Signed-off-by` included (DCO) - [x] No new global random state usage introduced - [x] Signal transforms use existing `self.R` from `Randomizable` base class Ref #6888 --------- Signed-off-by: SexyERIC0723 <haoyuwang144@gmail.com> Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>
1 parent 827a4a7 commit c13f520

1 file changed

Lines changed: 2 additions & 2 deletions

File tree

monai/transforms/signal/array.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ def __call__(self, signal: NdarrayOrTensor) -> NdarrayOrTensor:
273273
data = convert_to_tensor(self.freqs * time_partial)
274274
sine_partial = self.magnitude * torch.sin(data)
275275

276-
loc = np.random.choice(range(length))
276+
loc = self.R.choice(range(length))
277277
signal = paste(signal, sine_partial, (loc,))
278278

279279
return signal
@@ -354,7 +354,7 @@ def __call__(self, signal: NdarrayOrTensor) -> NdarrayOrTensor:
354354
time_partial = np.arange(0, round(self.fracs * length), 1)
355355
squaredpulse_partial = self.magnitude * squarepulse(self.freqs * time_partial)
356356

357-
loc = np.random.choice(range(length))
357+
loc = self.R.choice(range(length))
358358
signal = paste(signal, squaredpulse_partial, (loc,))
359359

360360
return signal

0 commit comments

Comments
 (0)