tensor icon indicating copy to clipboard operation
tensor copied to clipboard

Tensor Product (Kronecker product) of complex matrix

Open sah4ez opened this issue 5 years ago • 3 comments

Hi everyone! Thanks for great package for work with tensors! I tried use this package for work with complex matrix/vectors, but not found Tensor Product implementation. You'll plan add this functional?

sah4ez avatar Oct 02 '19 07:10 sah4ez

I wrote this methods as experiment:

func ProductVector(a, b *tensor.Dense) *tensor.Dense {
	if !a.Shape().IsVector() || !b.Shape().IsVector() {
		panic("should be vectors")
	}
	ar := a.Shape()
	br := b.Shape()
	l := ar[0] * br[0]
	k := tensor.New(tensor.WithShape(l), tensor.WithBacking(make([]complex128, ar[0]*br[0])))

	p := 0
	for i := 0; i < ar[0]; i++ {
		for j := 0; j < br[0]; j++ {
			ci, _ := a.At(i)
			cj, _ := b.At(j)
			k.Set(p, ci.(complex128)*cj.(complex128))
			p = p + 1
		}
	}
	return k
}

func ProductMatrix(m1, m2 *tensor.Dense) *tensor.Dense {
	if !m1.Shape().IsMatrix() || !m2.Shape().IsMatrix() {
		panic("should be matrix")
	}
	m := m1.Shape()
	p := m2.Shape()

	tmp := []*tensor.Dense{}
	for i := 0; i < m[0]; i++ {
		for j := 0; j < m[1]; j++ {
			cij, _ := m1.At(i, j)
			n, _ := tensor.Mul(m2, tensor.New(tensor.WithShape(1), tensor.WithBacking([]complex128{cij.(complex128)})))
			tmp = append(tmp, n.(*tensor.Dense))
		}
	}

	mv3 := []complex128{}
	for l := 0; l < len(tmp); l = l + m[0] {
		for j := 0; j < p[0]; j++ {
			for i := l; i < l+m[0]; i++ {
				for k := 0; k < p[1]; k++ {
					cjk, _ := tmp[i].At(j, k)
					mv3 = append(mv3, cjk.(complex128))
				}
			}
		}
	}
	m3 := tensor.New(tensor.WithShape(m[0]*p[0], m[1]*p[1]), tensor.WithBacking(mv3))

	return m3
}

I think, this code can add to genlib2 for all types. But I don't know how implement universal function for n-dimensions tensor.Dense

sah4ez avatar Oct 02 '19 09:10 sah4ez

Hey @sah4ez did you add this, do you need help?

chewxy avatar Dec 11 '19 23:12 chewxy

@chewxy As I understand, big part of code generated through genlib2. So, for all types, need implement this function. So I have questions:

  1. snippets with code is ok?
  2. if this will be only for 2-dementions matrix, ok?

sah4ez avatar Dec 13 '19 07:12 sah4ez