coeus_ops/resize/taps.rs
1//! Resize modes and the tap table that both forward and reverse mode read.
2
3use coeus_core::FloatElement;
4use eunomia::convert::IntegerTarget;
5
6/// Cubic convolution coefficient `a` used by torch's bicubic resize.
7const CUBIC_COEFFICIENT: f64 = -0.75;
8
9/// Resize mode.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum ResizeMode {
12 /// Nearest-neighbour — each output position copies one source position.
13 Nearest,
14 /// Linear (bilinear in 2-D) — each output position blends two source
15 /// positions per spatial axis.
16 Bilinear,
17 /// Cubic (bicubic in 2-D) — four source positions per spatial axis, cubic
18 /// convolution with `a = -0.75`. Weights can be negative, so the result may
19 /// overshoot the source range at edges.
20 Bicubic,
21 /// Area — average of every source element inside the output position's box.
22 Area,
23}
24
25/// Cubic convolution kernel: `|x| <= 1` uses the near lobe, `1 < |x| < 2` the
26/// far lobe, and the tap contributes nothing beyond 2.
27fn cubic(x: f64) -> f64 {
28 let x = x.abs();
29 if x <= 1.0 {
30 (CUBIC_COEFFICIENT + 2.0) * x.powi(3) - (CUBIC_COEFFICIENT + 3.0) * x.powi(2) + 1.0
31 } else if x < 2.0 {
32 CUBIC_COEFFICIENT * x.powi(3) - 5.0 * CUBIC_COEFFICIENT * x.powi(2)
33 + 8.0 * CUBIC_COEFFICIENT * x
34 - 4.0 * CUBIC_COEFFICIENT
35 } else {
36 0.0
37 }
38}
39
40/// Reusable per-axis tap table.
41///
42/// One table per axis is held across the whole resize, so the steady-state loop
43/// allocates nothing, while still allowing [`ResizeMode::Area`] to emit a
44/// variable number of taps (up to the downsample factor).
45#[derive(Default)]
46pub(super) struct TapTable {
47 index: Vec<usize>,
48 weight: Vec<f64>,
49}
50
51impl TapTable {
52 /// Replace the table contents with the taps for one output position.
53 ///
54 /// `out_index` must be less than `out_len`, and `in_len`/`out_len` must be
55 /// non-zero. `scale` is the sampling step in source units per output
56 /// position: `in_len / out_len` for an explicit `size`, but `1 /
57 /// scale_factor` when the caller resized by a factor — torch keeps the
58 /// requested factor rather than recomputing it from the rounded output
59 /// size, so the two differ for a fractional factor.
60 pub(super) fn fill(
61 &mut self,
62 out_index: usize,
63 in_len: usize,
64 out_len: usize,
65 mode: ResizeMode,
66 scale: f64,
67 ) {
68 self.index.clear();
69 self.weight.clear();
70 let half_pixel = (f64::from_count(out_index) + 0.5) * scale;
71 match mode {
72 ResizeMode::Nearest => {
73 // `floor(i * scale)` — no `+ 0.5`. torch's `nearest` kernel
74 // copies the cell the output cell *starts* in, so the two
75 // agree on every integer ratio and diverge as soon as the
76 // ratio is fractional.
77 let source =
78 usize::from_truncated(f64::from_count(out_index) * scale).min(in_len - 1);
79 self.index.push(source);
80 self.weight.push(1.0);
81 }
82 ResizeMode::Bilinear => {
83 // Clamp the source coordinate before splitting it: torch's
84 // `area_pixel_compute_source_index` returns 0 for a negative
85 // source, so a border output reuses the edge element with
86 // weight 1 instead of blending against it fractionally.
87 let source = (half_pixel - 0.5).max(0.0);
88 let lower = source.floor();
89 let lower_index = usize::from_truncated(lower);
90 let upper_weight = source - lower;
91 self.index.push(lower_index);
92 self.weight.push(1.0 - upper_weight);
93 self.index.push((lower_index + 1).min(in_len - 1));
94 self.weight.push(upper_weight);
95 }
96 ResizeMode::Bicubic => {
97 // No clamp here: torch keeps the negative coordinate for cubic
98 // and clamps the four *indices* instead.
99 let source = half_pixel - 0.5;
100 let lower = source.floor();
101 let fraction = source - lower;
102 let lower_index = isize::from_truncated(lower);
103 let last_index =
104 isize::try_from(in_len).expect("invariant: an axis length fits isize") - 1;
105 for tap in 0..4_usize {
106 let offset = isize::try_from(tap).expect("invariant: four taps fit isize");
107 let index = (lower_index - 1 + offset).clamp(0, last_index);
108 self.index.push(
109 usize::try_from(index).expect("invariant: a clamped index is non-negative"),
110 );
111 self.weight
112 .push(cubic(fraction + 1.0 - f64::from_count(tap)));
113 }
114 }
115 ResizeMode::Area => {
116 let start = out_index * in_len / out_len;
117 let end = ((out_index + 1) * in_len).div_ceil(out_len);
118 let weight = 1.0 / f64::from_count(end - start);
119 for index in start..end {
120 self.index.push(index);
121 self.weight.push(weight);
122 }
123 }
124 }
125 }
126
127 /// The current taps, paired with their weights.
128 pub(super) fn iter(&self) -> impl Iterator<Item = (usize, f64)> + '_ {
129 self.index.iter().copied().zip(self.weight.iter().copied())
130 }
131}