Ask Your Question
1

Generation of all 3-index tensors with {-1,0,1} as entries.

asked 2014-10-07 13:57:17 +0100

Ira gravatar image

updated 2014-10-07 13:58:58 +0100

I need to generate all tensors $A_{ijk}$ (i.e. array with 3 indices), where $i=0, \ldots, 6$, $j=0, \ldots 6$, $k=0, \ldots 5$, such that only integer numbers $-1$, $0$ and $1$ could be used as entries. There are $665*3$ such possibilities. What would be the shortest system of embedded loop for this in SAGE? I just started using SAGE and don't have any previous experience with Python. The only solution I was able to think of include hundreds of embedded loops.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2014-10-13 11:04:58 +0100

vdelecroix gravatar image

Hi,

I might have misunderstood, but the number of such arrays is $3^{776}$ which is of the size of $10^{140}$. There is no chance you can iterate through such a big set with a computer.

With more reasonable size this is doable as follows. There is a very nice standard Python library called itertools that allows to do that without nested loop. Let me first define a function to create a tensor from a list of values

sage: def one_line_array_to_tensor(l,m1,m2,m3):
....:    return [[[l[i + m3*(j + m2 * k) for i in range(m3)] for j in range(m2)] for k in range(m1)]

That can be used as

sage: sage: one_line_array_to_tensor(range(16),3,2,2)
[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
sage: one_line_array_to_tensor(range(16),2,3,2)
[[[0, 1], [2, 3], [4, 5]], [[6, 7], [8, 9], [10, 11]]]
sage: one_line_array_to_tensor(range(16),2,2,3)
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]

Then, you just need to iterate through the possible values:

sage: from itertools import product
sage: iterator = (one_line_array_to_tensor(p,2,2,2) for p in product((0,1,-1),repeat=2*2*2))
sage: for p in iterator:
....:    print p
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
[[[0, 0], [0, 0]], [[0, 0], [0, 1]]]
[[[0, 0], [0, 0]], [[0, 0], [0, -1]]]
...
[[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]]

Vincent

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2014-10-07 13:57:17 +0100

Seen: 302 times

Last updated: Oct 13 '14