1use std::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive};
31
32use ruxla_ir::{GatherScatterMode, ScatterDims, Shape};
33use ruxla_kernels::{BinaryOp, Element};
34
35use crate::backend::Backend;
36use crate::lax;
37use crate::value::{Array, ArrayLike, Int, Num, Scalar};
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct Slice {
43 pub start: Option<i64>,
45 pub stop: Option<i64>,
47 pub step: i64,
49}
50
51impl Slice {
52 pub fn new(start: Option<i64>, stop: Option<i64>) -> Self {
54 Self {
55 start,
56 stop,
57 step: 1,
58 }
59 }
60
61 #[track_caller]
67 pub fn step(self, step: i64) -> Self {
68 assert_ne!(step, 0, "the step of a slice must not be zero");
69 Self { step, ..self }
70 }
71
72 fn indices(&self, size: usize) -> (i64, i64, i64) {
75 let size = size as i64;
76 let (lo, hi) = if self.step > 0 {
77 (0, size)
78 } else {
79 (-1, size - 1)
80 };
81 let resolve = |v: Option<i64>, default: i64| match v {
82 None => default,
83 Some(v) if v < 0 => (v + size).clamp(lo, hi),
84 Some(v) => v.clamp(lo, hi),
85 };
86 if self.step > 0 {
87 (resolve(self.start, 0), resolve(self.stop, size), self.step)
88 } else {
89 (
90 resolve(self.start, size - 1),
91 resolve(self.stop, -1),
92 self.step,
93 )
94 }
95 }
96
97 fn start_and_size(&self, size: usize) -> (i64, usize) {
99 let (start, stop, step) = self.indices(size);
100 if step < 0 {
101 let new_start = stop + 1 + (start - stop - 1).abs() % step.abs();
102 (new_start, (start + 1 - new_start).max(0) as usize)
103 } else {
104 (start, (stop - start).max(0) as usize)
105 }
106 }
107}
108
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub struct NewAxis;
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct Ellipsis;
116
117#[derive(Clone, Copy, Debug)]
119pub enum Index<B: Backend> {
120 Int(i64),
122 Slice(Slice),
124 Dynamic(Scalar<B, i32>),
126 NewAxis,
128 Ellipsis,
130}
131
132macro_rules! int_index {
133 ($($t:ty)*) => {$(
134 impl<B: Backend> From<$t> for Index<B> {
135 #[inline]
136 fn from(i: $t) -> Self {
137 Index::Int(i64::try_from(i).expect("index out of range"))
138 }
139 }
140 )*};
141}
142int_index!(i32 i64 isize u32 usize);
143
144macro_rules! range_index {
145 ($($t:ty)*) => {$(
146 impl<B: Backend> From<Range<$t>> for Index<B> {
147 #[inline]
148 fn from(r: Range<$t>) -> Self {
149 Index::Slice(Slice::new(Some(r.start as i64), Some(r.end as i64)))
150 }
151 }
152 impl<B: Backend> From<RangeFrom<$t>> for Index<B> {
153 #[inline]
154 fn from(r: RangeFrom<$t>) -> Self {
155 Index::Slice(Slice::new(Some(r.start as i64), None))
156 }
157 }
158 impl<B: Backend> From<RangeTo<$t>> for Index<B> {
159 #[inline]
160 fn from(r: RangeTo<$t>) -> Self {
161 Index::Slice(Slice::new(None, Some(r.end as i64)))
162 }
163 }
164 impl<B: Backend> From<RangeInclusive<$t>> for Index<B> {
165 #[inline]
166 fn from(r: RangeInclusive<$t>) -> Self {
167 let end = *r.end() as i64;
168 Index::Slice(Slice::new(Some(*r.start() as i64), if end == -1 { None } else { Some(end + 1) }))
169 }
170 }
171 impl<B: Backend> From<RangeToInclusive<$t>> for Index<B> {
172 #[inline]
173 fn from(r: RangeToInclusive<$t>) -> Self {
174 let end = r.end as i64;
175 Index::Slice(Slice::new(None, if end == -1 { None } else { Some(end + 1) }))
176 }
177 }
178 )*};
179}
180range_index!(i32 i64 usize);
181
182impl<B: Backend> From<RangeFull> for Index<B> {
183 #[inline]
184 fn from(_: RangeFull) -> Self {
185 Index::Slice(Slice::new(None, None))
186 }
187}
188impl<B: Backend> From<Slice> for Index<B> {
189 #[inline]
190 fn from(s: Slice) -> Self {
191 Index::Slice(s)
192 }
193}
194impl<B: Backend> From<NewAxis> for Index<B> {
195 #[inline]
196 fn from(_: NewAxis) -> Self {
197 Index::NewAxis
198 }
199}
200impl<B: Backend> From<Ellipsis> for Index<B> {
201 #[inline]
202 fn from(_: Ellipsis) -> Self {
203 Index::Ellipsis
204 }
205}
206impl<B: Backend, I: Int> From<Scalar<B, I>> for Index<B> {
207 #[inline]
208 fn from(s: Scalar<B, I>) -> Self {
209 Index::Dynamic(s.cast::<i32>())
210 }
211}
212
213const INLINE_INDICES: usize = 4;
215
216#[derive(Clone, Debug)]
218pub struct Indices<B: Backend>(IndexList<B>);
219
220#[derive(Clone)]
224enum IndexList<B: Backend> {
225 Inline {
226 len: usize,
227 items: [std::mem::MaybeUninit<Index<B>>; INLINE_INDICES],
228 },
229 Heap(Vec<Index<B>>),
230}
231
232impl<B: Backend> std::fmt::Debug for IndexList<B> {
233 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234 f.debug_list().entries(Indices::slice(self)).finish()
235 }
236}
237
238impl<B: Backend> Indices<B> {
239 #[inline]
241 pub fn new() -> Self {
242 Indices(IndexList::Inline {
243 len: 0,
244 items: [std::mem::MaybeUninit::uninit(); INLINE_INDICES],
245 })
246 }
247
248 #[inline(always)]
250 pub fn push(&mut self, index: Index<B>) {
251 match &mut self.0 {
252 IndexList::Inline { len, items } if *len < INLINE_INDICES => {
253 items[*len].write(index);
254 *len += 1;
255 }
256 IndexList::Inline { .. } => {
257 let mut v = Self::slice(&self.0).to_vec();
258 v.push(index);
259 self.0 = IndexList::Heap(v);
260 }
261 IndexList::Heap(v) => v.push(index),
262 }
263 }
264}
265
266impl<B: Backend> Indices<B> {
267 #[inline]
269 fn slice(list: &IndexList<B>) -> &[Index<B>] {
270 match list {
271 IndexList::Inline { len, items } => {
272 unsafe { std::slice::from_raw_parts(items.as_ptr().cast::<Index<B>>(), *len) }
276 }
277 IndexList::Heap(v) => v,
278 }
279 }
280}
281
282impl<B: Backend> Default for Indices<B> {
283 fn default() -> Self {
284 Self::new()
285 }
286}
287
288impl<B: Backend> std::ops::Deref for Indices<B> {
289 type Target = [Index<B>];
290 #[inline]
291 fn deref(&self) -> &[Index<B>] {
292 Self::slice(&self.0)
293 }
294}
295
296impl<B: Backend> FromIterator<Index<B>> for Indices<B> {
297 fn from_iter<I: IntoIterator<Item = Index<B>>>(iter: I) -> Self {
298 let mut out = Self::new();
299 for i in iter {
300 out.push(i);
301 }
302 out
303 }
304}
305
306impl<B: Backend> IntoIndices<B> for Indices<B> {
307 #[inline]
308 fn into_indices(self) -> Indices<B> {
309 self
310 }
311}
312
313pub trait IntoIndices<B: Backend> {
315 fn into_indices(self) -> Indices<B>;
317}
318
319impl<B: Backend, T: Into<Index<B>>> IntoIndices<B> for T {
320 #[inline]
321 fn into_indices(self) -> Indices<B> {
322 let mut out = Indices::new();
323 out.push(self.into());
324 out
325 }
326}
327
328macro_rules! tuple_indices {
329 ($($t:ident),+) => {
330 impl<B: Backend, $($t: Into<Index<B>>),+> IntoIndices<B> for ($($t,)+) {
331 #[allow(non_snake_case)]
333 #[inline]
334 fn into_indices(self) -> Indices<B> {
335 let ($($t,)+) = self;
336 let mut out = Indices::new();
337 $(out.push($t.into());)+
338 out
339 }
340 }
341 };
342}
343tuple_indices!(A);
344tuple_indices!(A, C);
345tuple_indices!(A, C, D);
346tuple_indices!(A, C, D, E);
347tuple_indices!(A, C, D, E, F);
348tuple_indices!(A, C, D, E, F, G);
349
350#[track_caller]
352fn expand<B: Backend>(indices: Indices<B>, ndim: usize) -> Indices<B> {
353 let consumed = indices
354 .iter()
355 .filter(|i| matches!(i, Index::Int(_) | Index::Slice(_) | Index::Dynamic(_)))
356 .count();
357 assert!(
358 consumed <= ndim,
359 "too many indices: {consumed} for an array of rank {ndim}"
360 );
361 let ellipses = indices
362 .iter()
363 .filter(|i| matches!(i, Index::Ellipsis))
364 .count();
365 assert!(ellipses <= 1, "an index can have only one ellipsis");
366 let whole = || Index::Slice(Slice::new(None, None));
367 let mut out = Indices::new();
368 let mut seen = false;
369 for &i in indices.iter() {
370 if matches!(i, Index::Ellipsis) {
371 (0..ndim - consumed).for_each(|_| out.push(whole()));
372 seen = true;
373 } else {
374 out.push(i);
375 }
376 }
377 if !seen {
378 (0..ndim - consumed).for_each(|_| out.push(whole()));
379 }
380 out
381}
382
383fn finish<B: Backend, T: Element>(
385 x: Array<B, T>,
386 squeeze: &[usize],
387 new_axes: &[usize],
388) -> Array<B, T> {
389 let mut x = x;
390 if !squeeze.is_empty() {
391 let dims: Shape = x
392 .shape()
393 .iter()
394 .enumerate()
395 .filter(|(i, _)| !squeeze.contains(i))
396 .map(|(_, &d)| d)
397 .collect();
398 x = x.reshape(dims);
399 }
400 if !new_axes.is_empty() {
401 let shape = x.shape();
402 let rank = shape.rank() + new_axes.len();
403 let mut kept = 0..;
404 let mut out = Vec::with_capacity(rank);
405 let mut dims = Vec::new();
406 for i in 0..rank {
407 if new_axes.contains(&i) {
408 out.push(1);
409 } else {
410 out.push(shape[kept.next().expect("counted")]);
411 dims.push(i);
412 }
413 }
414 x = lax::broadcast_in_dim(&x, out, &dims);
415 }
416 x
417}
418
419impl<B: Backend, T: Element> Array<B, T> {
420 #[track_caller]
425 #[inline]
426 pub fn i(&self, index: impl IntoIndices<B>) -> Array<B, T> {
427 let indices = index.into_indices();
428 if B::FAST_PATHS
429 && let Some(shape) = B::dims(&self.0)
430 {
431 if let Some(x) = self.static_element(&indices, shape) {
432 return x.to_array();
433 }
434 if let Some(x) = self.leading_rows(&indices, shape) {
435 return x;
436 }
437 if let Some(x) = self.box_index(&indices, shape) {
438 return x;
439 }
440 }
441 self.index_general(indices, self.shape())
442 }
443
444 fn box_index(&self, indices: &[Index<B>], shape: &[usize]) -> Option<Array<B, T>> {
448 const MAX: usize = 8;
449 let rank = shape.len();
450 if rank > MAX || indices.len() > rank {
451 return None;
452 }
453 let (mut starts, mut sizes) = ([0usize; MAX], [0usize; MAX]);
454 let mut out = Shape::scalar();
455 for d in 0..rank {
456 match indices.get(d) {
457 None => {
458 sizes[d] = shape[d];
459 out.push(shape[d]);
460 }
461 Some(&Index::Int(i)) => {
462 let n = shape[d] as i64;
463 let j = if i < 0 { i + n } else { i };
464 if j < 0 || j >= n {
465 return None;
466 }
467 (starts[d], sizes[d]) = (j as usize, 1);
468 }
469 Some(Index::Slice(s)) => {
470 let (start, size) = s.start_and_size(shape[d]);
471 if s.step != 1 || start < 0 {
472 return None;
473 }
474 (starts[d], sizes[d]) = (start as usize, size);
475 out.push(size);
476 }
477 _ => return None,
478 }
479 }
480 B::slice_box::<T>(&self.0, &starts[..rank], &sizes[..rank], out).map(Array)
481 }
482
483 #[inline]
488 fn leading_rows(&self, indices: &[Index<B>], shape: &[usize]) -> Option<Array<B, T>> {
489 const MAX: usize = 8;
490 if indices.is_empty() || indices.len() >= shape.len() || indices.len() > MAX {
491 return None;
492 }
493 let mut at = [0usize; MAX];
494 for ((p, index), &size) in at.iter_mut().zip(indices).zip(shape) {
495 *p = match *index {
496 Index::Int(i) => {
497 let j = if i < 0 { i + size as i64 } else { i };
498 if j < 0 || j >= size as i64 {
499 return None;
500 }
501 j as usize
502 }
503 Index::Dynamic(s) if size > 0 => {
504 let i = B::int_value(s.0)?;
505 let j = if i < 0 { i + size as i64 } else { i };
506 j.clamp(0, size as i64 - 1) as usize
507 }
508 _ => return None,
509 };
510 }
511 B::index_leading::<T>(&self.0, &at[..indices.len()]).map(Array)
512 }
513
514 #[track_caller]
517 fn index_general(&self, indices: Indices<B>, shape: Shape) -> Array<B, T> {
518 if indices.len() <= shape.rank() && indices.iter().all(|i| matches!(i, Index::Int(_))) {
519 return self.int_index(&indices, &shape);
520 }
521 let indices = expand(indices, shape.rank());
522 if indices.iter().any(|i| matches!(i, Index::Dynamic(_))) {
523 self.dynamic_index(&indices, &shape)
524 } else {
525 self.static_index(&indices, &shape)
526 }
527 }
528
529 #[track_caller]
535 #[inline]
536 pub fn get(&self, index: impl IntoIndices<B>) -> Scalar<B, T> {
537 let indices = index.into_indices();
538 if B::FAST_PATHS
539 && let Some(shape) = B::dims(&self.0)
540 && let Some(x) = self.static_element(&indices, shape)
541 {
542 return x;
543 }
544 self.get_general(indices)
545 }
546
547 #[cold]
548 #[inline(never)]
549 #[track_caller]
550 fn get_general(&self, indices: Indices<B>) -> Scalar<B, T> {
551 self.i(indices).to_scalar()
552 }
553
554 #[inline(always)]
558 fn static_element(&self, indices: &[Index<B>], shape: &[usize]) -> Option<Scalar<B, T>> {
559 if indices.len() != shape.len() {
560 return None;
561 }
562 let mut flat = 0usize;
563 for (index, &size) in indices.iter().zip(shape) {
564 let j = match *index {
565 Index::Int(i) => {
566 let j = if i < 0 { i + size as i64 } else { i };
567 if j < 0 || j >= size as i64 {
568 return None;
570 }
571 j
572 }
573 Index::Dynamic(s) if size > 0 => {
577 let i = B::int_value(s.0)?;
578 let j = if i < 0 { i + size as i64 } else { i };
579 j.clamp(0, size as i64 - 1)
580 }
581 _ => return None,
582 };
583 flat = flat * size + j as usize;
584 }
585 B::element::<T>(&self.0, flat).map(Scalar)
586 }
587
588 #[track_caller]
591 fn int_index(&self, indices: &[Index<B>], shape: &[usize]) -> Array<B, T> {
592 let mut starts: Shape = shape.iter().map(|_| 0).collect();
593 let mut limits = Shape::from(shape);
594 for (axis, index) in indices.iter().enumerate() {
595 let Index::Int(i) = *index else {
596 unreachable!("checked by the caller")
597 };
598 let size = shape[axis] as i64;
599 let j = if i < 0 { i + size } else { i };
600 assert!(
601 (0..size).contains(&j),
602 "index {i} is out of bounds for axis {axis} with size {size}"
603 );
604 starts.set(axis, j as usize);
605 limits.set(axis, j as usize + 1);
606 }
607 if B::FAST_PATHS
608 && let Some(r) = B::index_leading::<T>(&self.0, &starts[..indices.len()])
609 {
610 return Array(r);
611 }
612 let trivial = starts.iter().all(|&s| s == 0) && limits[..] == shape[..];
613 let x = if trivial {
614 self.clone()
615 } else {
616 lax::slice(self, &starts, &limits, None)
617 };
618 x.reshape(&shape[indices.len()..])
619 }
620
621 #[track_caller]
622 fn static_index(&self, indices: &[Index<B>], shape: &[usize]) -> Array<B, T> {
623 let (mut starts, mut limits, mut strides) =
625 (Shape::scalar(), Shape::scalar(), Shape::scalar());
626 let (mut rev, mut squeeze, mut new_axes) =
627 (Shape::scalar(), Shape::scalar(), Shape::scalar());
628 let mut axis = 0;
629 for index in indices {
630 match index {
631 Index::NewAxis => new_axes.push(starts.len() - squeeze.len() + new_axes.len()),
632 Index::Int(i) => {
633 let size = shape[axis] as i64;
634 let j = if *i < 0 { i + size } else { *i };
635 assert!(
636 (0..size).contains(&j),
637 "index {i} is out of bounds for axis {axis} with size {size}"
638 );
639 starts.push(j as usize);
640 limits.push(j as usize + 1);
641 strides.push(1);
642 squeeze.push(axis);
643 axis += 1;
644 }
645 Index::Slice(s) => {
646 let size = shape[axis];
647 let (start, stop, step) = s.indices(size);
648 if step < 0 {
649 let new_start =
650 (stop + 1 + (start - stop - 1).abs() % step.abs()).min(size as i64);
651 starts.push(new_start as usize);
652 limits.push(new_start.max(start + 1) as usize);
653 strides.push(step.unsigned_abs() as usize);
654 rev.push(axis);
655 } else {
656 starts.push(start as usize);
657 limits.push(start.max(stop) as usize);
658 strides.push(step as usize);
659 }
660 axis += 1;
661 }
662 Index::Dynamic(_) | Index::Ellipsis => unreachable!("handled before"),
663 }
664 }
665 let trivial = starts.iter().all(|&s| s == 0)
666 && limits.iter().zip(shape).all(|(&l, &n)| l == n)
667 && strides.iter().all(|&s| s == 1);
668 let mut x = if trivial {
669 self.clone()
670 } else {
671 let st = (!strides.iter().all(|&s| s == 1)).then_some(strides);
672 lax::slice(self, &starts, &limits, st.as_deref())
673 };
674 if !rev.is_empty() {
675 x = lax::rev(&x, &rev);
676 }
677 finish(x, &squeeze, &new_axes)
678 }
679
680 #[track_caller]
681 fn dynamic_index(&self, indices: &[Index<B>], shape: &[usize]) -> Array<B, T> {
682 let mut starts: Vec<Scalar<B, i32>> = Vec::new();
683 let mut sizes = Vec::new();
684 let (mut rev, mut squeeze, mut new_axes) = (Vec::new(), Vec::new(), Vec::new());
685 let mut axis = 0;
686 for index in indices {
687 match index {
688 Index::NewAxis => new_axes.push(starts.len() - squeeze.len() + new_axes.len()),
689 Index::Int(_) | Index::Dynamic(_) => {
690 assert!(
691 shape[axis] > 0,
692 "index is out of bounds for axis {axis} with size 0"
693 );
694 starts.push(match index {
695 Index::Int(i) => Scalar::new(*i as i32),
696 Index::Dynamic(s) => *s,
697 _ => unreachable!("matched above"),
698 });
699 sizes.push(1);
700 squeeze.push(axis);
701 axis += 1;
702 }
703 Index::Slice(s) => {
704 assert!(
705 s.step.abs() == 1,
706 "slices with steps other than 1 and -1 cannot be combined with run-time indices"
707 );
708 let (start, n) = s.start_and_size(shape[axis]);
709 if s.step < 0 {
710 rev.push(axis);
711 }
712 starts.push(Scalar::new(start as i32));
713 sizes.push(n);
714 axis += 1;
715 }
716 Index::Ellipsis => unreachable!("handled before"),
717 }
718 }
719 let mut x = lax::dynamic_slice(self, &starts, &sizes);
720 if !rev.is_empty() {
721 x = lax::rev(&x, &rev);
722 }
723 finish(x, &squeeze, &new_axes)
724 }
725
726 #[track_caller]
729 pub fn at(&self, index: impl IntoIndices<B>) -> At<'_, B, T> {
730 At {
731 array: Base::Borrowed(self),
732 indices: index.into_indices(),
733 }
734 }
735
736 #[track_caller]
749 pub fn into_at(self, index: impl IntoIndices<B>) -> At<'static, B, T> {
750 At {
751 array: Base::Owned(self),
752 indices: index.into_indices(),
753 }
754 }
755
756 #[track_caller]
772 pub fn at_mut(&mut self, index: impl IntoIndices<B>) -> AtMut<'_, B, T> {
773 AtMut {
774 array: self,
775 indices: index.into_indices(),
776 }
777 }
778}
779
780fn box_update<B: Backend, T: Element>(
785 x: &mut Array<B, T>,
786 indices: &[Index<B>],
787 values: &Array<B, T>,
788 combine: Option<BinaryOp>,
789) -> bool {
790 const MAX: usize = 8;
791 let Some(shape) = B::dims(&x.0) else {
792 return false;
793 };
794 let rank = shape.len();
795 if rank > MAX || indices.len() > rank {
796 return false;
797 }
798 let (mut starts, mut sizes) = ([0usize; MAX], [0usize; MAX]);
800 let (mut selected, mut n_selected) = ([0usize; MAX], 0);
801 for d in 0..rank {
802 match indices.get(d) {
803 None => {
804 sizes[d] = shape[d];
805 selected[n_selected] = shape[d];
806 n_selected += 1;
807 }
808 Some(&Index::Int(i)) => {
809 let n = shape[d] as i64;
810 let j = if i < 0 { i + n } else { i };
811 if j < 0 || j >= n {
812 return false;
813 }
814 (starts[d], sizes[d]) = (j as usize, 1);
815 }
816 Some(Index::Slice(s)) => {
817 let (start, size) = s.start_and_size(shape[d]);
818 if s.step != 1 || start < 0 {
819 return false;
820 }
821 (starts[d], sizes[d]) = (start as usize, size);
822 selected[n_selected] = size;
823 n_selected += 1;
824 }
825 _ => return false,
826 }
827 }
828 let selected = &selected[..n_selected];
829 let broadcast;
833 let values = if values.size() == 1 || B::dims(&values.0) == Some(selected) {
834 values
835 } else {
836 broadcast = crate::jnp::broadcast_to(values, Shape::from(selected));
837 &broadcast
838 };
839 B::update_box::<T>(
840 &mut x.0,
841 &starts[..rank],
842 &sizes[..rank],
843 &values.0,
844 combine,
845 )
846}
847
848#[derive(Debug)]
850pub struct AtMut<'a, B: Backend, T: Element> {
851 array: &'a mut Array<B, T>,
852 indices: Indices<B>,
853}
854
855impl<B: Backend, T: Element> AtMut<'_, B, T> {
856 #[track_caller]
858 pub fn set(self, values: impl ArrayLike<B, T>) {
859 self.update(values, None);
860 }
861
862 #[allow(clippy::should_implement_trait)]
864 #[track_caller]
865 pub fn add(self, values: impl ArrayLike<B, T>) {
866 self.update(values, Some(BinaryOp::Add));
867 }
868
869 #[allow(clippy::should_implement_trait)]
871 #[track_caller]
872 pub fn mul(self, values: impl ArrayLike<B, T>) {
873 self.update(values, Some(BinaryOp::Mul));
874 }
875
876 #[track_caller]
878 pub fn max(self, values: impl ArrayLike<B, T>) {
879 self.update(values, Some(BinaryOp::Max));
880 }
881
882 #[track_caller]
884 pub fn min(self, values: impl ArrayLike<B, T>) {
885 self.update(values, Some(BinaryOp::Min));
886 }
887
888 #[track_caller]
889 #[inline(always)]
890 fn update(self, values: impl ArrayLike<B, T>, combine: Option<BinaryOp>) {
891 if B::FAST_PATHS
892 && let Some(v) = values.as_scalar()
893 && B::point_update_in_place::<T>(&mut self.array.0, &self.indices, v.0, combine)
894 {
895 return;
896 }
897 self.update_general(values.into_array(), combine);
898 }
899
900 #[track_caller]
903 #[cold]
904 #[inline(never)]
905 fn update_general(self, values: Array<B, T>, combine: Option<BinaryOp>) {
906 if B::FAST_PATHS && box_update(self.array, &self.indices, &values, combine) {
907 return;
908 }
909 let at = At {
910 array: Base::Borrowed(&*self.array),
911 indices: self.indices,
912 };
913 let updated = at.scatter(values, combine);
914 *self.array = updated;
915 }
916}
917
918#[derive(Debug)]
921enum Base<'a, B: Backend, T: Element> {
922 Borrowed(&'a Array<B, T>),
923 Owned(Array<B, T>),
924}
925
926impl<B: Backend, T: Element> std::ops::Deref for Base<'_, B, T> {
927 type Target = Array<B, T>;
928 #[inline]
929 fn deref(&self) -> &Array<B, T> {
930 match self {
931 Base::Borrowed(x) => x,
932 Base::Owned(x) => x,
933 }
934 }
935}
936
937#[derive(Debug)]
939pub struct At<'a, B: Backend, T: Element> {
940 array: Base<'a, B, T>,
941 indices: Indices<B>,
942}
943
944impl<B: Backend, T: Element> At<'_, B, T> {
945 #[track_caller]
947 pub fn get(self) -> Array<B, T> {
948 let shape = self.array.shape();
949 let indices = expand(self.indices, shape.rank());
950 if indices.iter().any(|i| matches!(i, Index::Dynamic(_))) {
951 self.array.dynamic_index(&indices, &shape)
952 } else {
953 self.array.static_index(&indices, &shape)
954 }
955 }
956
957 #[track_caller]
960 pub fn set(self, values: impl ArrayLike<B, T>) -> Array<B, T> {
961 self.scatter(values, None)
962 }
963
964 #[track_caller]
967 pub fn max(self, values: impl ArrayLike<B, T>) -> Array<B, T> {
968 self.scatter(values, Some(BinaryOp::Max))
969 }
970
971 #[track_caller]
974 pub fn min(self, values: impl ArrayLike<B, T>) -> Array<B, T> {
975 self.scatter(values, Some(BinaryOp::Min))
976 }
977
978 #[inline]
981 fn points(x: &Array<B, T>, indices: &[Index<B>]) -> Option<[B::Scalar<i32>; 8]> {
982 let shape = x.shape();
983 if indices.len() != shape.rank() || indices.len() > 8 {
984 return None;
985 }
986 let mut points = [Scalar::<B, i32>::new(0).0; 8];
987 for ((p, index), &size) in points.iter_mut().zip(indices).zip(shape.iter()) {
988 *p = match *index {
989 Index::Int(i) => {
990 Scalar::<B, i32>::new((if i < 0 { i + size as i64 } else { i }) as i32).0
991 }
992 Index::Dynamic(s) => lax::wrap_negative(s, size).0,
993 _ => return None,
994 };
995 }
996 Some(points)
997 }
998
999 #[track_caller]
1002 fn scatter(mut self, values: impl ArrayLike<B, T>, combine: Option<BinaryOp>) -> Array<B, T> {
1003 if B::FAST_PATHS
1004 && let Some(v) = values.as_scalar()
1005 {
1006 let n = self.indices.len();
1007 if let Base::Owned(x) = &mut self.array {
1008 if B::point_update_in_place::<T>(&mut x.0, &self.indices, v.0, combine) {
1009 let Base::Owned(x) = self.array else {
1010 unreachable!("matched above")
1011 };
1012 return x;
1013 }
1014 } else if let Some(points) = Self::points(&self.array, &self.indices) {
1015 let x = &*self.array;
1016 if let Some(r) = B::point_update::<T>(&x.0, &points[..n], &v.to_array().0, combine)
1017 {
1018 return Array(r);
1019 }
1020 }
1021 }
1022 let values = values.into_array();
1023 if B::FAST_PATHS {
1024 let mut x = match self.array {
1025 Base::Owned(x) => x,
1026 Base::Borrowed(x) => x.clone(),
1027 };
1028 if box_update(&mut x, &self.indices, &values, combine) {
1029 return x;
1030 }
1031 return Self {
1032 array: Base::Owned(x),
1033 indices: self.indices,
1034 }
1035 .scatter_general(values, combine);
1036 }
1037 self.scatter_general(values, combine)
1038 }
1039
1040 #[track_caller]
1042 fn scatter_general(self, values: Array<B, T>, combine: Option<BinaryOp>) -> Array<B, T> {
1043 let x = &*self.array;
1044 let shape = x.shape();
1045 let point = self.indices.len() == shape.rank()
1048 && self
1049 .indices
1050 .iter()
1051 .all(|i| matches!(i, Index::Int(_) | Index::Dynamic(_)));
1052 let indices = if point {
1053 self.indices
1054 } else {
1055 expand(self.indices, shape.rank())
1056 };
1057 if B::FAST_PATHS && point && values.size() == 1 {
1058 let mut buf = [Scalar::<B, i32>::new(0).0; 8];
1060 let mut heap = Vec::new();
1061 for (k, (index, &size)) in indices.iter().zip(shape.iter()).enumerate() {
1062 let p = match *index {
1063 Index::Int(i) => {
1064 Scalar::<B, i32>::new((if i < 0 { i + size as i64 } else { i }) as i32).0
1065 }
1066 Index::Dynamic(s) => lax::wrap_negative(s, size).0,
1067 _ => unreachable!("checked above"),
1068 };
1069 if k < buf.len() {
1070 buf[k] = p;
1071 }
1072 heap.extend((indices.len() > buf.len()).then_some(p));
1073 }
1074 let points = if indices.len() <= buf.len() {
1075 &buf[..indices.len()]
1076 } else {
1077 &heap[..]
1078 };
1079 if let Some(r) = B::point_update::<T>(&x.0, points, &values.0, combine) {
1080 return Array(r);
1081 }
1082 }
1083 let mut offset_dims = Vec::new();
1084 let mut collapsed = Vec::new();
1085 let mut start_index_map = Vec::new();
1086 let mut gather_indices: Vec<(Array<B, i32>, usize)> = Vec::new();
1087 let mut gather_shape: Vec<usize> = Vec::new();
1088 let mut slice_shape = Vec::new();
1089 let mut new_axes = Vec::new();
1090 let mut reversed = Vec::new();
1091 let (mut x_axis, mut y_axis, mut collapsed_y) = (0, 0, 0);
1092 for index in indices.iter() {
1093 match index {
1094 Index::Int(_) | Index::Dynamic(_) => {
1095 let size = shape[x_axis];
1096 assert!(
1097 size > 0,
1098 "index is out of bounds for axis {x_axis} with size 0"
1099 );
1100 let i: Scalar<B, i32> = match index {
1101 Index::Int(i) => {
1102 Scalar::new((if *i < 0 { i + size as i64 } else { *i }) as i32)
1103 }
1104 Index::Dynamic(s) => lax::wrap_negative(*s, size),
1106 _ => unreachable!("matched above"),
1107 };
1108 gather_indices.push((i.to_array(), gather_shape.len()));
1109 collapsed.push(x_axis);
1110 start_index_map.push(x_axis);
1111 x_axis += 1;
1112 }
1113 Index::NewAxis => {
1114 slice_shape.push(1);
1115 new_axes.push(y_axis);
1116 y_axis += 1;
1117 }
1118 Index::Slice(s) => {
1119 let size = shape[x_axis];
1120 let (start, stop, step) = s.indices(size);
1121 let n = if step > 0 {
1122 ((stop - start).max(0) as usize).div_ceil(step as usize)
1123 } else {
1124 ((start - stop).max(0) as usize).div_ceil(step.unsigned_abs() as usize)
1125 };
1126 slice_shape.push(n);
1127 if step == 1 {
1128 if n != size {
1129 gather_indices.push((
1130 Scalar::<B, i32>::new(start as i32).to_array(),
1131 gather_shape.len(),
1132 ));
1133 start_index_map.push(x_axis);
1134 }
1135 offset_dims.push(collapsed_y);
1136 } else {
1137 let base = Scalar::<B, i32>::new(start as i32);
1138 let mut idx = lax::iota::<B, i32>([n], 0) * Scalar::new(step as i32) + base;
1139 if step < 0 {
1140 reversed.push(collapsed_y);
1141 idx = lax::rev(&idx, &[0]);
1142 }
1143 gather_indices.push((idx, gather_shape.len()));
1144 start_index_map.push(x_axis);
1145 gather_shape.push(n);
1146 collapsed.push(x_axis);
1147 }
1148 collapsed_y += 1;
1149 y_axis += 1;
1150 x_axis += 1;
1151 }
1152 Index::Ellipsis => unreachable!("handled before"),
1153 }
1154 }
1155 if slice_shape.contains(&0) {
1156 return x.clone();
1157 }
1158 let index_array: Array<B, i32> = match gather_indices.len() {
1159 0 => crate::jnp::zeros([0]),
1160 1 => {
1161 let (g, _) = &gather_indices[0];
1162 let mut s = g.shape().dims().to_vec();
1163 s.push(1);
1164 let dims: Vec<usize> = (0..g.ndim()).collect();
1165 lax::broadcast_in_dim(g, s, &dims)
1166 }
1167 _ => {
1168 let mut full = gather_shape.clone();
1169 full.push(1);
1170 let parts: Vec<Array<B, i32>> = gather_indices
1171 .iter()
1172 .map(|(g, i)| {
1173 let dims: Vec<usize> = (*i..i + g.ndim()).collect();
1174 lax::broadcast_in_dim(g, full.clone(), &dims)
1175 })
1176 .collect();
1177 lax::concatenate(&parts, gather_shape.len())
1178 }
1179 };
1180 collapsed.sort_unstable();
1181 let y = values.broadcast_to(slice_shape);
1182 let mut y = finish(y, &new_axes, &[]);
1183 if !reversed.is_empty() {
1184 y = lax::rev(&y, &reversed);
1185 }
1186 let dims = ScatterDims {
1187 update_window_dims: offset_dims,
1188 inserted_window_dims: collapsed,
1189 scatter_dims_to_operand_dims: start_index_map,
1190 operand_batching_dims: vec![],
1191 scatter_indices_batching_dims: vec![],
1192 };
1193 Array(B::scatter::<T, i32>(
1194 combine,
1195 &x.0,
1196 &index_array.0,
1197 &y.0,
1198 &dims,
1199 GatherScatterMode::FillOrDrop,
1200 true,
1201 ))
1202 }
1203}
1204
1205impl<B: Backend, T: Num> At<'_, B, T> {
1206 #[allow(clippy::should_implement_trait)]
1210 #[track_caller]
1211 pub fn add(self, values: impl ArrayLike<B, T>) -> Array<B, T> {
1212 self.scatter(values, Some(BinaryOp::Add))
1213 }
1214
1215 #[allow(clippy::should_implement_trait)]
1217 #[track_caller]
1218 pub fn mul(self, values: impl ArrayLike<B, T>) -> Array<B, T> {
1219 self.scatter(values, Some(BinaryOp::Mul))
1220 }
1221}