hyperlattice 0.4.0

A small Rust linear algebra library with a crate-owned Scalar type and realistic or approximate backends.
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! Scalar constants, elementary functions, and zero-classification helpers.

use crate::complex::Complex;
use crate::{AbortSignal, Backend, BlasResult, CheckedBlasResult, Problem, Scalar};
use std::sync::atomic::Ordering;

/// Classification of whether a scalar is zero.
///
/// `Unknown` is important for computable reals and approximate intervals:
/// ordinary APIs may choose optimistic behavior, while checked APIs reject
/// unknown-zero values.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ZeroStatus {
    /// The value is definitely zero.
    Zero,
    /// The value is definitely non-zero.
    NonZero,
    /// The backend cannot prove whether the value is zero.
    Unknown,
}

/// Exact sign knowledge exposed through [`Scalar`](crate::Scalar).
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ScalarSign {
    /// The scalar is definitely negative.
    Negative,
    /// The scalar is definitely zero.
    Zero,
    /// The scalar is definitely positive.
    Positive,
}

/// Known most-significant binary digit for a non-zero scalar.
///
/// `exact_msd` is true when `msd` is known exactly. When it is false, `msd` is
/// a conservative backend-provided bound suitable for filtering but not for
/// reconstructing the value.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ScalarMagnitudeBits {
    /// Most-significant binary digit or conservative binary magnitude bound.
    pub msd: i32,
    /// Whether [`ScalarMagnitudeBits::msd`] is exact.
    pub exact_msd: bool,
}

/// Conservative scalar facts available without exposing backend internals.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ScalarFacts {
    /// Known sign, if the backend can prove it.
    pub sign: Option<ScalarSign>,
    /// Known zero/non-zero status.
    pub zero: ZeroStatus,
    /// Whether an exact rational representation is structurally available.
    pub exact_rational: bool,
    /// Conservative binary magnitude information for known non-zero values.
    pub magnitude: Option<ScalarMagnitudeBits>,
}

pub(crate) fn two<B: Backend>() -> Scalar<B> {
    2.into()
}

#[inline(always)]
pub(crate) fn with_abort<B: Backend>(mut value: Scalar<B>, signal: &AbortSignal) -> Scalar<B> {
    crate::trace_dispatch!("hyperlattice", "abort", "attach-owned-scalar");
    value.abort(signal.clone());
    value
}

#[inline(always)]
pub(crate) fn clone_with_abort<B: Backend>(value: &Scalar<B>, signal: &AbortSignal) -> Scalar<B> {
    crate::trace_dispatch!("hyperlattice", "abort", "clone-and-attach");
    with_abort(value.clone(), signal)
}

/// Classifies a scalar as zero, non-zero, or unknown.
#[inline(always)]
pub fn zero_status<B: Backend>(value: &Scalar<B>) -> ZeroStatus {
    crate::trace_dispatch!("hyperlattice", "zero_status", "scalar-query");
    value.zero_status()
}

/// Classifies a scalar after attaching an abort signal.
///
/// With the hyperreal backend, this allows long-running zero checks to observe
/// cancellation. With the approx backend, the signal is accepted as a no-op.
#[inline(always)]
pub fn zero_status_with_abort<B: Backend>(value: &Scalar<B>, signal: &AbortSignal) -> ZeroStatus {
    let status = zero_status(value);
    if status != ZeroStatus::Unknown || !signal.load(Ordering::Relaxed) {
        // Fast path for the common case: known structural status, or no active abort
        // request. Cloning just to attach a signal showed up in predicate-heavy benches.
        crate::trace_dispatch!("hyperlattice", "zero_status_abort", "no-clone-fast-path");
        return status;
    }

    crate::trace_dispatch!(
        "hyperlattice",
        "zero_status_abort",
        "clone-with-active-abort"
    );
    zero_status(&clone_with_abort(value, signal))
}

#[inline(always)]
pub(crate) fn reject_definite_zero<B: Backend>(value: &Scalar<B>) -> BlasResult<()> {
    if value.definitely_zero() {
        crate::trace_dispatch!("hyperlattice", "zero_guard", "definite-zero-rejected");
        Err(Problem::DivideByZero)
    } else {
        crate::trace_dispatch!("hyperlattice", "zero_guard", "not-definitely-zero");
        Ok(())
    }
}

#[inline(always)]
pub(crate) fn require_known_nonzero<B: Backend>(value: &Scalar<B>) -> CheckedBlasResult<()> {
    match zero_status(value) {
        ZeroStatus::Zero => {
            crate::trace_dispatch!("hyperlattice", "zero_guard", "checked-zero-rejected");
            Err(Problem::DivideByZero)
        }
        ZeroStatus::NonZero => {
            crate::trace_dispatch!("hyperlattice", "zero_guard", "checked-nonzero");
            Ok(())
        }
        ZeroStatus::Unknown => {
            crate::trace_dispatch!("hyperlattice", "zero_guard", "checked-unknown-rejected");
            Err(Problem::UnknownZero)
        }
    }
}

#[inline(always)]
pub(crate) fn require_known_nonzero_with_abort<B: Backend>(
    value: &Scalar<B>,
    signal: &AbortSignal,
) -> CheckedBlasResult<()> {
    match zero_status_with_abort(value, signal) {
        ZeroStatus::Zero => Err(Problem::DivideByZero),
        ZeroStatus::NonZero => Ok(()),
        ZeroStatus::Unknown => Err(Problem::UnknownZero),
    }
}

/// Returns the additive identity.
pub fn zero() -> Scalar {
    crate::trace_dispatch!("hyperlattice", "free_function", "zero");
    Scalar::zero()
}

/// Returns the multiplicative identity.
pub fn one() -> Scalar {
    crate::trace_dispatch!("hyperlattice", "free_function", "one");
    Scalar::one()
}

/// Returns Euler's number.
pub fn e() -> Scalar {
    crate::trace_dispatch!("hyperlattice", "free_function", "e");
    Scalar::e()
}

/// Returns pi.
pub fn pi() -> Scalar {
    crate::trace_dispatch!("hyperlattice", "free_function", "pi");
    Scalar::pi()
}

/// Returns tau, equal to `2 * pi`.
pub fn tau() -> Scalar {
    // Route through the backend hook so exact backends can return symbolic tau
    // instead of rebuilding `2 * pi` through multiplication.
    crate::trace_dispatch!("hyperlattice", "free_function", "tau");
    Scalar::tau()
}

/// Returns the imaginary unit as a complex scalar.
pub fn i() -> Complex {
    Complex::i()
}

/// Returns the multiplicative inverse of `value`.
pub fn reciprocal<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "reciprocal-owned");
    value.inverse()
}

/// Returns the multiplicative inverse of `value` without consuming it.
pub fn reciprocal_ref<B: Backend>(value: &Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "reciprocal-ref");
    value.inverse_ref()
}

/// Returns the multiplicative inverse after rejecting zero and unknown-zero values.
pub fn reciprocal_checked<B: Backend>(value: Scalar<B>) -> CheckedBlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "reciprocal-checked-owned");
    require_known_nonzero(&value)?;
    value.inverse()
}

/// Returns the checked multiplicative inverse without consuming `value`.
pub fn reciprocal_ref_checked<B: Backend>(value: &Scalar<B>) -> CheckedBlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "reciprocal-checked-ref");
    require_known_nonzero(value)?;
    value.inverse_ref()
}

/// Returns the checked multiplicative inverse after attaching an abort signal.
pub fn reciprocal_checked_with_abort<B: Backend>(
    value: Scalar<B>,
    signal: &AbortSignal,
) -> CheckedBlasResult<Scalar<B>> {
    crate::trace_dispatch!(
        "hyperlattice",
        "free_function",
        "reciprocal-checked-with-abort"
    );
    let value = with_abort(value, signal);
    require_known_nonzero_with_abort(&value, signal)?;
    value.inverse()
}

/// Raises `base` to a scalar exponent.
pub fn pow<B: Backend>(base: Scalar<B>, exponent: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "pow");
    base.pow(exponent)
}

/// Raises `base` to an integer exponent using exponentiation by squaring.
///
/// Negative exponents require the result to be invertible. `0^0` returns
/// [`Problem::NotANumber`].
pub fn powi<B: Backend>(base: Scalar<B>, exponent: i64) -> BlasResult<Scalar<B>> {
    if exponent == 0 {
        if base.definitely_zero() {
            crate::trace_dispatch!("hyperlattice", "powi", "zero-to-zero-domain-error");
            return Err(Problem::NotANumber);
        }
        crate::trace_dispatch!("hyperlattice", "powi", "exponent-zero-one");
        return Ok(Scalar::<B>::one());
    }

    let exp = exponent.unsigned_abs();
    // The hyperreal backend opts into hard-coded tiny exponents because the generic
    // squaring loop clones enough symbolic state to show up in scalar and matrix benches.
    let positive = match (B::SPECIALIZE_SCALAR_POWI, exp) {
        (_, 1) => {
            crate::trace_dispatch!("hyperlattice", "powi", "exponent-one");
            base
        }
        (true, 2) => {
            crate::trace_dispatch!("hyperlattice", "powi", "specialized-square");
            base.clone() * base
        }
        (true, 3) => {
            crate::trace_dispatch!("hyperlattice", "powi", "specialized-cube");
            let square = base.clone() * base.clone();
            square * base
        }
        (true, 4) => {
            crate::trace_dispatch!("hyperlattice", "powi", "specialized-fourth");
            let square = base.clone() * base;
            square.clone() * square
        }
        (true, 5) => {
            crate::trace_dispatch!("hyperlattice", "powi", "specialized-fifth");
            let square = base.clone() * base.clone();
            let fourth = square.clone() * square;
            fourth * base
        }
        _ => {
            crate::trace_dispatch!("hyperlattice", "powi", "generic-squaring");
            powi_by_squaring(base, exp)
        }
    };

    if exponent < 0 {
        crate::trace_dispatch!("hyperlattice", "powi", "negative-inverse");
        positive.inverse()
    } else {
        Ok(positive)
    }
}

fn powi_by_squaring<B: Backend>(base: Scalar<B>, exponent: u64) -> Scalar<B> {
    let mut exp = exponent;
    let mut result = None;
    let mut factor = base;
    while exp > 0 {
        if exp & 1 == 1 {
            result = Some(match result {
                Some(result) => result * factor.clone(),
                None => factor.clone(),
            });
        }
        exp >>= 1;
        if exp > 0 {
            factor = factor.clone() * factor;
        }
    }

    result.expect("non-zero exponent sets at least one result bit")
}

/// Returns `e` raised to `value`.
pub fn exp<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "exp");
    value.exp()
}

/// Returns the natural logarithm of `value`.
pub fn ln<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "ln");
    value.ln()
}

/// Returns the base-10 logarithm of `value`.
pub fn log10<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "log10");
    value.log10()
}

/// Returns the base-10 logarithm after attaching an abort signal.
pub fn log10_with_abort<B: Backend>(
    value: Scalar<B>,
    signal: &AbortSignal,
) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "log10-with-abort");
    with_abort(value, signal).log10()
}

/// Returns the principal square root of `value`.
pub fn sqrt<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "sqrt");
    value.sqrt()
}

/// Returns the sine of `value`.
pub fn sin<B: Backend>(value: Scalar<B>) -> Scalar<B> {
    crate::trace_dispatch!("hyperlattice", "free_function", "sin");
    value.sin()
}

/// Returns the cosine of `value`.
pub fn cos<B: Backend>(value: Scalar<B>) -> Scalar<B> {
    crate::trace_dispatch!("hyperlattice", "free_function", "cos");
    value.cos()
}

/// Returns the tangent of `value`.
pub fn tan<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "tan");
    value.tan()
}

/// Returns the hyperbolic sine of `value`.
pub fn sinh<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "sinh-exp-formula");
    let positive = value.clone().exp()?;
    let negative = (-value).exp()?;
    (positive - negative) / two()
}

/// Returns the hyperbolic cosine of `value`.
pub fn cosh<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "cosh-exp-formula");
    let positive = value.clone().exp()?;
    let negative = (-value).exp()?;
    (positive + negative) / two()
}

/// Returns the hyperbolic tangent of `value`.
pub fn tanh<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "tanh-exp-formula");
    let positive = value.clone().exp()?;
    let negative = (-value).exp()?;
    (positive.clone() - negative.clone()) / (positive + negative)
}

/// Returns the inverse sine of `value`.
pub fn asin<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "asin");
    value.asin()
}

/// Returns the inverse sine after attaching an abort signal.
pub fn asin_with_abort<B: Backend>(
    value: Scalar<B>,
    signal: &AbortSignal,
) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "asin-with-abort");
    with_abort(value, signal).asin()
}

/// Returns the inverse cosine of `value`.
pub fn acos<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "acos");
    value.acos()
}

/// Returns the inverse cosine after attaching an abort signal.
pub fn acos_with_abort<B: Backend>(
    value: Scalar<B>,
    signal: &AbortSignal,
) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "acos-with-abort");
    with_abort(value, signal).acos()
}

/// Returns the inverse tangent of `value`.
pub fn atan<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "atan");
    value.atan()
}

/// Returns the inverse tangent after attaching an abort signal.
pub fn atan_with_abort<B: Backend>(
    value: Scalar<B>,
    signal: &AbortSignal,
) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "atan-with-abort");
    with_abort(value, signal).atan()
}

/// Returns the inverse hyperbolic sine of `value`.
pub fn asinh<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "asinh");
    value.asinh()
}

/// Returns the inverse hyperbolic sine after attaching an abort signal.
pub fn asinh_with_abort<B: Backend>(
    value: Scalar<B>,
    signal: &AbortSignal,
) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "asinh-with-abort");
    with_abort(value, signal).asinh()
}

/// Returns the inverse hyperbolic cosine of `value`.
pub fn acosh<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "acosh");
    value.acosh()
}

/// Returns the inverse hyperbolic cosine after attaching an abort signal.
pub fn acosh_with_abort<B: Backend>(
    value: Scalar<B>,
    signal: &AbortSignal,
) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "acosh-with-abort");
    with_abort(value, signal).acosh()
}

/// Returns the inverse hyperbolic tangent of `value`.
pub fn atanh<B: Backend>(value: Scalar<B>) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "atanh");
    value.atanh()
}

/// Returns the inverse hyperbolic tangent after attaching an abort signal.
pub fn atanh_with_abort<B: Backend>(
    value: Scalar<B>,
    signal: &AbortSignal,
) -> BlasResult<Scalar<B>> {
    crate::trace_dispatch!("hyperlattice", "free_function", "atanh-with-abort");
    with_abort(value, signal).atanh()
}