The assignments q[i] =, q_temp[:, j], p[i] = are likely the source of your problem. If you manage to write them as one operation filling everything, it will probably go away.
The snippet you post has too many “free” variables to try to execute it, but it vaguely looks like it should be easy to eliminate the for loops.
Best regards
Thomas