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
//! Generate einsum function with naive loop

#[cfg(doc)]
use super::function_definition;

use crate::Subscripts;

use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use std::collections::HashSet;

fn index_ident(i: char) -> syn::Ident {
    quote::format_ident!("{}", i)
}

fn n_ident(i: char) -> syn::Ident {
    quote::format_ident!("n_{}", i)
}

fn contraction_for(indices: &[char], inner: TokenStream2) -> TokenStream2 {
    let mut tt = inner;
    for &i in indices.iter().rev() {
        let index = index_ident(i);
        let n = n_ident(i);
        tt = quote! {
            for #index in 0..#n { #tt }
        };
    }
    tt
}

fn contraction_inner(subscripts: &Subscripts) -> TokenStream2 {
    let mut inner_args_tt = Vec::new();
    for (argc, arg) in subscripts.inputs.iter().enumerate() {
        let mut index = Vec::new();
        for i in subscripts.inputs[argc].indices() {
            index.push(index_ident(i));
        }
        inner_args_tt.push(quote! {
            #arg[(#(#index),*)]
        })
    }
    let mut inner_mul = None;
    for inner in inner_args_tt {
        match inner_mul {
            Some(i) => inner_mul = Some(quote! { #i * #inner }),
            None => inner_mul = Some(inner),
        }
    }

    let output_ident = &subscripts.output;
    let mut output_indices = Vec::new();
    for i in &subscripts.output.indices() {
        let index = index_ident(*i);
        output_indices.push(index.clone());
    }
    quote! {
        #output_ident[(#(#output_indices),*)] = #inner_mul;
    }
}

/// Generate naive contraction loop
///
/// ```
/// # use ndarray::Array2;
/// # let arg0 = Array2::<f64>::zeros((3, 3));
/// # let arg1 = Array2::<f64>::zeros((3, 3));
/// # let mut out0 = Array2::<f64>::zeros((3, 3));
/// # let n_i = 3;
/// # let n_j = 3;
/// # let n_k = 3;
/// for i in 0..n_i {
///     for k in 0..n_k {
///         for j in 0..n_j {
///             out0[(i, k)] = arg0[(i, j)] * arg1[(j, k)];
///         }
///     }
/// }
/// ```
///
pub fn contraction(subscripts: &Subscripts) -> TokenStream2 {
    let mut indices: Vec<char> = subscripts.output.indices();
    for i in subscripts.contraction_indices() {
        indices.push(i);
    }

    let inner = contraction_inner(subscripts);
    contraction_for(&indices, inner)
}

/// Define the index size identifiers, e.g. `n_i`
pub fn define_array_size(subscripts: &Subscripts) -> TokenStream2 {
    let mut appeared: HashSet<char> = HashSet::new();
    let mut tt = Vec::new();
    for arg in subscripts.inputs.iter() {
        let n_ident: Vec<syn::Ident> = arg
            .indices()
            .into_iter()
            .map(|i| {
                if appeared.contains(&i) {
                    quote::format_ident!("_")
                } else {
                    appeared.insert(i);
                    n_ident(i)
                }
            })
            .collect();
        tt.push(quote! {
            let (#(#n_ident),*) = #arg.dim();
        });
    }
    quote! { #(#tt)* }
}

/// Generate `assert_eq!` to check the size of user input tensors
pub fn array_size_asserts(subscripts: &Subscripts) -> TokenStream2 {
    let mut tt = Vec::new();
    for arg in &subscripts.inputs {
        // local variable, e.g. `n_2`
        let n_each: Vec<_> = (0..arg.indices().len())
            .map(|m| quote::format_ident!("n_{}", m))
            .collect();
        // size of index defined previously, e.g. `n_i`
        let n: Vec<_> = arg.indices().into_iter().map(n_ident).collect();
        tt.push(quote! {
            let (#(#n_each),*) = #arg.dim();
            #(assert_eq!(#n_each, #n);)*
        });
    }
    quote! { #({ #tt })* }
}

fn define_output_array(subscripts: &Subscripts) -> TokenStream2 {
    // Define output array
    let output_ident = &subscripts.output;
    let mut n_output = Vec::new();
    for i in subscripts.output.indices() {
        n_output.push(n_ident(i));
    }
    quote! {
        let mut #output_ident = ndarray::Array::zeros((#(#n_output),*));
    }
}

/// Actual component of einsum [function_definition]
pub fn inner(subscripts: &Subscripts) -> TokenStream2 {
    let array_size = define_array_size(subscripts);
    let array_size_asserts = array_size_asserts(subscripts);
    let output_ident = &subscripts.output;
    let output_tt = define_output_array(subscripts);
    let contraction_tt = contraction(subscripts);
    quote! {
        #array_size
        #array_size_asserts
        #output_tt
        #contraction_tt
        #output_ident
    }
}

#[cfg(test)]
mod test {
    use crate::{codegen::format_block, *};

    #[test]
    fn define_array_size() {
        let mut namespace = Namespace::init();
        let subscripts = Subscripts::from_raw_indices(&mut namespace, "ij,jk->ik").unwrap();
        let tt = format_block(super::define_array_size(&subscripts).to_string());
        insta::assert_snapshot!(tt, @r###"
        let (n_a, n_b) = arg0.dim();
        let (_, n_c) = arg1.dim();
        "###);
    }

    #[test]
    fn contraction() {
        let mut namespace = Namespace::init();
        let subscripts = Subscripts::from_raw_indices(&mut namespace, "ij,jk->ik").unwrap();
        let tt = format_block(super::contraction(&subscripts).to_string());
        insta::assert_snapshot!(tt, @r###"
        for a in 0..n_a {
            for c in 0..n_c {
                for b in 0..n_b {
                    out0[(a, c)] = arg0[(a, b)] * arg1[(b, c)];
                }
            }
        }
        "###);
    }

    #[test]
    fn inner() {
        let mut namespace = Namespace::init();
        let subscripts = Subscripts::from_raw_indices(&mut namespace, "ij,jk->ik").unwrap();
        let tt = format_block(super::inner(&subscripts).to_string());
        insta::assert_snapshot!(tt, @r###"
        let (n_a, n_b) = arg0.dim();
        let (_, n_c) = arg1.dim();
        {
            let (n_0, n_1) = arg0.dim();
            assert_eq!(n_0, n_a);
            assert_eq!(n_1, n_b);
        }
        {
            let (n_0, n_1) = arg1.dim();
            assert_eq!(n_0, n_b);
            assert_eq!(n_1, n_c);
        }
        let mut out0 = ndarray::Array::zeros((n_a, n_c));
        for a in 0..n_a {
            for c in 0..n_c {
                for b in 0..n_b {
                    out0[(a, c)] = arg0[(a, b)] * arg1[(b, c)];
                }
            }
        }
        out0
        "###);
    }
}