Skip to content
Draft
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
201 changes: 201 additions & 0 deletions src/expr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
//! Tensors read as expressions: the tree of building blocks a tensor is
//! composed of, with their types erased, so that it can be inspected and
//! rewritten into an equal one before it is evaluated. The compositions of
//! `function` fix their shape in their type, which a rewrite cannot change; an
//! `Expr` holds it as data.
//!
//! There is no second way of building a tensor here. The tree of any tensor
//! built with the functions of this crate is read through `Function::parts`
//! when it is rewritten, and every node of an expression evaluates as the
//! composition it stands for, built with `compose` and `multiset_lift` out of
//! the very parts it was read from.

use std::fmt;
use std::rc::Rc;

use crate::function::{Function, Parts, compose, multiset_lift};
use crate::multiset::Multiset;
use crate::sets::{HRect, Multisets, Values};
use crate::tensor::Tensor;

/// A tensor, with its type erased.
pub type TensorMap<A> = Rc<dyn Function<Domain = HRect, Codomain = Values<A>>>;

/// A function on values `f: 𝕊 → 𝕊`, with its type erased.
pub type ValueMap<A> = Rc<dyn Function<Domain = Values<A>, Codomain = Values<A>>>;

/// An index map `ρ`, with its type erased.
pub type IndexMap = Rc<dyn Function<Domain = HRect, Codomain = HRect>>;

/// An index function to multisets of indices `ψ`, with its type erased. Its
/// codomain tells how many indices it may send one to.
pub type MultiIndexMap = Rc<dyn Function<Domain = HRect, Codomain = Multisets<HRect>>>;

/// A reduction `Ω`, with its type erased. Its neutral element is what it gives
/// for the empty multiset.
pub type ReductionMap<A> = Rc<dyn Function<Domain = Multisets<Values<A>>, Codomain = Values<A>>>;

/// A tensor on a hrect, read as an expression tree. Cloning one shares the
/// tree, and a rewrite shares every subtree it leaves unchanged.
pub struct Expr<A = f32>(Rc<Inner<A>>);

struct Inner<A> {
node: Node<A>,
// What the node evaluates as: the tensor it was read from, or the
// composition of its parts.
tensor: TensorMap<A>,
}

/// The node at the root of an expression.
pub enum Node<A = f32> {
/// A tensor that is not looked into: a leaf of the tree, such as the
/// physical tensor holding the stored values of a sparse tensor.
Tensor(TensorMap<A>),
/// `f ∘ T`: `f` applied to each value of `T`.
Map { f: ValueMap<A>, input: Expr<A> },
/// `T ∘ ρ`: `T` read through the index map `ρ`.
Reindex { input: Expr<A>, rho: IndexMap },
/// `Ω ∘ Ū ∘ ψ`: at each index, `Ω` of the values of `U` at the indices `ψ`
/// maps it to.
Reduce {
omega: ReductionMap<A>,
u: Expr<A>,
psi: MultiIndexMap,
},
}

// Written out rather than derived, which would require `A: Clone`: cloning an
// expression only shares it.
impl<A> Clone for Expr<A> {
fn clone(&self) -> Self {
Self(Rc::clone(&self.0))
}
}

impl<A> Expr<A> {
pub fn node(&self) -> &Node<A> {
&self.0.node
}

/// The tensor the expression evaluates as.
pub fn tensor(&self) -> TensorMap<A> {
Rc::clone(&self.0.tensor)
}

/// Whether two expressions are the same one, not only equal.
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}

impl<A: 'static> Expr<A> {
/// The expression of `tensor`, read from the way it was built. What is not
/// a composition of a function on values after a tensor, of a tensor after
/// an index map, or of a reduction after a lifted tensor after an index
/// function, is a leaf: a function on values from another type, a jagged
/// tensor, or any tensor whose parts are not known.
pub(crate) fn of(tensor: impl Tensor<A> + 'static) -> Self {
Self::read(Rc::new(tensor))
}

fn read(tensor: TensorMap<A>) -> Self {
let node = Self::node_of(&tensor).unwrap_or_else(|| Node::Tensor(Rc::clone(&tensor)));
Self(Rc::new(Inner { node, tensor }))
}

fn node_of(tensor: &TensorMap<A>) -> Option<Node<A>> {
let Parts::Composition { outer, inner } = tensor.parts()? else {
return None;
};
if let (Some(f), Some(input)) = (
outer.get::<Values<A>, Values<A>>(),
inner.get::<HRect, Values<A>>(),
) {
return Some(Node::Map {
f,
input: Self::read(input),
});
}
if let (Some(input), Some(rho)) =
(outer.get::<HRect, Values<A>>(), inner.get::<HRect, HRect>())
{
return Some(Node::Reindex {
input: Self::read(input),
rho,
});
}
let omega = outer.get::<Multisets<Values<A>>, Values<A>>()?;
let lifted = inner.get::<HRect, Multisets<Values<A>>>()?;
let Parts::Composition { outer, inner } = lifted.parts()? else {
return None;
};
let lift = outer.get::<Multisets<HRect>, Multisets<Values<A>>>()?;
let psi = inner.get::<HRect, Multisets<HRect>>()?;
let Parts::Lift(u) = lift.parts()? else {
return None;
};
Some(Node::Reduce {
omega,
u: Self::read(u.get::<HRect, Values<A>>()?),
psi,
})
}

/// The expression with `node` at its root, which evaluates as the
/// composition of its parts. As with `compose`, what an index map or index
/// function lands in must lie in the domain of what is read through it.
pub fn new(node: Node<A>) -> Self {
let tensor: TensorMap<A> = match &node {
Node::Tensor(tensor) => Rc::clone(tensor),
Node::Map { f, input } => Rc::new(compose(Rc::clone(f), input.tensor())),
Node::Reindex { input, rho } => Rc::new(compose(input.tensor(), Rc::clone(rho))),
Node::Reduce { omega, u, psi } => Rc::new(compose(
Rc::clone(omega),
compose(multiset_lift(u.tensor()), Rc::clone(psi)),
)),
};
Self(Rc::new(Inner { node, tensor }))
}
}

/// The neutral element `e` of a reduction: what it gives for the empty
/// multiset.
pub fn neutral<A>(omega: &ReductionMap<A>) -> A {
omega.apply(&Multiset::default())
}

/// An expression evaluates as the tensor it was read from or built as.
impl<A: 'static> Function for Expr<A> {
type Domain = HRect;
type Codomain = Values<A>;

fn apply(&self, index: &[usize]) -> A {
self.0.tensor.apply(index)
}

fn domain(&self) -> HRect {
self.0.tensor.domain()
}

fn codomain(&self) -> Values<A> {
Values::new()
}

fn parts(&self) -> Option<Parts> {
self.0.tensor.parts()
}
}

/// Prints the shape of the tree, the kind of each node and what it holds:
/// `Reduce(Map(Tensor))` for `Σ ∘ (f ∘ U)‾ ∘ ψ`. The functions at the nodes are
/// not printed, as nothing tells what they are but their values.
impl<A> fmt::Debug for Expr<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.node() {
Node::Tensor(_) => f.write_str("Tensor"),
Node::Map { input, .. } => write!(f, "Map({input:?})"),
Node::Reindex { input, .. } => write!(f, "Reindex({input:?})"),
Node::Reduce { u, .. } => write!(f, "Reduce({u:?})"),
}
}
}
82 changes: 76 additions & 6 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 @@ -20,6 +21,46 @@ pub trait Function {
fn domain(&self) -> Self::Domain;

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

/// What this function is composed of, or `None` for one that is not looked
/// into, such as a physical tensor. This is how a rewrite reads the
/// structure of an expression built with the functions of this crate,
/// without that structure being written out a second time.
fn parts(&self) -> Option<Parts>
where
Self: 'static,
{
None
}
}

/// A function with its type erased down to its domain and codomain, as held by
/// a composition or a lifted function that is taken apart.
pub struct Part(Box<dyn Any>);

impl Part {
pub fn new<F: Function + 'static>(f: Rc<F>) -> Self {
let erased: Rc<dyn Function<Domain = F::Domain, Codomain = F::Codomain>> = f;
Self(Box::new(erased))
}

/// The function, if it goes from `D` to `C`. This is how one tells a function
/// on values from a tensor or an index map: by what it goes between.
pub fn get<D: Set + 'static, C: Set + 'static>(
&self,
) -> Option<Rc<dyn Function<Domain = D, Codomain = C>>> {
self.0
.downcast_ref::<Rc<dyn Function<Domain = D, Codomain = C>>>()
.cloned()
}
}

/// The ways a function is built from others.
pub enum Parts {
/// `outer ∘ inner`.
Composition { outer: Part, inner: Part },
/// `f̄`, the extension of `f` to multisets.
Lift(Part),
}

// A shared function is the same function, so that one can be used in several
Expand All @@ -39,12 +80,21 @@ impl<T: Function + ?Sized> Function for Rc<T> {
fn codomain(&self) -> Self::Codomain {
(**self).codomain()
}

fn parts(&self) -> Option<Parts>
where
Self: 'static,
{
(**self).parts()
}
}

/// `f ∘ g`: applies `g`, then `f` to the result.
/// `f ∘ g`: applies `g`, then `f` to the result. Both are shared, so that a
/// composition can be taken apart into its parts, and a rewrite of it can reuse
/// them as they are.
pub struct Composition<F, G> {
f: F,
g: G,
f: Rc<F>,
g: Rc<G>,
}

/// Composes `f` after `g`. Composing a tensor after an index map re-indexes it,
Expand All @@ -60,7 +110,10 @@ 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>
Expand All @@ -82,18 +135,28 @@ where
fn codomain(&self) -> Self::Codomain {
self.f.codomain()
}

fn parts(&self) -> Option<Parts>
where
Self: 'static,
{
Some(Parts::Composition {
outer: Part::new(Rc::clone(&self.f)),
inner: Part::new(Rc::clone(&self.g)),
})
}
}

/// 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,
f: Rc<F>,
}

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

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

fn parts(&self) -> Option<Parts>
where
Self: 'static,
{
Some(Parts::Lift(Part::new(Rc::clone(&self.f))))
}
}

/// A function on values, given as a closure, from `A` to `B`. Composed after a
Expand Down
Loading
Loading