einsum¶
One notation for the products of linear algebra.
Functions¶
einsum¶
The contraction that Text spells, as NumPy's einsum in its explicit form.
einsum<"ij,jk->ik">(a, b) is the matrix product, einsum<"ii->">(a) the trace, einsum<"i,j->ij">(u, v) the outer product. Each operand is read in the space of all the labels, the operands are multiplied element by element, and the labels the result lacks are summed, by a Reduce over that product: lazy, as any expression, einsum<"ij,jk->ik">(a, b)[i, k] computes one sum.
The notation:
- operands are separated by
,, then comes->and the result; the arrow is required; - a label is a letter
atoz, one per axis, so an operand of rank 2 is two letters; no spaces, no capitals, no...; - the result lists labels that appear in some operand, each at most once; it may be empty (
"ij,ij->"), and the result is then of rank 0, read asresult[]; - a label that is not in the result is summed over;
- a label that repeats within one operand takes its diagonal (
"ii->i"); one that is in several operands must have the same extent in each.
The result is an expression of one axis per label of the result, in the order written, whose extent is that of the first operand axis with the label, static where an operand's type fixes it. Its elements are the products of the operands' elements, summed over the labels the result lacks.
Anything that is wrong with the text, or with the operands for it, is a compile error whose message begins with einsum::
- no
->, or a character other than letters,,and the arrow; - a label repeated in the result, or in the result and in no operand;
- a number of operands other than the text has, or an operand whose rank is not the number of its labels;
- operands whose types fix different extents for one label.
Extents that only dynamic extents fix, and that differ, are caught at run time.
One loop over the whole space, without intermediates: a chain of three or more operands may cost more than contracting them pair by pair. An operand that is an expression is computed again for each value of the labels it lacks; a tensor of its values, made first, is read instead.
const Tensor c = einsum<"ij,jk->ik">(a, b); // matrix product
const auto trace = einsum<"ii->">(a)[];
Template parameters
| Name | Description |
|---|---|
Text | The notation, such as "ij,jk->ik". |
Parameters
| Name | Description |
|---|---|
args | The operands: tensors, views or expressions, as many as the text has. |