Mehdi - 1 year ago 303

Python Question

I was wondering if there is an implementation for the Energy for 1-D wavelet in Python, the same as the Matlab '[Ea,Ed] = wenergy(C,L) '.

I have tried to write one on my own but i am not sure of it:

The formula is:

Where Dj is supposed the detail vector, and j = 1,2,...,ld and N1 is the data length at the decomposition level.

`import json`

import pywt

f=open('DataFile.txt','r')

D=json.load(f)

f.close()

#create the wavelet function

db1 = pywt.Wavelet('db13')

#calculate the number of necessary decompositions

NbrDecomp= pywt.dwt_max_level(len(D), db1)+1

#Initialize an empty list to receive the Detail and Approximation

Vector = [None] * NbrDecomp

#we use the Wavelet decomposition in the pywt module

Vector = pywt.wavedec(D, db1)

#Now Vector = [Approxiamtion N, Details N, Details N-1,.....]

#Where N would be the number of decompositions

According to the definition the energy at the level k is :

`Energy(k)=np.sqrt(sum([x**2 for x in Vecktor[len(Vektor)-N-1-k]])/len(Vektor))`

Was the implementation correct ?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You can simplify your code a little bit:

```
coeffs[len(coeffs) - k - 1]
```

can be rewritten as

```
coeffs[-k]
```

and you can do the squaring and summation as one NumPy operation (since you're using NumPy already)

```
def Energy(coeffs, k):
return np.sqrt(np.sum(np.array(coeffs[-k]) ** 2)) / len(coeffs[-k])
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**