Skip to content

Commit a307be8

Browse files
authored
Add Affine and InvAffine for sparse latticed tensors (#15)
- Add Affine (basis·x + offset) and its inverse InvAffine, which solves for the physical indices directly instead of scanning them - Add sparse_latticed_tensor, a Sum over InvAffine - Test the sparse latticed tensor examples and check InvAffine against a scan on 1000 random lattices
1 parent 64a6993 commit a307be8

7 files changed

Lines changed: 725 additions & 14 deletions

File tree

‎src/functions.rs‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ use std::rc::Rc;
88
use crate::display::BoxedTensor;
99
use crate::domain::HRect;
1010
use crate::mapping::{
11-
COO, Concat, Diagonal, EmptyMapping, InvProjection, Permutation, Projection, Squeeze,
12-
Unsqueeze, Where,
11+
Affine, COO, Concat, Diagonal, EmptyMapping, InvAffine, InvProjection, Permutation, Projection,
12+
Squeeze, Unsqueeze, Where,
1313
};
1414
use crate::tensor::{
1515
JaggedTensor, LeftComposition, Physical, Product, Reduction, ReductionTensor, RightComposition,
@@ -269,6 +269,20 @@ pub fn sparse_coo_tensor(
269269
Sum::new(values, Rc::new(COO::new(HRect::new(size), coordinates)))
270270
}
271271

272+
/// A sparse latticed tensor of shape `shape`: the value at index `x` of
273+
/// `physical` sits at `basis·x + offset`, and the tensor is zero off that
274+
/// lattice. `basis` has a row per dimension of `shape` and a column per
275+
/// dimension of `physical`. Values the lattice sends to one index add up.
276+
pub fn sparse_latticed_tensor<T: BoxedTensor + 'static>(
277+
physical: Rc<T>,
278+
basis: Vec<Vec<i64>>,
279+
offset: Vec<i64>,
280+
shape: Vec<usize>,
281+
) -> Sum<InvAffine> {
282+
let affine = Affine::new(physical.hrect().clone(), basis, offset, HRect::new(shape));
283+
Sum::new(physical, Rc::new(InvAffine::new(affine)))
284+
}
285+
272286
pub fn sum<T: BoxedTensor + 'static>(input: Rc<T>, dim: usize) -> Sum<InvProjection> {
273287
let codomain = input.hrect().clone();
274288
Sum::new(input, Rc::new(InvProjection::new(codomain, dim)))

‎src/lattice.rs‎

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
//! Inverting an affine map on a box without scanning the box: finding every
2+
//! index `x` with `basis·x = c` and `0 <= x_j < extents[j]`.
3+
//!
4+
//! Integer column operations of determinant ±1 bring the basis to
5+
//! `basis·[particular | kernel] = [h | 0]`, where `h` is a staircase of full
6+
//! column rank. Every integer solution is then `x = particular·z + kernel·t`,
7+
//! exactly: `z` is unique and found by substitution down the staircase of `h`,
8+
//! and `t` ranges over the integer kernel. The kernel's basis is brought to a
9+
//! staircase too, so that each coordinate of `t` in turn gets an exact range
10+
//! from the extents.
11+
12+
/// The indices of a box that `x ↦ basis·x` sends to a given point.
13+
pub(crate) struct Preimage {
14+
h: Vec<Vec<i64>>,
15+
h_pivots: Vec<usize>,
16+
particular: Vec<Vec<i64>>,
17+
kernel: Vec<Vec<i64>>,
18+
kernel_pivots: Vec<usize>,
19+
extents: Vec<i64>,
20+
}
21+
22+
impl Preimage {
23+
pub(crate) fn new(basis: &[Vec<i64>], extents: &[usize]) -> Self {
24+
let n = extents.len();
25+
let (echelon, operations, h_pivots) = column_echelon(basis.to_vec(), n);
26+
let r = h_pivots.len();
27+
let h = echelon.iter().map(|row| row[..r].to_vec()).collect();
28+
let particular = operations.iter().map(|row| row[..r].to_vec()).collect();
29+
let free = operations.iter().map(|row| row[r..].to_vec()).collect();
30+
let (kernel, _, kernel_pivots) = column_echelon(free, n - r);
31+
Self {
32+
h,
33+
h_pivots,
34+
particular,
35+
kernel,
36+
kernel_pivots,
37+
extents: extents.iter().map(|&extent| extent as i64).collect(),
38+
}
39+
}
40+
41+
/// Every index `x` of the box with `basis·x = c`.
42+
pub(crate) fn solve(&self, c: &[i64]) -> Vec<Vec<usize>> {
43+
let mut z = vec![0; self.h_pivots.len()];
44+
for (i, &row) in self.h_pivots.iter().enumerate() {
45+
let rest = c[row] - dot(&self.h[row][..i], &z[..i]);
46+
let step = self.h[row][i];
47+
if rest % step != 0 {
48+
return Vec::new();
49+
}
50+
z[i] = rest / step;
51+
}
52+
// The rows between pivots must hold too.
53+
if self
54+
.h
55+
.iter()
56+
.zip(c)
57+
.any(|(row, &target)| dot(row, &z) != target)
58+
{
59+
return Vec::new();
60+
}
61+
let mut x: Vec<i64> = self.particular.iter().map(|row| dot(row, &z)).collect();
62+
// Coordinates above the kernel's first pivot are already final.
63+
let fixed = self.kernel_pivots.first().copied().unwrap_or(x.len());
64+
if !(0..fixed).all(|j| (0..self.extents[j]).contains(&x[j])) {
65+
return Vec::new();
66+
}
67+
let mut found = Vec::new();
68+
self.enumerate(0, &mut x, &mut found);
69+
found
70+
}
71+
72+
/// Tries every value of `t[level]` that keeps the coordinates it settles in
73+
/// range, these being the rows from its pivot to the next one.
74+
fn enumerate(&self, level: usize, x: &mut [i64], found: &mut Vec<Vec<usize>>) {
75+
if level == self.kernel_pivots.len() {
76+
found.push(x.iter().map(|&coord| coord as usize).collect());
77+
return;
78+
}
79+
let end = self
80+
.kernel_pivots
81+
.get(level + 1)
82+
.copied()
83+
.unwrap_or(x.len());
84+
let rows = self.kernel_pivots[level]..end;
85+
let settled = self.kernel[rows.clone()]
86+
.iter()
87+
.zip(&x[rows.clone()])
88+
.zip(&self.extents[rows]);
89+
let (mut low, mut high) = (i64::MIN, i64::MAX);
90+
for ((row, &coord), &extent) in settled {
91+
let (step, last) = (row[level], extent - 1);
92+
if step > 0 {
93+
low = low.max(ceil_div(-coord, step));
94+
high = high.min(floor_div(last - coord, step));
95+
} else if step < 0 {
96+
low = low.max(ceil_div(last - coord, step));
97+
high = high.min(floor_div(-coord, step));
98+
} else if !(0..=last).contains(&coord) {
99+
return;
100+
}
101+
}
102+
for t in low..=high {
103+
for (coord, row) in x.iter_mut().zip(&self.kernel) {
104+
*coord += row[level] * t;
105+
}
106+
self.enumerate(level + 1, x, found);
107+
for (coord, row) in x.iter_mut().zip(&self.kernel) {
108+
*coord -= row[level] * t;
109+
}
110+
}
111+
}
112+
}
113+
114+
/// Brings `matrix` to column echelon form by integer column operations of
115+
/// determinant ±1. Returns the echelon form `e`, the operations `v` with
116+
/// `matrix·v = e`, and the pivot row of each column of `e` that is not zero.
117+
/// Those columns come first: each is zero above its pivot, and every column is
118+
/// zero to the right of a pivot.
119+
fn column_echelon(
120+
mut matrix: Vec<Vec<i64>>,
121+
cols: usize,
122+
) -> (Vec<Vec<i64>>, Vec<Vec<i64>>, Vec<usize>) {
123+
let mut operations: Vec<Vec<i64>> = (0..cols)
124+
.map(|i| (0..cols).map(|j| i64::from(i == j)).collect())
125+
.collect();
126+
let mut pivots = Vec::new();
127+
for row in 0..matrix.len() {
128+
let c = pivots.len();
129+
if c == cols {
130+
break;
131+
}
132+
// Folds every entry right of column `c` into it, leaving their gcd there.
133+
for j in c + 1..cols {
134+
let (a, b) = (matrix[row][c], matrix[row][j]);
135+
if b != 0 {
136+
let (g, s, t) = ext_gcd(a, b);
137+
let operation = (s, t, -b / g, a / g);
138+
column_op(&mut matrix, c, j, operation);
139+
column_op(&mut operations, c, j, operation);
140+
}
141+
}
142+
if matrix[row][c] != 0 {
143+
pivots.push(row);
144+
}
145+
}
146+
(matrix, operations, pivots)
147+
}
148+
149+
/// Turns columns `c` and `j` into `s·c + t·j` and `u·c + w·j`.
150+
fn column_op(matrix: &mut [Vec<i64>], c: usize, j: usize, (s, t, u, w): (i64, i64, i64, i64)) {
151+
for row in matrix {
152+
let (x, y) = (row[c], row[j]);
153+
row[c] = s * x + t * y;
154+
row[j] = u * x + w * y;
155+
}
156+
}
157+
158+
/// `(g, s, t)` with `s·a + t·b = g`, where `g` is the gcd of `a` and `b`, and
159+
/// is not negative.
160+
fn ext_gcd(a: i64, b: i64) -> (i64, i64, i64) {
161+
if b == 0 {
162+
if a < 0 { (-a, -1, 0) } else { (a, 1, 0) }
163+
} else {
164+
let (g, s, t) = ext_gcd(b, a % b);
165+
(g, t, s - (a / b) * t)
166+
}
167+
}
168+
169+
fn dot(a: &[i64], b: &[i64]) -> i64 {
170+
a.iter().zip(b).map(|(x, y)| x * y).sum()
171+
}
172+
173+
fn floor_div(n: i64, d: i64) -> i64 {
174+
if d < 0 {
175+
(-n).div_euclid(-d)
176+
} else {
177+
n.div_euclid(d)
178+
}
179+
}
180+
181+
fn ceil_div(n: i64, d: i64) -> i64 {
182+
-floor_div(-n, d)
183+
}

‎src/lib.rs‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
pub mod display;
55
pub mod domain;
66
pub mod functions;
7+
mod lattice;
78
pub mod mapping;
89
pub mod signature;
910
pub mod tensor;
@@ -12,13 +13,13 @@ pub use display::{BoxedTensor, format_boxed};
1213
pub use domain::{Domain, HRect, JaggedDomain};
1314
pub use functions::{
1415
Dims, clamp, concatenate, diagonalize, eye, eye_rect, mm, movedim, negate, ones, permute, pow,
15-
prod, scale, sparse_coo_tensor, square, squeeze, stack, sum, transpose, unsqueeze, where_,
16-
zeros,
16+
prod, scale, sparse_coo_tensor, sparse_latticed_tensor, square, squeeze, stack, sum, transpose,
17+
unsqueeze, where_, zeros,
1718
};
1819
pub use mapping::{
19-
BoxedMapping, BoxedPowersetMapping, COO, Concat, Diagonal, EmptyMapping, IndexMapping,
20-
InvProjection, Permutation, Powerset, PowersetMapping, Projection, Squeeze, Stride, Unsqueeze,
21-
Where,
20+
Affine, BoxedMapping, BoxedPowersetMapping, COO, Concat, Diagonal, EmptyMapping, IndexMapping,
21+
InvAffine, InvProjection, Permutation, Powerset, PowersetMapping, Projection, Squeeze, Stride,
22+
Unsqueeze, Where,
2223
};
2324
pub use signature::{HRectSignature, Signature};
2425
pub use tensor::{

‎src/mapping.rs‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::rc::Rc;
33

44
use crate::display::BoxedTensor;
55
use crate::domain::{Domain, HRect, JaggedDomain};
6+
use crate::lattice::Preimage;
67
use crate::signature::{HRectSignature, Signature};
78

89
/// A set of indices, as returned by a `PowersetMapping`.
@@ -575,3 +576,130 @@ impl HRectPowersetMapping for InvProjection {
575576
&self.signature
576577
}
577578
}
579+
580+
/// The affine map `x ↦ basis·x + offset`. `basis` has a row per dimension of the
581+
/// codomain and a column per dimension of the domain. Its entries and `offset`
582+
/// may be negative, as long as every index of the domain lands in the codomain.
583+
/// Read through this, a tensor gives its values on a lattice, e.g. its diagonal
584+
/// with `basis = [[1], [1]]`.
585+
pub struct Affine {
586+
signature: HRectSignature,
587+
basis: Vec<Vec<i64>>,
588+
offset: Vec<i64>,
589+
}
590+
591+
impl Affine {
592+
pub fn new(domain: HRect, basis: Vec<Vec<i64>>, offset: Vec<i64>, codomain: HRect) -> Self {
593+
assert_eq!(
594+
basis.len(),
595+
codomain.ndim(),
596+
"a basis row per dimension of the codomain is required"
597+
);
598+
assert!(
599+
basis.iter().all(|row| row.len() == domain.ndim()),
600+
"a basis column per dimension of the domain is required"
601+
);
602+
assert_eq!(
603+
offset.len(),
604+
codomain.ndim(),
605+
"an offset per dimension of the codomain is required"
606+
);
607+
// An empty domain has no index to land anywhere.
608+
if !domain.shape().contains(&0) {
609+
for (i, (row, &start)) in basis.iter().zip(&offset).enumerate() {
610+
// Each coordinate varies on its own, so each term is at its
611+
// smallest and largest at one end or the other of its range.
612+
let (lowest, highest) = row.iter().zip(domain.shape()).fold(
613+
(start, start),
614+
|(low, high), (&step, &extent)| {
615+
let end = step * (extent as i64 - 1);
616+
(low + end.min(0), high + end.max(0))
617+
},
618+
);
619+
assert!(
620+
0 <= lowest && highest < codomain.shape()[i] as i64,
621+
"the lattice reaches {lowest} to {highest} along dimension {i}, which has extent {}",
622+
codomain.shape()[i]
623+
);
624+
}
625+
}
626+
Self {
627+
signature: HRectSignature::new(domain, codomain),
628+
basis,
629+
offset,
630+
}
631+
}
632+
}
633+
634+
impl HRectMapping for Affine {
635+
type Codomain = HRect;
636+
637+
fn map(&self, index: &[usize]) -> Vec<usize> {
638+
// Every coordinate is non-negative, as checked when constructing.
639+
self.basis
640+
.iter()
641+
.zip(&self.offset)
642+
.map(|(row, &start)| {
643+
let coord = start
644+
+ row
645+
.iter()
646+
.zip(index)
647+
.map(|(&step, &x)| step * x as i64)
648+
.sum::<i64>();
649+
coord as usize
650+
})
651+
.collect()
652+
}
653+
654+
fn signature(&self) -> &HRectSignature {
655+
&self.signature
656+
}
657+
}
658+
659+
/// The inverse of an `Affine`: sends each index of its codomain back to the
660+
/// indices of its domain that land on it. There are none off the lattice, so a
661+
/// sum over this lays its underlying tensor out on the lattice and is zero
662+
/// elsewhere: a sparse latticed tensor. They are found by solving
663+
/// `basis·x = index - offset`, so a read costs about as much as the basis is
664+
/// large, however large the tensors.
665+
pub struct InvAffine {
666+
signature: HRectSignature,
667+
offset: Vec<i64>,
668+
preimage: Preimage,
669+
}
670+
671+
impl InvAffine {
672+
pub fn new(affine: Affine) -> Self {
673+
let Affine {
674+
signature,
675+
basis,
676+
offset,
677+
} = affine;
678+
let preimage = Preimage::new(&basis, signature.domain().shape());
679+
Self {
680+
signature: HRectSignature::new(
681+
signature.codomain().clone(),
682+
signature.domain().clone(),
683+
),
684+
offset,
685+
preimage,
686+
}
687+
}
688+
}
689+
690+
impl HRectPowersetMapping for InvAffine {
691+
type Codomain = HRect;
692+
693+
fn map(&self, index: &[usize]) -> Powerset {
694+
let target: Vec<i64> = index
695+
.iter()
696+
.zip(&self.offset)
697+
.map(|(&coord, &start)| coord as i64 - start)
698+
.collect();
699+
self.preimage.solve(&target).into_iter().collect()
700+
}
701+
702+
fn signature(&self) -> &HRectSignature {
703+
&self.signature
704+
}
705+
}

0 commit comments

Comments
 (0)