Python-numpy...how to reduce run time?

135 views Asked by At

Im new to python and programming with it but Ive written this code in order to extract the S-wave from a wavelet using Hilbert transformation for determining end of S wave...it works but it takes a lot of time to process. is there a way to reduce this time?

#!/usr/bin/env python

import numpy as np
import math as mt
import os
from matplotlib import  *
from obspy import *
from pylab import *
import scipy.signal as sig


cwd = os.getcwd()

def Swin(Fname):
    L = np.array()
    F = open(Fname)
    L = np.loadtxt(F)
    xx = zeros(len(L), dtype=float32)

    for n in range(0, len(L)):
        xx[n] = 0.005*n

#Start of S wave

    G = np.arange(len(L), dtype=float64)
    W = np.arange(0, len(G))
    C = np.arange(0, len(G))

    Et=0.0
    for i in range (1, len(L)):
        Et = Et+(L[i]**2)

    SOS = 0
    E = 0.0
    for n in range (0, len(L)):
        E = 0.0
        p = n
        for j in range (0, p+1):
            E = E+(L[j]**2)
        if E/Et >= 0.05 :
            SOS = n
            en = E/Et
            break
            break

    SOS = SOS*0.005


#End of S wave by Hilbert transformation

    P = np.arange(0, len(L), dtype=float64)
    W = sig.hilbert(L)
    C = sqrt((L**2)+(W**2))

    for i in range (1, len(C)):
        count = 0.0
        for j in range (1, i):
            count = count+(C[j]**2)
        P[i] = sqrt((1.0/i)*count)

    EOS = argmax(P)*0.005

    SEF = open('/home/babak/Documents/Thesis/SEswin/SEswin.txt', 'a')
    sss = (Fname, SOS, EOS)
    SEF.write('\n'+str(sss)+'\n')
    SEF.close

    EOSn = int(EOS*200)
    SOSn = int(SOS*200)
    han = sig.hann(int((EOSn-SOSn)*0.05))
    ll = argmax(han)

#1st half of hanning function

    cosine1 = zeros(ll)

    for n in range (0, ll):
        cosine1[n] = han[n]

#2nd half of hanning unction
    cosine2 = zeros(len(han)-ll)

    for n in range (0, (len(han)-ll)):
        cosine2[n] = han[ll+n]


#windowing the s-wave of wavelet

    for n in range (0, len(cosine1)):
        L[SOSn-len(cosine1)+n] = L[SOSn-len(cosine1)+n]*cosine1[n]

    for n in range (EOSn, len(cosine2)):
        L[EOSn+n] = L[EOSn+n]*cosine2[n]


    for n in range (0, SOSn-len(cosine1)):
        L[n] = 0

    for n in range (EOSn+len(cosine2), len(L)):
        L[n] = 0

    np.savetxt('/home/babak/Documents/Thesis/S-extraction/'+Fname[:(len(Fname)-4)]+'-s.cor', L)

    return L


Folders = os.listdir('/home/babak/Documents/Thesis/test/')
for n in Folders:
    Swin(n)
0

There are 0 answers