Python Forum
Vectorizing a quadruple for loop in python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Vectorizing a quadruple for loop in python
#11
(Aug-28-2023, 09:30 AM)winash12 Wrote: I was not able to visualize what would be my boolean condition since both inner_point and outer_point are tuples

np.asarray might help you
import numpy as np

MyTuple = (1, 2, 3, 0, 0, 100)
print(f"MyTyple type = {type(MyTuple)}")

MyTupleConvertedIntoArray = np.asarray(MyTuple)
print(f"MyTupleConvertedIntoArray type = {type(MyTupleConvertedIntoArray)}")
print(f"MyTupleConvertedIntoArray = {MyTupleConvertedIntoArray}")
Output:
MyTyple type = <class 'tuple'> MyTupleConvertedIntoArray type = <class 'numpy.ndarray'> MyTupleConvertedIntoArray = [ 1 2 3 0 0 100]
Reply
#12
Great tips.

Presuming we can continue the discussion two issues come up in trying unroll the for loops

1) How to vectorize the creation of outer and inner points ?
 args = []
for i in range (0,100):
    for j in range(0,200):
        outer_point = [i,j]
        op = np.asarray(outer_point)
        args.append(op)
opC = np.concatenate(args,axis=0)
2) The shape of collection of outer points and inner points is different .

set1d

Use setdiff1d to calculate the diff of outer and inner points and store the difference as a boolean array.
Reply
#13
import numpy as np
import time

n = 1_000
m = 2_000

t0 = time.time()
args = []
for i in range (0,n):
    for j in range(0,m):
        outer_point = [i,j]
        op = np.asarray(outer_point)
        args.append(op)
opC = np.concatenate(args,axis=0)
t1 = time.time()
print(f"current snipper = {t1 - t0}")



t2 = time.time()
i = np.ones(m)
j = np.arange(n)
ind1 = np.kron(j, i).reshape(-1, 1)

k = np.ones(n)
l = np.arange(m)
ind2 = np.kron(k, l).reshape(-1, 1)

op = np.hstack((ind1, ind2))
op = op.flatten(order='C')
t3 = time.time()
print(f"new snipper = {t3 - t2}")
print(f"with n = {n} and m = {m}, vectorization ratio is X {(t1 - t0) / (t3 - t2):.1f}")

Check = np.array_equal(opC, op)
if Check: print("Both arrays are identical!!!")
Output:
current snipper = 2.0446 new snipper = 0.0309 with n = 1000 and m = 2000, vectorization ratio is X 66.2 Both arrays are identical!!!
winash12 likes this post
Reply
#14
As I see it, all points (i, j) up to i = 9, j = 19 will be in (k, l), because you start each loop at zero.

If your condition is: inner_point != outer_point, I think you just need this:

for k in range(10,30):
     for l in range(20,40):         
         inner_point = [k,l]         
         print('the x difference is', 9-k)
         print('the y difference is', 19-l)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Vectorizing using numpy pythonhelp 0 1,635 Aug-26-2019, 09:03 AM
Last Post: pythonhelp

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020