Sunday 8 September 2019

Decreasing the time necessary to enter the coefficients of a matrix

Using Python, I want to build a square matrix whose coefficients are functions evaluated at some given points. The matrix is lower triangular, yet it takes more than 200 seconds to enter all the coefficients when the size is 1000. This is quite surprising to me as I have already dealt with square matrices of size greater than 1 million.

I guess that the loss of time comes from the function that defines all the non-zero coefficients of the matrix: it is a product of four terms, each of them involving a complex power (see the minimal example below). I would be really happy if someone could help me: the purpose is to reach a size of 1 million within a few seconds (hope this is doable...). Maybe the use of ** is not optimal for the complex power; or maybe there is a quicker way to fill a lower triangular matrix? Any help will be appreciated!

For the code below, Ns is the size of the square matrix.

import math
from math import *
import numpy as np
from numpy import exp, log, sqrt, cos, sin, arange
import time


tmps1 = time.time()


Ns = 100
h = 1/float(Ns)
Ns = int(Ns)

mu = 0.01

rn = -6.34
rc = 0.86
r1 = 1.32
r2 = 4.16

P = np.zeros((Ns + 1, 1))
for j in range(0, Ns + 1):
    P[j] = r1 + j*(r2-r1)*h

kappan = 0.24
kappac = -0.24
kappa1 = 0.095
kappa2 = -0.095


z = complex(0.01,0.01)


def E(exponent,p):
    return (  ( ((p-rn)/(2-rn))**((exponent)/(2*kappan)) )*( ((p-rc)/(2-rc))**((exponent)/(2*kappac)) )*( ((p-r1)/(2-r1))**((exponent)/(2*kappa1)) )*( ((r2-p)/(r2-2))**((exponent)/(2*kappa2)) )  )

def D(p,r):
    return (      ( 1/(2*complex(0.0,1.0)*(z-mu/r1)) )*(   ( 1/(2*(kappa1-complex(0.0,1.0)*(z-mu/r1))) )*( E(2*(kappa1-complex(0.0,1.0)*(z-mu/r1)),r)*E(2*complex(0.0,1.0)*(z-mu/r1),p) )   -   ( 1/(2*kappa1) )*E(2*kappa1,r)   )      )


A = np.zeros((Ns-1, Ns-1), dtype=np.complex_)

for j in range(1, Ns-1):
    for k in range(1, j+1):
        A[j,k] = D(P[j+1], P[k+1]) - D(P[j+1], P[k])


tmps2 = time.time()-tmps1
print "\n\nExecution time = %f\n\n" %tmps2



from Decreasing the time necessary to enter the coefficients of a matrix

No comments:

Post a Comment