radsym 0.1.2

Radial symmetry detection: center proposals, local support analysis, scoring, and refinement
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Annulus sampling for local support extraction.
//!
//! Samples gradient vectors along circular or elliptical annuli around a
//! hypothesis center, producing [`SupportEvidence`] for scoring.

use crate::core::coords::PixelCoord;
use crate::core::geometry::Ellipse;
use crate::core::gradient::GradientField;
use crate::core::scalar::Scalar;

use super::evidence::{GradientSample, SupportEvidence};

/// Configuration for annulus sampling.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AnnulusSamplingConfig {
    /// Number of angular samples around the annulus.
    pub num_angular_samples: usize,
    /// Number of radial samples across the annulus width.
    pub num_radial_samples: usize,
}

impl AnnulusSamplingConfig {
    /// Validate configuration parameters.
    pub fn validate(&self) -> crate::core::error::Result<()> {
        use crate::core::error::RadSymError;
        if self.num_angular_samples < 4 {
            return Err(RadSymError::InvalidConfig {
                reason: "num_angular_samples must be >= 4",
            });
        }
        if self.num_radial_samples < 1 {
            return Err(RadSymError::InvalidConfig {
                reason: "num_radial_samples must be >= 1",
            });
        }
        Ok(())
    }
}

impl Default for AnnulusSamplingConfig {
    fn default() -> Self {
        Self {
            num_angular_samples: 64,
            num_radial_samples: 9,
        }
    }
}

/// Sample gradients along a circular annulus.
///
/// Samples at evenly spaced angles around the annulus, at multiple radial
/// offsets between `inner_radius` and `outer_radius`. For each sample,
/// records the gradient vector and its alignment with the radial direction.
pub fn sample_annulus(
    gradient: &GradientField,
    center: PixelCoord,
    inner_radius: Scalar,
    outer_radius: Scalar,
    config: &AnnulusSamplingConfig,
) -> SupportEvidence {
    let gx_view = gradient.gx();
    let gy_view = gradient.gy();
    let mut samples = Vec::new();
    let mut alignment_sum = 0.0f32;

    let n_ang = config.num_angular_samples;
    let n_rad = config.num_radial_samples;

    for ai in 0..n_ang {
        let theta = 2.0 * std::f32::consts::PI * ai as Scalar / n_ang as Scalar;
        let cos_t = theta.cos();
        let sin_t = theta.sin();

        for ri in 0..n_rad {
            let t = if n_rad <= 1 {
                0.5
            } else {
                ri as Scalar / (n_rad - 1) as Scalar
            };
            let r = inner_radius + t * (outer_radius - inner_radius);

            let sx = center.x + r * cos_t;
            let sy = center.y + r * sin_t;

            let Some(gx) = gx_view.sample(sx, sy) else {
                continue;
            };
            let Some(gy) = gy_view.sample(sx, sy) else {
                continue;
            };
            let mag = (gx * gx + gy * gy).sqrt();
            if mag < 1e-8 {
                continue;
            }

            let alignment = ((gx * cos_t + gy * sin_t) / mag).abs();
            alignment_sum += alignment;

            samples.push(GradientSample {
                position: PixelCoord::new(sx, sy),
                gx,
                gy,
                radial_alignment: alignment,
            });
        }
    }

    let sample_count = samples.len();
    let mean_alignment = if sample_count > 0 {
        alignment_sum / sample_count as Scalar
    } else {
        0.0
    };

    let coverage = compute_circular_angular_coverage(&samples, center, config.num_angular_samples);
    SupportEvidence {
        gradient_samples: samples,
        angular_coverage: coverage,
        sample_count,
        mean_gradient_alignment: mean_alignment,
    }
}

/// Sample gradients along an elliptical annulus.
///
/// The ellipse is parameterized by semi-major/minor axes and angle. Samples
/// follow the ellipse boundary scaled between inner and outer factors.
pub fn sample_elliptical_annulus(
    gradient: &GradientField,
    ellipse: &Ellipse,
    inner_scale: Scalar,
    outer_scale: Scalar,
    config: &AnnulusSamplingConfig,
) -> SupportEvidence {
    let gx_view = gradient.gx();
    let gy_view = gradient.gy();
    let mut samples = Vec::new();
    let mut alignment_sum = 0.0f32;

    let cos_a = ellipse.angle.cos();
    let sin_a = ellipse.angle.sin();

    let n_ang = config.num_angular_samples;
    let n_rad = config.num_radial_samples;

    for ai in 0..n_ang {
        let theta = 2.0 * std::f32::consts::PI * ai as Scalar / n_ang as Scalar;
        let cos_t = theta.cos();
        let sin_t = theta.sin();

        // Ellipse point in local frame
        let ex = ellipse.semi_major * cos_t;
        let ey = ellipse.semi_minor * sin_t;

        for ri in 0..n_rad {
            let t = if n_rad <= 1 {
                0.5
            } else {
                ri as Scalar / (n_rad - 1) as Scalar
            };
            let scale = inner_scale + t * (outer_scale - inner_scale);

            // Scale the ellipse point
            let lx = scale * ex;
            let ly = scale * ey;

            // Rotate to image frame
            let sx = ellipse.center.x + lx * cos_a - ly * sin_a;
            let sy = ellipse.center.y + lx * sin_a + ly * cos_a;

            let Some(gx) = gx_view.sample(sx, sy) else {
                continue;
            };
            let Some(gy) = gy_view.sample(sx, sy) else {
                continue;
            };
            let mag = (gx * gx + gy * gy).sqrt();
            if mag < 1e-8 {
                continue;
            }

            // True ellipse normal in local coordinates, scaled copies preserve direction.
            let nx_local = ellipse.semi_minor * cos_t;
            let ny_local = ellipse.semi_major * sin_t;
            let n_mag = (nx_local * nx_local + ny_local * ny_local).sqrt();
            if n_mag < 1e-8 {
                continue;
            }
            let nx = (nx_local * cos_a - ny_local * sin_a) / n_mag;
            let ny = (nx_local * sin_a + ny_local * cos_a) / n_mag;

            let alignment = ((gx * nx + gy * ny) / mag).abs();
            alignment_sum += alignment;

            samples.push(GradientSample {
                position: PixelCoord::new(sx, sy),
                gx,
                gy,
                radial_alignment: alignment,
            });
        }
    }

    let sample_count = samples.len();
    let mean_alignment = if sample_count > 0 {
        alignment_sum / sample_count as Scalar
    } else {
        0.0
    };

    let coverage =
        compute_elliptical_angular_coverage(&samples, ellipse, config.num_angular_samples);
    SupportEvidence {
        gradient_samples: samples,
        angular_coverage: coverage,
        sample_count,
        mean_gradient_alignment: mean_alignment,
    }
}

/// Estimate angular coverage from gradient samples.
///
/// Divides the annulus into `n_bins` angular bins and counts what fraction
/// of bins have at least one well-aligned sample (alignment > 0.5).
fn compute_circular_angular_coverage(
    samples: &[GradientSample],
    center: PixelCoord,
    n_bins: usize,
) -> Scalar {
    if samples.is_empty() || n_bins == 0 {
        return 0.0;
    }
    let mut bins = vec![false; n_bins];
    for s in samples {
        if s.radial_alignment > 0.5 {
            let angle = (s.position.y - center.y).atan2(s.position.x - center.x);
            let normalized = (angle + std::f32::consts::PI) / (2.0 * std::f32::consts::PI);
            let bin = (normalized * n_bins as Scalar) as usize;
            let bin = bin.min(n_bins - 1);
            bins[bin] = true;
        }
    }
    let filled = bins.iter().filter(|&&b| b).count();
    filled as Scalar / n_bins as Scalar
}

fn compute_elliptical_angular_coverage(
    samples: &[GradientSample],
    ellipse: &Ellipse,
    n_bins: usize,
) -> Scalar {
    if samples.is_empty() || n_bins == 0 || ellipse.semi_major <= 1e-6 || ellipse.semi_minor <= 1e-6
    {
        return 0.0;
    }

    let cos_a = ellipse.angle.cos();
    let sin_a = ellipse.angle.sin();
    let mut bins = vec![false; n_bins];

    for s in samples {
        if s.radial_alignment <= 0.5 {
            continue;
        }

        let dx = s.position.x - ellipse.center.x;
        let dy = s.position.y - ellipse.center.y;
        let lx = dx * cos_a + dy * sin_a;
        let ly = -dx * sin_a + dy * cos_a;
        let angle = (ly / ellipse.semi_minor).atan2(lx / ellipse.semi_major);
        let normalized = (angle + std::f32::consts::PI) / (2.0 * std::f32::consts::PI);
        let bin = ((normalized * n_bins as Scalar) as usize).min(n_bins - 1);
        bins[bin] = true;
    }

    let filled = bins.iter().filter(|&&b| b).count();
    filled as Scalar / n_bins as Scalar
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::geometry::Ellipse;
    use crate::core::gradient::sobel_gradient;
    use crate::core::image_view::ImageView;

    fn make_ring_image(size: usize, cx: f32, cy: f32, r_inner: f32, r_outer: f32) -> Vec<u8> {
        let mut data = vec![0u8; size * size];
        for y in 0..size {
            for x in 0..size {
                let dx = x as f32 - cx;
                let dy = y as f32 - cy;
                let r = (dx * dx + dy * dy).sqrt();
                if r >= r_inner && r <= r_outer {
                    data[y * size + x] = 255;
                }
            }
        }
        data
    }

    #[test]
    fn sample_annulus_on_ring() {
        let size = 80;
        let cx = 40.0;
        let cy = 40.0;
        let data = make_ring_image(size, cx, cy, 14.0, 18.0);
        let image = ImageView::from_slice(&data, size, size).unwrap();
        let grad = sobel_gradient(&image).unwrap();

        let evidence = sample_annulus(
            &grad,
            PixelCoord::new(cx, cy),
            12.0,
            20.0,
            &AnnulusSamplingConfig::default(),
        );

        assert!(evidence.sample_count > 0, "should have samples");
        assert!(
            evidence.mean_gradient_alignment > 0.3,
            "gradients on a ring should be radially aligned, got {}",
            evidence.mean_gradient_alignment
        );
    }

    #[test]
    fn sample_annulus_off_center() {
        let size = 80;
        let data = make_ring_image(size, 40.0, 40.0, 14.0, 18.0);
        let image = ImageView::from_slice(&data, size, size).unwrap();
        let grad = sobel_gradient(&image).unwrap();

        // Sample far from the actual center — should have poor alignment
        let evidence = sample_annulus(
            &grad,
            PixelCoord::new(20.0, 20.0),
            12.0,
            20.0,
            &AnnulusSamplingConfig::default(),
        );

        // Off-center sampling should yield worse alignment than on-center
        let on_center = sample_annulus(
            &grad,
            PixelCoord::new(40.0, 40.0),
            12.0,
            20.0,
            &AnnulusSamplingConfig::default(),
        );

        assert!(
            on_center.mean_gradient_alignment > evidence.mean_gradient_alignment,
            "on-center ({}) should beat off-center ({})",
            on_center.mean_gradient_alignment,
            evidence.mean_gradient_alignment
        );
    }

    #[test]
    fn sample_elliptical_annulus_on_circle() {
        // An elliptical annulus with equal semi-axes should behave like circular
        let size = 80;
        let data = make_ring_image(size, 40.0, 40.0, 14.0, 18.0);
        let image = ImageView::from_slice(&data, size, size).unwrap();
        let grad = sobel_gradient(&image).unwrap();

        let ellipse = Ellipse::new(PixelCoord::new(40.0, 40.0), 16.0, 16.0, 0.0);
        let evidence = sample_elliptical_annulus(
            &grad,
            &ellipse,
            0.75, // inner_scale = 12/16
            1.25, // outer_scale = 20/16
            &AnnulusSamplingConfig::default(),
        );

        assert!(evidence.sample_count > 0);
        assert!(
            evidence.mean_gradient_alignment > 0.3,
            "expected good alignment, got {}",
            evidence.mean_gradient_alignment
        );
    }

    #[test]
    fn empty_region_yields_zero_evidence() {
        let data = vec![0u8; 64 * 64];
        let image = ImageView::from_slice(&data, 64, 64).unwrap();
        let grad = sobel_gradient(&image).unwrap();

        let evidence = sample_annulus(
            &grad,
            PixelCoord::new(32.0, 32.0),
            10.0,
            15.0,
            &AnnulusSamplingConfig::default(),
        );

        assert_eq!(evidence.sample_count, 0);
        assert_eq!(evidence.mean_gradient_alignment, 0.0);
    }
}