oxiz-math 0.1.1

Mathematical foundations for OxiZ SMT solver
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
//! Delta-rational numbers for handling strict inequalities.
//!
//! A delta-rational is a number of the form r + δ*k where:
//! - r is a rational number
//! - δ is an infinitesimal (smaller than any positive rational)
//! - k is an integer coefficient
//!
//! This allows us to represent strict inequalities:
//! - x < 5 becomes x ≤ 5 - δ
//! - x > 5 becomes x ≥ 5 + δ
//!
//! Reference: Z3's delta_rational implementation.

use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::{One, Signed, Zero};
use std::cmp::Ordering;
use std::fmt;
use std::ops::{Add, Neg, Sub};

/// A delta-rational number: r + δ*k
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeltaRational {
    /// The rational part.
    pub rational: BigRational,
    /// The infinitesimal coefficient.
    pub delta_coeff: i64,
}

impl DeltaRational {
    /// Create a new delta-rational.
    pub fn new(rational: BigRational, delta_coeff: i64) -> Self {
        Self {
            rational,
            delta_coeff,
        }
    }

    /// Create a delta-rational from a rational (delta_coeff = 0).
    #[inline]
    pub fn from_rational(r: BigRational) -> Self {
        Self::new(r, 0)
    }

    /// Create a delta-rational from an integer.
    #[inline]
    pub fn from_int(n: i64) -> Self {
        Self::from_rational(BigRational::from_integer(BigInt::from(n)))
    }

    /// Create zero (0 + 0*δ).
    #[inline]
    pub fn zero() -> Self {
        Self::from_int(0)
    }

    /// Create one (1 + 0*δ).
    #[inline]
    pub fn one() -> Self {
        Self::from_int(1)
    }

    /// Create the infinitesimal δ (0 + 1*δ).
    #[inline]
    pub fn delta() -> Self {
        Self::new(BigRational::zero(), 1)
    }

    /// Check if this is zero.
    #[inline]
    pub fn is_zero(&self) -> bool {
        self.rational.is_zero() && self.delta_coeff == 0
    }

    /// Check if this is one.
    #[inline]
    pub fn is_one(&self) -> bool {
        self.rational.is_one() && self.delta_coeff == 0
    }

    /// Check if this is purely rational (delta_coeff = 0).
    #[inline]
    pub fn is_rational(&self) -> bool {
        self.delta_coeff == 0
    }

    /// Get the floor of the rational part.
    pub fn floor(&self) -> BigInt {
        crate::rational::floor(&self.rational)
    }

    /// Get the ceiling of the rational part (adjusted for delta).
    pub fn ceil(&self) -> BigInt {
        if self.delta_coeff > 0 {
            // r + δ*k where k > 0, so ceiling is ceil(r)
            crate::rational::ceil(&self.rational)
        } else if self.delta_coeff < 0 {
            // r + δ*k where k < 0, so we need floor if r is integer, else ceil
            if self.rational.is_integer() {
                crate::rational::floor(&self.rational)
            } else {
                crate::rational::ceil(&self.rational)
            }
        } else {
            crate::rational::ceil(&self.rational)
        }
    }

    /// Negate the delta-rational.
    pub fn negate(&self) -> Self {
        Self::new(-&self.rational, -self.delta_coeff)
    }

    /// Add two delta-rationals.
    pub fn add(&self, other: &Self) -> Self {
        Self::new(
            &self.rational + &other.rational,
            self.delta_coeff + other.delta_coeff,
        )
    }

    /// Subtract two delta-rationals.
    pub fn sub(&self, other: &Self) -> Self {
        Self::new(
            &self.rational - &other.rational,
            self.delta_coeff - other.delta_coeff,
        )
    }

    /// Multiply by a rational scalar.
    pub fn mul_rational(&self, r: &BigRational) -> Self {
        if r.is_zero() {
            return Self::zero();
        }

        // (a + δ*k) * r = a*r + δ*(k*r)
        // But delta coefficient must be integer, so we only support integer r for now
        if r.is_integer() {
            let r_int = r.numer().to_string().parse::<i64>().unwrap_or(0);
            Self::new(&self.rational * r, self.delta_coeff * r_int)
        } else {
            // For non-integer rationals, we can't maintain integer delta coefficient
            // Just multiply the rational part
            Self::new(&self.rational * r, 0)
        }
    }

    /// Divide by a positive rational scalar.
    pub fn div_rational(&self, r: &BigRational) -> Option<Self> {
        if r.is_zero() {
            return None;
        }

        // (a + δ*k) / r = a/r + δ*(k/r)
        if r.is_integer() && r.is_positive() {
            let r_int = r.numer().to_string().parse::<i64>().unwrap_or(1);
            if r_int != 0 {
                Some(Self::new(&self.rational / r, self.delta_coeff / r_int))
            } else {
                None
            }
        } else {
            // For non-integer rationals, just divide the rational part
            Some(Self::new(&self.rational / r, 0))
        }
    }

    /// Compare two delta-rationals.
    pub fn cmp_delta(&self, other: &Self) -> Ordering {
        // First compare rational parts
        match self.rational.cmp(&other.rational) {
            Ordering::Equal => {
                // If rational parts are equal, compare delta coefficients
                self.delta_coeff.cmp(&other.delta_coeff)
            }
            ord => ord,
        }
    }

    /// Check if this delta-rational is positive.
    pub fn is_positive(&self) -> bool {
        self.rational.is_positive() || (self.rational.is_zero() && self.delta_coeff > 0)
    }

    /// Check if this delta-rational is negative.
    pub fn is_negative(&self) -> bool {
        self.rational.is_negative() || (self.rational.is_zero() && self.delta_coeff < 0)
    }

    /// Check if this delta-rational is non-negative.
    pub fn is_non_negative(&self) -> bool {
        !self.is_negative()
    }

    /// Check if this delta-rational is non-positive.
    pub fn is_non_positive(&self) -> bool {
        !self.is_positive()
    }

    /// Get the sign: -1, 0, or 1.
    pub fn sign(&self) -> i8 {
        if self.is_positive() {
            1
        } else if self.is_negative() {
            -1
        } else {
            0
        }
    }

    /// Convert to a lower bound for an interval (r if δ >= 0, else r - ε).
    pub fn to_lower_bound(&self) -> BigRational {
        self.rational.clone()
    }

    /// Convert to an upper bound for an interval (r if δ <= 0, else r + ε).
    pub fn to_upper_bound(&self) -> BigRational {
        self.rational.clone()
    }
}

impl Default for DeltaRational {
    fn default() -> Self {
        Self::zero()
    }
}

impl From<BigRational> for DeltaRational {
    fn from(r: BigRational) -> Self {
        Self::from_rational(r)
    }
}

impl From<i64> for DeltaRational {
    fn from(n: i64) -> Self {
        Self::from_int(n)
    }
}

impl PartialOrd for DeltaRational {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(std::cmp::Ord::cmp(self, other))
    }
}

impl Ord for DeltaRational {
    fn cmp(&self, other: &Self) -> Ordering {
        self.cmp_delta(other)
    }
}

impl Neg for DeltaRational {
    type Output = Self;

    fn neg(self) -> Self::Output {
        self.negate()
    }
}

impl Neg for &DeltaRational {
    type Output = DeltaRational;

    fn neg(self) -> Self::Output {
        self.negate()
    }
}

impl Add for DeltaRational {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        DeltaRational::add(&self, &rhs)
    }
}

impl Add<&DeltaRational> for &DeltaRational {
    type Output = DeltaRational;

    fn add(self, rhs: &DeltaRational) -> Self::Output {
        DeltaRational::add(self, rhs)
    }
}

impl Sub for DeltaRational {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        DeltaRational::sub(&self, &rhs)
    }
}

impl Sub<&DeltaRational> for &DeltaRational {
    type Output = DeltaRational;

    fn sub(self, rhs: &DeltaRational) -> Self::Output {
        DeltaRational::sub(self, rhs)
    }
}

impl fmt::Display for DeltaRational {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.delta_coeff == 0 {
            write!(f, "{}", self.rational)
        } else if self.rational.is_zero() {
            if self.delta_coeff == 1 {
                write!(f, "δ")
            } else if self.delta_coeff == -1 {
                write!(f, "")
            } else {
                write!(f, "{}δ", self.delta_coeff)
            }
        } else if self.delta_coeff == 1 {
            write!(f, "{} + δ", self.rational)
        } else if self.delta_coeff == -1 {
            write!(f, "{} - δ", self.rational)
        } else if self.delta_coeff > 0 {
            write!(f, "{} + {}δ", self.rational, self.delta_coeff)
        } else {
            write!(f, "{} - {}δ", self.rational, -self.delta_coeff)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rat(n: i64) -> BigRational {
        BigRational::from_integer(BigInt::from(n))
    }

    #[test]
    fn test_delta_basic() {
        let d = DeltaRational::delta();
        assert_eq!(d.rational, BigRational::zero());
        assert_eq!(d.delta_coeff, 1);
    }

    #[test]
    fn test_delta_add() {
        let a = DeltaRational::new(rat(5), 2); // 5 + 2δ
        let b = DeltaRational::new(rat(3), -1); // 3 - δ
        let c = DeltaRational::add(&a, &b); // 8 + δ

        assert_eq!(c.rational, rat(8));
        assert_eq!(c.delta_coeff, 1);
    }

    #[test]
    fn test_delta_sub() {
        let a = DeltaRational::new(rat(5), 2); // 5 + 2δ
        let b = DeltaRational::new(rat(3), -1); // 3 - δ
        let c = DeltaRational::sub(&a, &b); // 2 + 3δ

        assert_eq!(c.rational, rat(2));
        assert_eq!(c.delta_coeff, 3);
    }

    #[test]
    fn test_delta_cmp() {
        let a = DeltaRational::new(rat(5), 0); // 5
        let b = DeltaRational::new(rat(5), 1); // 5 + δ
        let c = DeltaRational::new(rat(5), -1); // 5 - δ

        assert!(a < b);
        assert!(c < a);
        assert!(c < b);
    }

    #[test]
    fn test_delta_zero_cmp() {
        let zero = DeltaRational::zero();
        let delta = DeltaRational::delta();
        let minus_delta = DeltaRational::new(rat(0), -1);

        assert!(minus_delta < zero);
        assert!(zero < delta);
        assert!(minus_delta < delta);
    }

    #[test]
    fn test_delta_sign() {
        let pos = DeltaRational::new(rat(5), 0);
        let neg = DeltaRational::new(rat(-5), 0);
        let delta_pos = DeltaRational::delta();
        let delta_neg = DeltaRational::new(rat(0), -1);

        assert!(pos.is_positive());
        assert!(neg.is_negative());
        assert!(delta_pos.is_positive());
        assert!(delta_neg.is_negative());
    }

    #[test]
    fn test_delta_mul_rational() {
        let a = DeltaRational::new(rat(5), 2); // 5 + 2δ
        let b = a.mul_rational(&rat(3)); // 15 + 6δ

        assert_eq!(b.rational, rat(15));
        assert_eq!(b.delta_coeff, 6);
    }

    #[test]
    fn test_delta_negate() {
        let a = DeltaRational::new(rat(5), 2); // 5 + 2δ
        let b = a.negate(); // -5 - 2δ

        assert_eq!(b.rational, rat(-5));
        assert_eq!(b.delta_coeff, -2);
    }
}