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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
//! Einsum subscripts, e.g. `ij,jk->ik`
use crate::{parser::*, *};
use anyhow::Result;
use proc_macro2::TokenStream;
use quote::{format_ident, quote, ToTokens, TokenStreamExt};
use std::{
    collections::{BTreeMap, BTreeSet},
    fmt,
    str::FromStr,
};

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Subscript {
    raw: RawSubscript,
    position: Position,
}

impl Subscript {
    pub fn raw(&self) -> &RawSubscript {
        &self.raw
    }

    pub fn position(&self) -> &Position {
        &self.position
    }

    pub fn indices(&self) -> Vec<char> {
        match &self.raw {
            RawSubscript::Indices(indices) => indices.clone(),
            RawSubscript::Ellipsis { start, end } => {
                start.iter().chain(end.iter()).cloned().collect()
            }
        }
    }
}

impl ToTokens for Subscript {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        ToTokens::to_tokens(&self.position, tokens)
    }
}

#[cfg_attr(doc, katexit::katexit)]
/// Einsum subscripts with tensor names, e.g. `ab,bc->ac | arg0,arg1->out0`
///
/// Indices are remapped as starting from `a` to distinguish same subscripts, e.g. `i,i->` and `j,j->`
///
/// ```
/// use einsum_codegen::{*, parser::RawSubscript};
///
/// let mut names = Namespace::init();
/// let mut ss1 = Subscripts::from_raw_indices(&mut names, "ij,jk,kl->il").unwrap();
///
/// let mut names = Namespace::init();
/// let mut ss2 = Subscripts::from_raw_indices(&mut names, "xz,zy,yw->xw").unwrap();
///
/// assert_eq!(ss1, ss2);
/// assert_eq!(ss1.to_string(), "ab,bc,cd->ad | arg0,arg1,arg2->out0");
/// assert_eq!(ss2.to_string(), "ab,bc,cd->ad | arg0,arg1,arg2->out0");
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct Subscripts {
    /// Input subscript, `ij` and `jk`
    pub inputs: Vec<Subscript>,
    /// Output subscript.
    pub output: Subscript,
}

// `ij,jk->ik | arg0,arg1->out0` format
impl fmt::Debug for Subscripts {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (n, input) in self.inputs.iter().enumerate() {
            write!(f, "{}", input.raw)?;
            if n < self.inputs.len() - 1 {
                write!(f, ",")?;
            }
        }
        write!(f, "->{} | ", self.output.raw)?;

        for (n, input) in self.inputs.iter().enumerate() {
            write!(f, "{}", input.position)?;
            if n < self.inputs.len() - 1 {
                write!(f, ",")?;
            }
        }
        write!(f, "->{}", self.output.position)?;
        Ok(())
    }
}

impl fmt::Display for Subscripts {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl ToTokens for Subscripts {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let fn_name = format_ident!("{}", self.escaped_ident());
        let args = &self.inputs;
        let out = &self.output;
        tokens.append_all(quote! {
            let #out = #fn_name(#(#args),*);
        });
    }
}

impl Subscripts {
    /// Returns $\alpha$ if this subscripts requires $O(N^\alpha)$ floating point operation
    pub fn compute_order(&self) -> usize {
        self.memory_order() + self.contraction_indices().len()
    }

    /// Returns $\beta$ if this subscripts requires $O(N^\beta)$ memory
    pub fn memory_order(&self) -> usize {
        self.output.indices().len()
    }

    /// Normalize subscripts into "explicit mode"
    ///
    /// [numpy.einsum](https://numpy.org/doc/stable/reference/generated/numpy.einsum.html)
    /// has "explicit mode" including `->`, e.g. `ij,jk->ik` and
    /// "implicit mode" e.g. `ij,jk`.
    /// The output subscript is determined from input subscripts in implicit mode:
    ///
    /// > In implicit mode, the chosen subscripts are important since the axes
    /// > of the output are reordered alphabetically.
    /// > This means that `np.einsum('ij', a)` doesn’t affect a 2D array,
    /// > while `np.einsum('ji', a)` takes its transpose.
    /// > Additionally, `np.einsum('ij,jk', a, b)` returns a matrix multiplication,
    /// > while, `np.einsum('ij,jh', a, b)` returns the transpose of
    /// > the multiplication since subscript ‘h’ precedes subscript ‘i’.
    ///
    /// ```
    /// use std::str::FromStr;
    /// use einsum_codegen::{*, parser::*};
    ///
    /// // Infer output subscripts for implicit mode
    /// let mut names = Namespace::init();
    /// let raw = RawSubscripts::from_str("ab,bc").unwrap();
    /// let subscripts = Subscripts::from_raw(&mut names, raw);
    /// assert_eq!(subscripts.to_string(), "ab,bc->ac | arg0,arg1->out0");
    ///
    /// // Reordered alphabetically
    /// let mut names = Namespace::init(); // reset namespace
    /// let raw = RawSubscripts::from_str("ba").unwrap();
    /// let subscripts = Subscripts::from_raw(&mut names, raw);
    /// assert_eq!(subscripts.to_string(), "ab->ba | arg0->out0");
    /// ```
    ///
    pub fn from_raw(names: &mut Namespace, raw: RawSubscripts) -> Self {
        let inputs = raw
            .inputs
            .iter()
            .enumerate()
            .map(|(i, indices)| Subscript {
                raw: indices.clone(),
                position: Position::Arg(i),
            })
            .collect();
        let position = names.new_ident();
        if let Some(output) = raw.output {
            let mut cand = Subscripts {
                inputs,
                output: Subscript {
                    raw: output,
                    position,
                },
            };
            cand.remap_indices();
            return cand;
        }

        let count = count_indices(&inputs);
        let output = Subscript {
            raw: RawSubscript::Indices(
                count
                    .iter()
                    .filter_map(|(key, value)| if *value == 1 { Some(*key) } else { None })
                    .collect(),
            ),
            position,
        };
        let mut cand = Subscripts { inputs, output };
        cand.remap_indices();
        cand
    }

    pub fn from_raw_indices(names: &mut Namespace, indices: &str) -> Result<Self> {
        let raw = RawSubscripts::from_str(indices)?;
        Ok(Self::from_raw(names, raw))
    }

    /// Indices to be contracted
    ///
    /// ```
    /// use std::str::FromStr;
    /// use maplit::btreeset;
    /// use einsum_codegen::*;
    ///
    /// let mut names = Namespace::init();
    ///
    /// // Matrix multiplication AB
    /// let subscripts = Subscripts::from_raw_indices(&mut names, "ab,bc->ac").unwrap();
    /// assert_eq!(subscripts.contraction_indices(), btreeset!{'b'});
    ///
    /// // Reduce all Tr(AB)
    /// let subscripts = Subscripts::from_raw_indices(&mut names, "ab,ba->").unwrap();
    /// assert_eq!(subscripts.contraction_indices(), btreeset!{'a', 'b'});
    ///
    /// // Take diagonal elements
    /// let subscripts = Subscripts::from_raw_indices(&mut names, "aa->a").unwrap();
    /// assert_eq!(subscripts.contraction_indices(), btreeset!{});
    /// ```
    pub fn contraction_indices(&self) -> BTreeSet<char> {
        let count = count_indices(&self.inputs);
        let mut subscripts: BTreeSet<char> = count
            .into_iter()
            .filter_map(|(key, value)| if value > 1 { Some(key) } else { None })
            .collect();
        for c in &self.output.indices() {
            subscripts.remove(c);
        }
        subscripts
    }

    /// Factorize subscripts
    ///
    /// ```text
    /// ab,bc,cd->ad | arg0,arg1,arg2->out0
    /// ```
    ///
    /// will be factorized with `(arg0, arg1)` into
    ///
    /// ```text
    /// ab,bc->ac | arg0,arg1 -> out1
    /// ab,bc->ac | out1 arg2 -> out0
    /// ```
    ///
    /// Be sure that the indices of `out1` in the first step `ac` is renamed
    /// into `ab` in the second step.
    ///
    /// ```
    /// use einsum_codegen::{*, parser::RawSubscript};
    /// use std::str::FromStr;
    /// use maplit::btreeset;
    ///
    /// let mut names = Namespace::init();
    /// let base = Subscripts::from_raw_indices(&mut names, "ab,bc,cd->ad").unwrap();
    ///
    /// let (step1, step2) = base.factorize(&mut names,
    ///   btreeset!{ Position::Arg(0), Position::Arg(1) }
    /// ).unwrap();
    ///
    /// assert_eq!(step1.to_string(), "ab,bc->ac | arg0,arg1->out1");
    /// assert_eq!(step2.to_string(), "ab,bc->ac | out1,arg2->out0");
    /// ```
    pub fn factorize(
        &self,
        names: &mut Namespace,
        inners: BTreeSet<Position>,
    ) -> Result<(Self, Self)> {
        let mut inner_inputs = Vec::new();
        let mut outer_inputs = Vec::new();
        let mut indices: BTreeMap<char, (usize /* inner */, usize /* outer */)> = BTreeMap::new();
        for input in &self.inputs {
            if inners.contains(&input.position) {
                inner_inputs.push(input.clone());
                for c in input.indices() {
                    indices
                        .entry(c)
                        .and_modify(|(i, _)| *i += 1)
                        .or_insert((1, 0));
                }
            } else {
                outer_inputs.push(input.clone());
                for c in input.indices() {
                    indices
                        .entry(c)
                        .and_modify(|(_, o)| *o += 1)
                        .or_insert((0, 1));
                }
            }
        }
        let out = Subscript {
            raw: RawSubscript::Indices(
                indices
                    .into_iter()
                    .filter_map(|(key, (i, o))| {
                        if i == 1 || (i >= 2 && o > 0) {
                            Some(key)
                        } else {
                            None
                        }
                    })
                    .collect(),
            ),
            position: names.new_ident(),
        };
        outer_inputs.insert(0, out.clone());

        let mut inner = Subscripts {
            inputs: inner_inputs,
            output: out,
        };
        let mut outer = Subscripts {
            inputs: outer_inputs,
            output: self.output.clone(),
        };
        inner.remap_indices();
        outer.remap_indices();
        Ok((inner, outer))
    }

    /// Escaped subscript for identifier
    ///
    /// This is not injective, e.g. `i...,j->ij` and `i,...j->ij`
    /// returns a same result `i____j__ij`.
    ///
    pub fn escaped_ident(&self) -> String {
        use std::fmt::Write;
        let mut out = String::new();
        for input in &self.inputs {
            write!(out, "{}", input.raw).unwrap();
            write!(out, "_").unwrap();
        }
        write!(out, "_{}", self.output.raw).unwrap();
        out
    }

    fn remap_indices(&mut self) {
        let mut map: BTreeMap<char, u32> = BTreeMap::new();
        let mut update = |raw: &mut RawSubscript| match raw {
            RawSubscript::Indices(indices) => {
                for i in indices {
                    if !map.contains_key(i) {
                        map.insert(*i, 'a' as u32 + map.len() as u32);
                    }
                    *i = char::from_u32(map[i]).unwrap();
                }
            }
            RawSubscript::Ellipsis { start, end } => {
                for i in start.iter_mut().chain(end.iter_mut()) {
                    if !map.contains_key(i) {
                        map.insert(*i, 'a' as u32 + map.len() as u32);
                    }
                    *i = char::from_u32(map[i]).unwrap();
                }
            }
        };
        for input in &mut self.inputs {
            update(&mut input.raw);
        }
        update(&mut self.output.raw)
    }
}

fn count_indices(inputs: &[Subscript]) -> BTreeMap<char, u32> {
    let mut count = BTreeMap::new();
    for input in inputs {
        for c in input.indices() {
            count.entry(c).and_modify(|n| *n += 1).or_insert(1);
        }
    }
    count
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn escaped_ident() {
        let mut names = Namespace::init();

        let subscripts = Subscripts::from_raw_indices(&mut names, "ab,bc->ac").unwrap();
        assert_eq!(subscripts.escaped_ident(), "ab_bc__ac");

        // implicit mode
        let subscripts = Subscripts::from_raw_indices(&mut names, "ab,bc").unwrap();
        assert_eq!(subscripts.escaped_ident(), "ab_bc__ac");

        // output scalar
        let subscripts = Subscripts::from_raw_indices(&mut names, "a,a").unwrap();
        assert_eq!(subscripts.escaped_ident(), "a_a__");

        // ellipsis
        let subscripts = Subscripts::from_raw_indices(&mut names, "ab...,bc...->ac...").unwrap();
        assert_eq!(subscripts.escaped_ident(), "ab____bc_____ac___");
    }
}