subsume 0.6.0

Geometric region embeddings (boxes, cones, octagons, Gaussians, hyperbolic intervals, sheaf networks) for subsumption, entailment, and logical query answering
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Candle implementation of Box trait.

use crate::{Box, BoxError};
use candle_core::Tensor;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// A box embedding implemented using `candle_core::Tensor`.
#[derive(Debug, Clone)]
pub struct CandleBox {
    /// Minimum bounds [d]
    min: Tensor,
    /// Maximum bounds [d]
    max: Tensor,
    /// Temperature for Gumbel-Softmax (1.0 = standard box)
    pub(crate) temperature: f32,
}

impl CandleBox {
    /// Create a CandleBox without validating that min <= max.
    ///
    /// Used by Gumbel LSE intersection, which can produce "flipped" boxes
    /// (min > max in some dimension) that softplus volume handles gracefully.
    pub(crate) fn new_unchecked(min: Tensor, max: Tensor, temperature: f32) -> Self {
        Self {
            min,
            max,
            temperature,
        }
    }

    /// Create a new CandleBox.
    ///
    /// # Errors
    ///
    /// Returns `BoxError` if min/max have different shapes or if any min\[i\] > max\[i\].
    pub fn new(min: Tensor, max: Tensor, temperature: f32) -> std::result::Result<Self, BoxError> {
        if min.shape() != max.shape() {
            return Err(BoxError::DimensionMismatch {
                expected: min.dims().len(),
                actual: max.dims().len(),
            });
        }

        // Validate bounds
        let min_data = min
            .to_vec1::<f32>()
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let max_data = max
            .to_vec1::<f32>()
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        for (i, (&m, &max_val)) in min_data.iter().zip(max_data.iter()).enumerate() {
            if m.is_nan() || max_val.is_nan() {
                return Err(BoxError::InvalidBounds {
                    dim: i,
                    min: m as f64,
                    max: max_val as f64,
                });
            }
            if m > max_val {
                return Err(BoxError::InvalidBounds {
                    dim: i,
                    min: m as f64,
                    max: max_val as f64,
                });
            }
        }

        // Validate temperature: must be finite and positive
        if !temperature.is_finite() || temperature <= 0.0 {
            return Err(BoxError::InvalidTemperature {
                value: temperature as f64,
                reason: "temperature must be finite and positive",
            });
        }

        Ok(Self {
            min,
            max,
            temperature,
        })
    }
}

impl Box for CandleBox {
    type Scalar = f32;
    type Vector = Tensor;

    fn min(&self) -> &Self::Vector {
        &self.min
    }

    fn max(&self) -> &Self::Vector {
        &self.max
    }

    fn dim(&self) -> usize {
        self.min.dims().iter().product()
    }

    fn volume(&self) -> std::result::Result<Self::Scalar, BoxError> {
        // Volume = ∏(max\[i\] - min\[i\])
        let diff = self
            .max
            .sub(&self.min)
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        // Compute product by iterating over elements
        let diff_data = diff
            .to_vec1::<f32>()
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let volume = diff_data.iter().product::<f32>();
        Ok(volume)
    }

    fn intersection(&self, other: &Self) -> std::result::Result<Self, BoxError> {
        if self.dim() != other.dim() {
            return Err(BoxError::DimensionMismatch {
                expected: self.dim(),
                actual: other.dim(),
            });
        }

        let intersection_min = self
            .min
            .maximum(&other.min)
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let intersection_max = self
            .max
            .minimum(&other.max)
            .map_err(|e| BoxError::Internal(e.to_string()))?;

        // Check if intersection is valid (not disjoint)
        // If min > max in any dimension, boxes are disjoint
        let min_data = intersection_min
            .to_vec1::<f32>()
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let max_data = intersection_max
            .to_vec1::<f32>()
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        for (min_val, max_val) in min_data.iter().zip(max_data.iter()) {
            if min_val > max_val {
                // Boxes are disjoint - return a zero-volume box
                return Self::new(
                    intersection_min.clone(),
                    intersection_min.clone(),
                    self.temperature,
                );
            }
        }

        Self::new(intersection_min, intersection_max, self.temperature)
    }

    fn containment_prob(&self, other: &Self) -> std::result::Result<Self::Scalar, BoxError> {
        if self.dim() != other.dim() {
            return Err(BoxError::DimensionMismatch {
                expected: self.dim(),
                actual: other.dim(),
            });
        }

        // P(other ⊆ self) = intersection_volume(other, self) / other.volume()
        let intersection = self.intersection(other)?;
        let intersection_vol = intersection.volume()?;
        let other_vol = other.volume()?;

        if other_vol <= 0.0 {
            return Err(BoxError::ZeroVolume);
        }

        Ok((intersection_vol / other_vol).clamp(0.0, 1.0))
    }

    fn overlap_prob(&self, other: &Self) -> std::result::Result<Self::Scalar, BoxError> {
        // P(self ∩ other ≠ ∅) = intersection_volume / union_volume
        // Using inclusion-exclusion: P(A ∩ B ≠ ∅) = intersection_vol(A, B) / union_vol(A, B)
        let intersection = self.intersection(other)?;
        let intersection_vol = intersection.volume()?;

        // Union volume = vol(A) + vol(B) - intersection_vol(A, B)
        let vol_a = self.volume()?;
        let vol_b = other.volume()?;
        let union_vol = vol_a + vol_b - intersection_vol;

        if union_vol <= 0.0 {
            return Ok(0.0);
        }

        Ok((intersection_vol / union_vol).clamp(0.0, 1.0))
    }

    fn union(&self, other: &Self) -> std::result::Result<Self, BoxError> {
        if self.dim() != other.dim() {
            return Err(BoxError::DimensionMismatch {
                expected: self.dim(),
                actual: other.dim(),
            });
        }

        let union_min = self
            .min
            .minimum(&other.min)
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let union_max = self
            .max
            .maximum(&other.max)
            .map_err(|e| BoxError::Internal(e.to_string()))?;

        Self::new(union_min, union_max, self.temperature)
    }

    fn center(&self) -> std::result::Result<Self::Vector, BoxError> {
        // Center = (min + max) / 2
        let sum = self
            .min
            .add(&self.max)
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let two = Tensor::new(&[2.0f32], self.min.device())
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let center = sum
            .broadcast_div(&two)
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        Ok(center)
    }

    fn distance(&self, other: &Self) -> std::result::Result<Self::Scalar, BoxError> {
        if self.dim() != other.dim() {
            return Err(BoxError::DimensionMismatch {
                expected: self.dim(),
                actual: other.dim(),
            });
        }

        // Check if boxes overlap (distance = 0)
        let intersection = self.intersection(other)?;
        let intersection_vol = intersection.volume()?;
        if intersection_vol > 0.0 {
            return Ok(0.0);
        }

        // Compute minimum distance between two axis-aligned boxes
        // For each dimension, compute the gap (or 0 if overlapping)
        // Use element-wise operations on tensors
        let self_min_data = self
            .min
            .to_vec1::<f32>()
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let self_max_data = self
            .max
            .to_vec1::<f32>()
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let other_min_data = other
            .min
            .to_vec1::<f32>()
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let other_max_data = other
            .max
            .to_vec1::<f32>()
            .map_err(|e| BoxError::Internal(e.to_string()))?;

        let mut dist_sq = 0.0;
        for i in 0..self.dim() {
            let gap = if self_max_data[i] < other_min_data[i] {
                other_min_data[i] - self_max_data[i]
            } else if other_max_data[i] < self_min_data[i] {
                self_min_data[i] - other_max_data[i]
            } else {
                0.0
            };
            dist_sq += gap * gap;
        }

        Ok(dist_sq.sqrt())
    }

    fn truncate(&self, k: usize) -> std::result::Result<Self, BoxError> {
        let d = self.dim();
        if k > d {
            return Err(BoxError::DimensionMismatch {
                expected: d,
                actual: k,
            });
        }
        if k == d {
            return Ok(self.clone());
        }

        // Expect 1-D tensors of shape [d].
        let min_t = self
            .min
            .narrow(0, 0, k)
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        let max_t = self
            .max
            .narrow(0, 0, k)
            .map_err(|e| BoxError::Internal(e.to_string()))?;
        Self::new(min_t, max_t, self.temperature)
    }
}

impl Serialize for CandleBox {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("CandleBox", 3)?;

        // Convert tensors to Vec<f32> for serialization
        let min_vec = self.min.to_vec1::<f32>().map_err(|e| {
            serde::ser::Error::custom(format!("Failed to serialize min tensor: {}", e))
        })?;
        let max_vec = self.max.to_vec1::<f32>().map_err(|e| {
            serde::ser::Error::custom(format!("Failed to serialize max tensor: {}", e))
        })?;

        state.serialize_field("min", &min_vec)?;
        state.serialize_field("max", &max_vec)?;
        state.serialize_field("temperature", &self.temperature)?;
        state.end()
    }
}

impl<'de> Deserialize<'de> for CandleBox {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::{self, MapAccess, Visitor};
        use std::fmt;

        #[derive(Deserialize)]
        #[serde(field_identifier, rename_all = "lowercase")]
        enum Field {
            Min,
            Max,
            Temperature,
        }

        struct CandleBoxVisitor;

        impl<'de> Visitor<'de> for CandleBoxVisitor {
            type Value = CandleBox;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct CandleBox")
            }

            fn visit_map<V>(self, mut map: V) -> Result<CandleBox, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut min_vec: Option<Vec<f32>> = None;
                let mut max_vec: Option<Vec<f32>> = None;
                let mut temperature: Option<f32> = None;

                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Min => {
                            if min_vec.is_some() {
                                return Err(de::Error::duplicate_field("min"));
                            }
                            min_vec = Some(map.next_value()?);
                        }
                        Field::Max => {
                            if max_vec.is_some() {
                                return Err(de::Error::duplicate_field("max"));
                            }
                            max_vec = Some(map.next_value()?);
                        }
                        Field::Temperature => {
                            if temperature.is_some() {
                                return Err(de::Error::duplicate_field("temperature"));
                            }
                            temperature = Some(map.next_value()?);
                        }
                    }
                }

                let min_vec = min_vec.ok_or_else(|| de::Error::missing_field("min"))?;
                let max_vec = max_vec.ok_or_else(|| de::Error::missing_field("max"))?;
                let temperature = temperature.unwrap_or(1.0);

                // Reconstruct tensors from vectors
                // Note: We use CPU device by default during deserialization
                // Users can move tensors to GPU after deserialization if needed
                let device = candle_core::Device::Cpu;
                let min_tensor = Tensor::new(&min_vec[..], &device).map_err(|e| {
                    de::Error::custom(format!("Failed to create min tensor: {}", e))
                })?;
                let max_tensor = Tensor::new(&max_vec[..], &device).map_err(|e| {
                    de::Error::custom(format!("Failed to create max tensor: {}", e))
                })?;

                CandleBox::new(min_tensor, max_tensor, temperature)
                    .map_err(|e| de::Error::custom(format!("Failed to create CandleBox: {}", e)))
            }
        }

        const FIELDS: &[&str] = &["min", "max", "temperature"];
        deserializer.deserialize_struct("CandleBox", FIELDS, CandleBoxVisitor)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Box as BoxTrait;
    use candle_core::Device;

    #[test]
    fn serde_json_roundtrip() {
        let min = Tensor::new(&[1.0f32, 2.0, 3.0], &Device::Cpu).unwrap();
        let max = Tensor::new(&[4.0f32, 5.0, 6.0], &Device::Cpu).unwrap();
        let original = CandleBox::new(min, max, 0.7).unwrap();

        let json = serde_json::to_string(&original).unwrap();
        let restored: CandleBox = serde_json::from_str(&json).unwrap();

        // Verify dimensions match.
        assert_eq!(original.dim(), restored.dim());

        // Verify min/max coordinates match.
        let orig_min: Vec<f32> = original.min().to_vec1().unwrap();
        let rest_min: Vec<f32> = restored.min().to_vec1().unwrap();
        let orig_max: Vec<f32> = original.max().to_vec1().unwrap();
        let rest_max: Vec<f32> = restored.max().to_vec1().unwrap();
        assert_eq!(orig_min, rest_min);
        assert_eq!(orig_max, rest_max);

        // Verify temperature survives roundtrip.
        assert!((original.temperature - restored.temperature).abs() < 1e-7);

        // Verify volume is preserved.
        let vol_orig = original.volume(1.0).unwrap();
        let vol_rest = restored.volume(1.0).unwrap();
        assert!((vol_orig - vol_rest).abs() < 1e-6);
    }
}