Python-numpy ......如何减少运行时间?

时间:2014-11-23 13:27:31

标签: python linux numpy scipy wavelet

我是python新手并使用它进行编程但是我编写了这段代码,以便使用希尔伯特变换从小波中提取S波来确定S波的结束......它可以工作但是需要花费大量的时间来处理。有没有办法减少这个时间?

#!/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 个答案:

没有答案