Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Problem In calling a Function from another python file of project
#1
Hello Everyone,
Smile

I had created two different python files (EEG.py and Digital_Filter.py) in pycharm IDE under one project.
And I want to call a function declared in Digital_Filter.py into EEG.py but I am receving an error
(ImportError: cannot import name 'apply_filter' from 'Digital_Filter' (C:\Users\LM HealthCare\Documents\Pycharm\Projects\EEG\Digital_Filter.py))


And this is the code I am using to do this
# import Tkinter
from tkinter import *
from Digital_Filter import apply_filter

Now can any one please help me in getting out of this.
Quote
#2
(Sep-25-2019, 01:07 PM)vinod2810 Wrote: Now can any one please help me in getting out of this.

Not with what you've given us. We need more information about Digital_Filter. Is it small enough that you can post it here? The question is really how apply_filter is defined in the file. If it is defined conditionally or within another function or class, that could be why the import is not seeing it. Also check to make sure the path given in the error is the path to the correct file.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#3
I am posting my digital filter code below:
from scipy import signal
from EEG import eeg_data
import array as arr


sample_rate = 250
nyquist_rate = sample_rate/2

gMax_Blocks = 32
gMax_Samples = 8
gMax_Channel = 4

# Cofficient for IIR filters
b2 = arr.array('d',[0.965080986344733, -0.242468320175764, 1.94539149412878, -0.242468320175764, 0.965080986344733])
a2 = arr.array('d',[1, -0.246778261129785, 1.94417178469135, -0.238158379221743, 0.931381682126902])
b = arr.array('d',[0.200138725658073, 0, -0.400277451316145, 0, 0.200138725658073])
a = arr.array('d',[1, -2.35593463113158, 1.94125708865521, -0.784706375533419, 0.199907605296834])



def apply_filter():
    fc = 0.5  # Cut-off frequency of the filter
    w = fc / (sample_rate / 2)  # Normalize the frequency
    b, a = signal.butter(2, w, 'high')
    for  line in eeg_data:
        output = arr.arry('d',[signal.filtfilt(b, a, line)])
Quote
#4
I don't know why that doesn't work. I copied your code and it works for me, although I had to comment out the EEG import as I don't have that module.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#5
let me post booth of my files

first file EEG.py
#import os
#os.chdir("C:\\Users\\LM HealthCare\\Documents\\Pycharm\\Projects\\EEG")

# import Tkinter
from tkinter import *
from scipy import signal
#from Digital_Filter import apply_filter
import Digital_Filter
from scipy import signal
# from win32api import GetSystemMetrics
import array as arr
import ctypes

user32 = ctypes.windll.user32

main = Tk()

# Setting Main Window of the Application
main.title('NeuroCare')
screen_width = main.winfo_screenwidth()
screen_height = main.winfo_screenheight()
main_Window_width = screen_width - 8
main_Window_height = screen_height - 90

main.geometry("{}x{}+{}+{}".format(main_Window_width, main_Window_height, -5, -3))
main.resizable(0, 0)

# Adding menubar and menu options
menu = Menu(main)
menu.bg = 'black'
main.config(menu=menu)

filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label='New')

editmenu = Menu(menu)
menu.add_cascade(label='Edit', menu=editmenu)

# Adding Toolbar options
toolbar = Frame(main.master, bd=1, relief=RAISED, bg='light blue')
New_button = Button(toolbar, text='Start', activebackground='light grey' ).pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)

# Add a canvas to plot eeg waves
eeg_canvas = Canvas(main, bg='yellow', width=main_Window_width, height=main_Window_height - 40, relief = SUNKEN).pack(fill=X, side="top")

# Reading text file in
with open("C:\\Users\\LM HealthCare\\Desktop\\Desktop C drive desktop\\EEG,ECG txt Data\\eeg ch1.txt", "r") as f:
    eeg_data = f.read()
    eeg_data = eeg_data.split('\n')

for line in eeg_data:
    #line1 = float(line)
 #   output = arr.array('f',(line1))
    output= float(line)
 
    Filtered_Data = Digital_Filter.apply_filter(output)

main.mainloop()
Second File Digital_Filter .py
from scipy import signal
# from EEG import eeg_data
import EEG
import array as arr


sample_rate = 250
nyquist_rate = sample_rate /2

gMax_Blocks = 32
gMax_Samples = 8
gMax_Channel = 4

# Cofficient for IIR filters
b2 = arr.array('d' ,[0.965080986344733, -0.242468320175764, 1.94539149412878, -0.242468320175764, 0.965080986344733])
a2 = arr.array('d' ,[1, -0.246778261129785, 1.94417178469135, -0.238158379221743, 0.931381682126902])
b = arr.array('d' ,[0.200138725658073, 0, -0.400277451316145, 0, 0.200138725658073])
a = arr.array('d' ,[1, -2.35593463113158, 1.94125708865521, -0.784706375533419, 0.199907605296834])



def apply_filter(output):
    fc = 0.5  # Cut-off frequency of the filter
    w = fc / (sample_rate / 2)  # Normalize the frequency
    b, a = signal.butter(2, w, 'high' ,analog=False)
    x = [signal.filtfilt(b, a, output)]
    return x
Now It Is Showing Error:
AttributeError: module 'Digital_Filter' has no attribute 'apply_filter'
Quote
#6
Oh, it's a circular import problem. If A imports B, B cannot then import A. It seems the main problem is you want eeg_data from EEG in Digital_Filter. You don't seem to be using it in EEG, so I would probably just load it in Digital_Filter. Another option is to have a third module that loads eeg_data, that both EEG and Digital_Filter can import.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#7
Thanks for your valuable reply facing another problem similar like this I am posting my error and code below please provide your suggestion

Error faced is described below:
Backend TkAgg is interactive backend. Turning interactive mode on.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\LM HealthCare\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\LM HealthCare\Documents\Pycharm\Projects\EEG\EEG.py", line 47, in click
Click_Listner.Start_click(line)
AttributeError: module 'Click_Listner' has no attribute 'Start_click'




Code for EEG.py

from tkinter import *
import numpy as np
import Digital_Filter
import array as arr
import matplotlib.pyplot as plt
import Click_Listner
import Test
# some program constants
alpha_band_Hz = [8.0, 10.5]   # where to look for the alpha peak
noise_band_Hz = [14.0, 20.0]  # was 20-40 Hz
NFFT = 400      # pitck the length of the fft
fs_Hz = 100.0   # assumed sample rate for the EEG data
f_lim_Hz = [0, 40]      # frequency limits for plotting
t_lim_sec = [0, 0]      # default plot time limits [0,0] will be ignored
alpha_lim_sec = [0, 0]  # default
output = [] # Array to store float data coverted from string


main = Tk()
# Reading text file in
def read_file():
    with open("C:\\Users\\LM HealthCare\\Desktop\\Desktop C drive desktop\\EEG,ECG txt Data\\delta_Band_Power.txt", "r") as f:
        eeg_data = f.read()
        eeg_data = eeg_data.split('\n')
        n = 0



        for line in eeg_data:
            line1 = float(eeg_data[n])
            output.append(line1)
            n += 1
    # Applying filters
    Filtered_Data = Digital_Filter.apply_filter1hz_Highpass(output)
    t_sec = np.array(range(0, Filtered_Data.size)) / 250
    #ax[0].plot(t_sec, Filtered_Data, color='green')
    Filtered_Data = Digital_Filter.apply_filter60hz_Notch(Filtered_Data)
    #ax[1].plot(t_sec, Filtered_Data, color='red')
    Filtered_Data = Digital_Filter.apply_filter120hz_Notch(Filtered_Data)
    return Filtered_Data

# Functions for click events
def click():
    Test.Ft_data=read_file()
    for line in Test.Ft_data:
        Click_Listner.Start_click(line)

# Setting Main Window of the Application
main.title('NeuroCare')
screen_width = main.winfo_screenwidth()
screen_height = main.winfo_screenheight()
main_Window_width = screen_width - 8
main_Window_height = screen_height - 90

main.geometry("{}x{}+{}+{}".format(main_Window_width, main_Window_height, -5, -3))
main.resizable(0, 0)
Filtered_Data = []


# Adding menubar and menu options
menu = Menu(main)
menu.bg = 'black'
main.config(menu=menu)

filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label='New')

editmenu = Menu(menu)
menu.add_cascade(label='Edit', menu=editmenu)

# Adding Toolbar options
toolbar = Frame(main.master, bd=1, relief=RAISED, bg='light blue')
New_button = Button(toolbar, text='Start', activebackground='light grey', command=click ).pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)

# Add a canvas to plot eeg waves
eeg_canvas = Canvas(main, bg='yellow', width=main_Window_width, height=main_Window_height - 40, relief = SUNKEN).pack(fill=X, side="top")

Raw_data = []


#plt.plot(output, 'k-', label='input')
#plt.show()


# fig, ax  = plt.subplots(2,1)
#
#
# ax[0].plot(t_sec, Filtered_Data, color='blue')
# ax[0].set_ylim(-100, 100)
# ax[0].set_xlim(0, 30)
# ax[0].set_ylabel('EEG (uV)')
# ax[0].set_xlabel('Time (sec)')
#
# plt.ylim(-100, 100)
# plt.ylabel('EEG (uV)')
# plt.xlabel('Time (sec)')
# plt.xlim(70, 120)
#Filtered_Data = Filtered_Data.__format__('%.5f')


#plt.show()


#plt.plot(Filtered_Data, 'b-', linewidth=1.5, label='filtered')
#plt.show()
#Filtered_Data = Filtered_Data.split('\n')
x=10

main.mainloop()


Code for click_listner:

import Functions
#import Test
def Start_click(xvalue):
   # for line in Test.Ft_data:
        Functions.dataEnter = True
        Functions.Print_Canavas(xvalue)
   # x=True

Code for functions:

import EEG
currentX = 0
lastX = 0
y1 = 200
y2=  200
dataEnter = False
def Print_Canavas(xvalue):
    currentx = lastX + 0.1
    if dataEnter == True :
        EEG.eeg_canvas.create_line(lastX, y1, currentX , (y2-xvalue), fill = 'Green')
        EEG.eeg_canvas.create_line(0, 50 * 2, 400, 50 * 2)

        y1= ( y2 - xvalue )
        dataEnter = False
    lastX = currentX
    if lastX == EEG.eeg_canvas.width:
        lastx = 0


Code for Test:

Ft_data=[]
Quote
#8
It's the same problem just extended a bit. EEG imports Click_Listener, Click_Listener imports Functions, and Functions tries to import EEG, which isn't finished loading yet because it is still trying to import Click_Listener.

This is highlighting why classes and object oriented programming are so useful to GUI programming. You have a function bound to an event, so you don't have control of it's parameters. But you need to access other parts of your GUI from the function. You're trying to do this with imports, so you keep getting circular imports. If the function is part of the same class as the rest of the GUI, it can access the other parts of the GUI using class attributes.

I would really recommend learning OOP and classes before moving forward with GUIs. There are lots of tutorials on this site about classes. I even link to one in my signature.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  python file(.py) not working with my tkinter project DeanAseraf1 8 254 Jul-30-2019, 12:55 PM
Last Post: DeanAseraf1
  Calling widget from another function? WuchaDoin 1 531 Oct-23-2018, 12:55 AM
Last Post: stullis

Forum Jump:


Users browsing this thread: 1 Guest(s)