Skip to content

Commit 27fe67c

Browse files
Jammy2211Jammy2211claude
authored
refactor: vectorize k x s segment-id construction (#362 refactor exercise) (#365)
The per-pixel python loop becomes pure numpy (repeat/cumsum/divmod on the flat sample index): cold construction 62 ms -> 9.7 ms on a 3000-pixel adaptive mask (cached repeat calls unchanged at ~80 us). Exact same ids as the loop on adaptive references; suite unchanged. Behaviour-preserving; closes the library leg of the k x s refactor exercise. The operate/image call-site pattern was reviewed and left as-is (clean two-step seam); no PyAutoGalaxy edits needed. Co-authored-by: Jammy2211 <JNightingale2211@gmail.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
1 parent 4ed7472 commit 27fe67c

1 file changed

Lines changed: 16 additions & 8 deletions

File tree

autoarray/operators/over_sampling/over_sample_util.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -181,14 +181,22 @@ def _convolve_bin_segment_ids_cached(
181181
f"sizes {np.unique(sub_size[sub_size % s != 0])} are not."
182182
)
183183

184-
segment_ids = np.empty(int(np.sum(sub_size**2)), dtype="int64")
185-
186-
offset = 0
187-
for p, n in enumerate(sub_size):
188-
k = n // s
189-
rows, cols = np.divmod(np.arange(n * n), n)
190-
segment_ids[offset : offset + n * n] = p * s**2 + (rows // k) * s + (cols // k)
191-
offset += n * n
184+
# Vectorized construction: for every sample, its pixel index p, position
185+
# within the pixel's n_p x n_p block, and fine cell (row // k_p) * s + col // k_p.
186+
counts = sub_size**2
187+
n_samples = int(np.sum(counts))
188+
189+
pixel_of_sample = np.repeat(np.arange(sub_size.shape[0]), counts)
190+
block_starts = np.concatenate(([0], np.cumsum(counts)[:-1]))
191+
within = np.arange(n_samples) - block_starts[pixel_of_sample]
192+
193+
n_of_sample = sub_size[pixel_of_sample]
194+
k_of_sample = n_of_sample // s
195+
rows, cols = np.divmod(within, n_of_sample)
196+
197+
segment_ids = (
198+
pixel_of_sample * s**2 + (rows // k_of_sample) * s + (cols // k_of_sample)
199+
)
192200

193201
segment_ids.setflags(write=False)
194202
return segment_ids

0 commit comments

Comments
 (0)