Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ pub fn format_boxed<A: Display>(tensor: &dyn Tensor<A>) -> String {
format_tensor(tensor.domain().shape(), &|index| tensor.apply(index))
}

// A tensor whose type was erased, as `rewrite` returns, prints the same way.
impl<A: Display> Display for dyn Tensor<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&format_boxed(self))
}
}

impl<A: Clone + Display> Display for Physical<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&format_boxed(self))
Expand All @@ -25,8 +32,10 @@ impl<A: Clone + Display> Display for Physical<A> {
// one applied last gives values that print, multisets included.
impl<F, G> Display for Composition<F, G>
where
F: Function<Domain = G::Codomain>,
G: Function<Domain = HRect>,
F: Function<Domain = G::Codomain> + 'static,
G: Function<Domain = HRect> + 'static,
F::Codomain: 'static,
G::Codomain: 'static,
<F::Codomain as Set>::Owned: Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand Down
160 changes: 152 additions & 8 deletions src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//! multisets. Tensors, index maps, index functions and reductions are all
//! functions, and every operation on them is built from these.

use std::any::Any;
use std::borrow::Borrow;
use std::rc::Rc;

Expand All @@ -11,6 +12,10 @@ use crate::sets::{Multisets, Set, Values};
/// of values, or of multisets of either. A tensor goes from indices to values,
/// an index map from indices to indices, an index function from indices to
/// multisets of indices, and a reduction from multisets of values to values.
///
/// Besides `apply`, a function can describe itself so that `rewrite` can find
/// the identities of the paper that apply to it. Every such method has a
/// default that finds nothing, which is always correct.
pub trait Function {
type Domain: Set;
type Codomain: Set;
Expand All @@ -20,10 +25,51 @@ pub trait Function {
fn domain(&self) -> Self::Domain;

fn codomain(&self) -> Self::Codomain;

/// An equivalent function that is cheaper to evaluate, or `None` when no
/// identity applies anywhere inside this one.
fn rewritten(
&self,
) -> Option<Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Codomain>>> {
None
}

/// When this is a reduction `Ω` after a function returning multisets of at
/// most one element, and `f` keeps the neutral element of `Ω`: `f` after
/// this, rewritten as `Ω ∘ f̄` after that function. `f` is given as an
/// `Rc<dyn Function>` from the codomain of this to itself, behind `Any`.
fn absorbed(
&self,
_f: &dyn Any,
) -> Option<Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Codomain>>> {
None
}

/// When this is a reduction and `f` keeps its neutral element: `f̄`, the
/// extension of `f` to the multisets this reduces. `f` is given as for
/// `absorbed`.
fn lifted_keeping_neutral(
&self,
_f: &dyn Any,
) -> Option<Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Domain>>> {
None
}

/// Whether every multiset this returns holds at most one element.
fn returns_at_most_one(&self) -> bool {
false
}

/// Whether this maps each multiset to one of the same size, as the
/// extension of a function to multisets does.
fn keeps_sizes(&self) -> bool {
false
}
}

// A shared function is the same function, so that one can be used in several
// compositions, or have its type erased as an `Rc<dyn Tensor<A>>`.
// compositions, or have its type erased as an `Rc<dyn Tensor<A>>`. Rewriting
// sees through it.
impl<T: Function + ?Sized> Function for Rc<T> {
type Domain = T::Domain;
type Codomain = T::Codomain;
Expand All @@ -39,12 +85,41 @@ impl<T: Function + ?Sized> Function for Rc<T> {
fn codomain(&self) -> Self::Codomain {
(**self).codomain()
}

fn rewritten(
&self,
) -> Option<Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Codomain>>> {
(**self).rewritten()
}

fn absorbed(
&self,
f: &dyn Any,
) -> Option<Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Codomain>>> {
(**self).absorbed(f)
}

fn lifted_keeping_neutral(
&self,
f: &dyn Any,
) -> Option<Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Domain>>> {
(**self).lifted_keeping_neutral(f)
}

fn returns_at_most_one(&self) -> bool {
(**self).returns_at_most_one()
}

fn keeps_sizes(&self) -> bool {
(**self).keeps_sizes()
}
}

/// `f ∘ g`: applies `g`, then `f` to the result.
pub struct Composition<F, G> {
f: F,
g: G,
// Shared, so that rewriting can reuse them without taking this apart.
pub(crate) f: Rc<F>,
pub(crate) g: Rc<G>,
}

/// Composes `f` after `g`. Composing a tensor after an index map re-indexes it,
Expand All @@ -60,13 +135,19 @@ where
codomain.lies_in(&domain),
"the inner function lands in {codomain:?}, which does not lie in the domain {domain:?} of the outer one"
);
Composition { f, g }
Composition {
f: Rc::new(f),
g: Rc::new(g),
}
}

impl<F, G> Function for Composition<F, G>
where
F: Function<Domain = G::Codomain>,
G: Function,
F: Function<Domain = G::Codomain> + 'static,
G: Function + 'static,
F::Codomain: 'static,
G::Domain: 'static,
G::Codomain: 'static,
{
type Domain = G::Domain;
type Codomain = F::Codomain;
Expand All @@ -82,21 +163,73 @@ where
fn codomain(&self) -> Self::Codomain {
self.f.codomain()
}

// Rewrites both sides, then `f` after the rewritten `g` with Theorem 1, which
// `absorbed` checks the conditions of.
fn rewritten(
&self,
) -> Option<Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Codomain>>> {
let new_f = self.f.rewritten();
let new_g = self.g.rewritten();
let changed = new_f.is_some() || new_g.is_some();
let f: Rc<dyn Function<Domain = F::Domain, Codomain = F::Codomain>> =
new_f.unwrap_or_else(|| self.f.clone());
let g: Rc<dyn Function<Domain = G::Domain, Codomain = G::Codomain>> =
new_g.unwrap_or_else(|| self.g.clone());
if let Some(absorbed) = g.absorbed(&f) {
// `f` was taken for a function from the codomain of `g` to itself, so
// the codomain of `g` is that of `f`, as the downcast confirms.
let absorbed: Box<dyn Any> = Box::new(absorbed);
if let Ok(absorbed) = absorbed
.downcast::<Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Codomain>>>()
{
return Some(*absorbed);
}
}
changed.then(|| {
Rc::new(compose(f, g))
as Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Codomain>>
})
}

// Here this is `Ω ∘ H`, with `Ω` in `f` and `H` in `g`.
fn absorbed(
&self,
f: &dyn Any,
) -> Option<Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Codomain>>> {
if !self.g.returns_at_most_one() {
return None;
}
let lifted = self.f.lifted_keeping_neutral(f)?;
// Erased, so that the result has the same type whatever this one is, and
// rewriting it again does not build ever larger types.
let omega: Rc<dyn Function<Domain = F::Domain, Codomain = F::Codomain>> = self.f.clone();
let inner: Rc<dyn Function<Domain = G::Domain, Codomain = G::Codomain>> = self.g.clone();
Some(Rc::new(compose(omega, compose(lifted, inner))))
}

fn returns_at_most_one(&self) -> bool {
self.g.returns_at_most_one() && self.f.keeps_sizes()
}
}

/// A function from multisets to multisets: the extension of `f` to multisets,
/// written `f̄` in the paper. It maps a multiset to the multiset of the images
/// of its elements, repeats included, so it goes from the multisets of the
/// domain of `f` to those of its codomain.
pub struct MultiFunction<F> {
f: F,
pub(crate) f: F,
}

pub fn multiset_lift<F: Function>(f: F) -> MultiFunction<F> {
MultiFunction { f }
}

impl<F: Function> Function for MultiFunction<F> {
impl<F: Function> Function for MultiFunction<F>
where
F::Domain: 'static,
F::Codomain: 'static,
{
type Domain = Multisets<F::Domain>;
type Codomain = Multisets<F::Codomain>;

Expand All @@ -113,6 +246,17 @@ impl<F: Function> Function for MultiFunction<F> {
fn codomain(&self) -> Self::Codomain {
Multisets::new(self.f.codomain())
}

fn rewritten(
&self,
) -> Option<Rc<dyn Function<Domain = Self::Domain, Codomain = Self::Codomain>>> {
let rewritten = self.f.rewritten()?;
Some(Rc::new(multiset_lift(rewritten)))
}

fn keeps_sizes(&self) -> bool {
true
}
}

/// A function on values, given as a closure, from `A` to `B`. Composed after a
Expand Down
14 changes: 7 additions & 7 deletions src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ pub fn where_<A>(
/// Spreads a vector over the diagonal of a tensor of the given rank: rank two
/// gives a diagonal matrix, rank three a tensor whose only non-zero indices
/// are of the form `[i, i, i]`.
pub fn diagonalize<A: Clone, U: Tensor<A>>(
pub fn diagonalize<A: Clone + PartialEq + 'static, U: Tensor<A> + 'static>(
u: U,
rank: usize,
) -> ReductionTensor<Sum<A>, U, Diagonal>
Expand All @@ -224,7 +224,7 @@ where

/// Reducing over the empty set gives the reduction's neutral element at every
/// index, so a constant tensor needs no underlying data at all.
fn neutral<R: Reduction<f32>>(
fn neutral<R: Reduction<f32> + 'static>(
shape: Vec<usize>,
) -> ReductionTensor<ReductionFunction<R>, Physical, EmptyMapping> {
let empty = EmptyMapping::new(HRect::new(shape), HRect::new(vec![0]));
Expand Down Expand Up @@ -266,7 +266,7 @@ pub fn eye(
/// `indices`, and zero everywhere else. As in torch, `indices` has one row per
/// dimension, so column `k` is the coordinate of `values[k]`, and values at a
/// repeated coordinate add up.
pub fn sparse_coo_tensor<A: Clone, U: Tensor<A>>(
pub fn sparse_coo_tensor<A: Clone + PartialEq + 'static, U: Tensor<A> + 'static>(
indices: Vec<Vec<usize>>,
values: U,
size: Vec<usize>,
Expand Down Expand Up @@ -312,7 +312,7 @@ where
/// `physical` sits at `basis·x + offset`, and the tensor is zero off that
/// lattice. `basis` has a row per dimension of `shape` and a column per
/// dimension of `physical`. Values the lattice sends to one index add up.
pub fn sparse_latticed_tensor<A: Clone, U: Tensor<A>>(
pub fn sparse_latticed_tensor<A: Clone + PartialEq + 'static, U: Tensor<A> + 'static>(
physical: U,
basis: Vec<Vec<i64>>,
offset: Vec<i64>,
Expand All @@ -328,7 +328,7 @@ where
)
}

pub fn sum<A: Clone, U: Tensor<A>>(
pub fn sum<A: Clone + PartialEq + 'static, U: Tensor<A> + 'static>(
input: U,
dim: usize,
) -> ReductionTensor<Sum<A>, U, InvProjection>
Expand All @@ -339,7 +339,7 @@ where
compose(Sum::new(), compose(multiset_lift(input), rows))
}

pub fn prod<A: Clone, U: Tensor<A>>(
pub fn prod<A: Clone + PartialEq + 'static, U: Tensor<A> + 'static>(
input: U,
dim: usize,
) -> ReductionTensor<Product<A>, U, InvProjection>
Expand All @@ -354,7 +354,7 @@ where
/// matrices at each `[m, n, p]`.
type Products<A> = ReductionTensor<Product<A>, Composition<JaggedTensor<A>, Concat>, InvProjection>;

pub fn mm<A: Clone + 'static, U: Tensor<A> + 'static, V: Tensor<A> + 'static>(
pub fn mm<A: Clone + PartialEq + 'static, U: Tensor<A> + 'static, V: Tensor<A> + 'static>(
mat1: U,
mat2: V,
) -> ReductionTensor<Sum<A>, Products<A>, InvProjection>
Expand Down
Loading
Loading