Python Forum
NameError mlab not defined
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
NameError mlab not defined
#1
I wrote a program to analyze ECG rhythms. It works on my computer, but I emailed it to a friend for them to run it and suddenly it's saying that mlab is not defined. The whole program hangs up and it won't proceed. Why does it work for me and not for him?

"""
Created on Fri Nov  3 11:57:12 2017

@author: CB
"""



import numpy as np
import peakutils
from peakutils.plot import plot as pplot
from matplotlib import pyplot
from matplotlib.mlab import detrend
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file = filedialog.askopenfilename()
print(file)


file = open(file).read().split('\n')
row1 = file[0].split(' ')
y = np.array(file[1:len(file)-1]).astype(np.float)
timeStep = float(row1[5])
x = [i for i in range(len(file)-2)]
x = np.array(x)

def savitzky_golay(y, window_size, order, deriv=0, rate=1):
    from math import factorial

    try:
        window_size = np.abs(np.int(window_size))
        order = np.abs(np.int(order))
    except ValueError:
        raise ValueError("window_size and order have to be of type int")
    if window_size % 2 != 1 or window_size < 1:
        raise TypeError("window_size size must be a positive odd number")
    if window_size < order + 2:
        raise TypeError("window_size is too small for the polynomials order")
    order_range = range(order+1)
    half_window = (window_size -1) // 2
    # precompute coefficients
    b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])
    m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)
    # pad the signal at the extremes with
    # values taken from the signal itself
    firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
    lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
    y = np.concatenate((firstvals, y, lastvals))
    return np.convolve( m[::-1], y, mode='valid')

y = savitzky_golay(y,49,5)
y = savitzky_golay(y,39,5)
y = savitzky_golay(y,59,5)

y = mlab.detrend(y)

rPeaks = peakutils.indexes(y, thres=0.9, min_dist=100)
peaks = peakutils.indexes(y, thres=0.3, min_dist=20)
nidx = peakutils.indexes(-y,thres = .85, min_dist = 25)
pyplot.figure(figsize=(10,6))
pplot(x,y, nidx)
pplot(x,y, rPeaks)
pyplot.title('ECG Data')



r_r = []        
for i in range (0,len(rPeaks)-1):
    r_r.append((rPeaks[i+1]-rPeaks[i])*timeStep)
r_r = np.array(r_r)
dev = np.std(r_r*1000)   

peakRat = len(peaks)/len(rPeaks)

heartRate = 60/np.mean(r_r)
print('Heart Rate:')
print(heartRate)

if dev > 200:
    print('Diagnosis: \nAV Block Second Degree')
elif heartRate >100:
    print('Diagnosis:\nSinus Tachycardia')
elif heartRate < 60 and dev < 5:
    print('Diagnosis: \nSinus Bradycardia')
elif dev > 5 and dev < 80:
    print('Diagnosis:')
    if peakRat > 5:
        print('Atrial Fibrillation')
    elif peakRat < 5:
        print('Sinus Arrythmia')
elif dev < 5:

    pri = []
    qrs = []
    for i in range(1,len(rPeaks)-1):
        bBnd = rPeaks[i]-500
        xrange = np.where((peaks>bBnd)*(peaks<rPeaks[i]))
        xrange = np.array(xrange[0])
        qrs.append(((nidx[2*i+1])-(nidx[2*i]))*timeStep*1.7)
        pri.append((rPeaks[i]-peaks[xrange])*timeStep*100)
    qrs = np.mean(np.array(qrs))    
    pri = np.mean(np.array(pri))
    
    if pri >20:
        print('Diagnosis:\nAV Block First Degree')
    elif qrs > .1:
        print('Diagnosis:\nBundle Branch Block')
    elif qrs < .1:
        print('Diagnosis:\nNormal')
Granted, you won't have the files to put through it's analysis, but he is getting this error:
Error:
y = mlab.detrend(y) NameError: name 'mlab' is not defined
"Nobody really knows how to program, the pros Google too." -A Google Engineer
Reply
#2
on line 13 you have from matplotlib.mlab import detrend, so line59 should be y = detrend(y)
otherwise you need to do from matplotlib import mlab
I doubt the code as is works for you too
Reply
#3
In addition, I see you open a file, but I don't see where you close it.

Why bury an import in a function rather than have it at the top with your other imports?
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#4
@sparkz_alot

I ended up using "from matplotlib import mlab" and the associates line for line 59. Does that address what you're talking about with the hidden import, or are you referring to line 32? I can try moving that to the top of my program and running it that way.

Also, I'm still working on adding functions to export the results of the evaluation as a .txt file. Eventually, this program will have a menu of options to open the file, show graphs, evaluate the rhythms, and export the results. The last option will be one to close the file. Thank you very much for your help, both of you.
"Nobody really knows how to program, the pros Google too." -A Google Engineer
Reply
#5
He refers to line 32.
Reply
#6
In python, imports are normally expected at the top of the file.  Not all languages have that convention.
Unless you don't plan on ever showing your code to someone else, it's normally best to try to stick to conventions, to make it as easy as possible for someone else to understand quickly.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  NameError: name 'predicted_labels' is not defined hobbyist 2 710 Dec-08-2023, 02:18 PM
Last Post: hobbyist
  NameError: name 'rand' is not defined Truman 7 6,734 Jun-17-2020, 07:14 PM
Last Post: Truman
  Python : NameError: name 'total_wait' is not defined carla 3 5,215 Jun-04-2017, 05:49 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020