A reproduction of einsum c side einsum parsing in python. Returns ------- input_strings : str Parsed input strings output_string : str Parsed output string operands : list of array_like The operands to use in the numpy contraction Examples -
(operands)
| 521 | |
| 522 | |
| 523 | def _parse_einsum_input(operands): |
| 524 | """ |
| 525 | A reproduction of einsum c side einsum parsing in python. |
| 526 | |
| 527 | Returns |
| 528 | ------- |
| 529 | input_strings : str |
| 530 | Parsed input strings |
| 531 | output_string : str |
| 532 | Parsed output string |
| 533 | operands : list of array_like |
| 534 | The operands to use in the numpy contraction |
| 535 | |
| 536 | Examples |
| 537 | -------- |
| 538 | The operand list is simplified to reduce printing: |
| 539 | |
| 540 | >>> np.random.seed(123) |
| 541 | >>> a = np.random.rand(4, 4) |
| 542 | >>> b = np.random.rand(4, 4, 4) |
| 543 | >>> _parse_einsum_input(('...a,...a->...', a, b)) |
| 544 | ('za,xza', 'xz', [a, b]) # may vary |
| 545 | |
| 546 | >>> _parse_einsum_input((a, [Ellipsis, 0], b, [Ellipsis, 0])) |
| 547 | ('za,xza', 'xz', [a, b]) # may vary |
| 548 | """ |
| 549 | |
| 550 | if len(operands) == 0: |
| 551 | raise ValueError("No input operands") |
| 552 | |
| 553 | if isinstance(operands[0], str): |
| 554 | subscripts = operands[0].replace(" ", "") |
| 555 | operands = [asanyarray(v) for v in operands[1:]] |
| 556 | |
| 557 | # Ensure all characters are valid |
| 558 | for s in subscripts: |
| 559 | if s in '.,->': |
| 560 | continue |
| 561 | if s not in einsum_symbols: |
| 562 | raise ValueError("Character %s is not a valid symbol." % s) |
| 563 | |
| 564 | else: |
| 565 | tmp_operands = list(operands) |
| 566 | operand_list = [] |
| 567 | subscript_list = [] |
| 568 | for p in range(len(operands) // 2): |
| 569 | operand_list.append(tmp_operands.pop(0)) |
| 570 | subscript_list.append(tmp_operands.pop(0)) |
| 571 | |
| 572 | output_list = tmp_operands[-1] if len(tmp_operands) else None |
| 573 | operands = [asanyarray(v) for v in operand_list] |
| 574 | subscripts = "" |
| 575 | last = len(subscript_list) - 1 |
| 576 | for num, sub in enumerate(subscript_list): |
| 577 | for s in sub: |
| 578 | if s is Ellipsis: |
| 579 | subscripts += "..." |
| 580 | else: |
no test coverage detected