Home > front end >  Smart way to create n dimensional lattice of tuples from n 1-d numpy arrays and operate on each latt
Smart way to create n dimensional lattice of tuples from n 1-d numpy arrays and operate on each latt

Time:04-22

How to create an n dimensional lattice from n 1-d numpy arrays of dissimilar sizes. Meaning, imagine each lattice point contains a tuple of n numbers: small example: lets have n=3, and a = np.array([1,2,3]), b = np.array([4,5]), c = np.array([8,10]), so I would want a 3x2x2 structure with the points have elements (1,4,8), (1,4,10), ... , (3,5,10) in regular order. What will be a smart way to achieve this for large sized a, b, c (also maybe n) and do operations on each tuple (like compare if any two entries of a tuple are close for each tuple).

CodePudding user response:

import numpy as np
nt = 100
lattice = np.empty(nt, dtype='object')
lattice[0] = np.array([1,2,3])
lattice[1] = np.array([4,5])
lattice[2] = np.array([8,10])

CodePudding user response:

    In [254]: a = np.array([1,2,3]); b = np.array([4,5]); c = np.array([8,10])

meshgrid can generate the values - as a tuple of arrays:

    In [255]: xyz = np.meshgrid(a,b,c, indexing='ij')
    In [256]: xyz
    Out[256]: 
    [array([[[1, 1],
             [1, 1]],
     
            [[2, 2],
             [2, 2]],
     
            [[3, 3],
             [3, 3]]]),
     array([[[4, 4],
             [5, 5]],
     
            [[4, 4],
             [5, 5]],
     
            [[4, 4],
             [5, 5]]]),
     array([[[ 8, 10],
             [ 8, 10]],
     
            [[ 8, 10],
             [ 8, 10]],
     
            [[ 8, 10],
             [ 8, 10]]])]

Joining them into one array:

    In [257]: np.stack(xyz, axis=3)
    Out[257]: 
    array([[[[ 1,  4,  8],
             [ 1,  4, 10]],
    
            [[ 1,  5,  8],
             [ 1,  5, 10]]],
    
    
           [[[ 2,  4,  8],
             [ 2,  4, 10]],
    
            [[ 2,  5,  8],
             [ 2,  5, 10]]],
    
    
           [[[ 3,  4,  8],
             [ 3,  4, 10]],
    
            [[ 3,  5,  8],
             [ 3,  5, 10]]]])

Flattening the first dimensions:

In [258]: np.reshape(_,(-1,3))
Out[258]: 
array([[ 1,  4,  8],
       [ 1,  4, 10],
       [ 1,  5,  8],
       [ 1,  5, 10],
       [ 2,  4,  8],
       [ 2,  4, 10],
       [ 2,  5,  8],
       [ 2,  5, 10],
       [ 3,  4,  8],
       [ 3,  4, 10],
       [ 3,  5,  8],
       [ 3,  5, 10]])

with a common Python tool:

In [260]: from itertools import product
In [261]: ijk = list(product(a,b,c))
In [262]: ijk
Out[262]: 
[(1, 4, 8),
 (1, 4, 10),
 (1, 5, 8),
 (1, 5, 10),
 (2, 4, 8),
 (2, 4, 10),
 (2, 5, 8),
 (2, 5, 10),
 (3, 4, 8),
 (3, 4, 10),
 (3, 5, 8),
 (3, 5, 10)]
  • Related