最近我创建了一个GUI,它获取了一个CSV文件,并在所选位置绘制了所选变量的平均值和标准值。
几天前,GUI工作得非常好。一旦我加载CSV文件或选择了位置变量后,它就开始崩溃(没有响应)。有时它绘制第一组数据,然后它停止工作(我应该能够重新选择数据并重新绘制)。
然而,它经常起作用并绘制平均值和标准。
我一遍又一遍地搜索谷歌,但找不到任何问题的答案。
如果有人能提供帮助并给出解决方案,我将不胜感激。
import matplotlib
from Tkinter import *
import csv
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import numpy as np
import pylab as pl
from matplotlib import style
style.use('ggplot')
from tkFileDialog import askopenfilename
import inspect, os
root=Tk()
root.geometry("%dx%d+%d+%d" % (1500, 900, 500, 150))
root.title("Spectroscopy Library 1.0")
root.configure(bg='white')
#root.iconbitmap(iconpath) # setting the icon
T = Text(root, height=1, width=40,bg='white', fg='gray13',font=("Helvetica",24))
T.pack()
T.insert(END, "Tumor Average Spectra, Short Echo Time at 1.5 T")
filename = askopenfilename()
Label(root, text="Location:",bg='white').grid(row=3, sticky=W)
var1 = IntVar()
Checkbutton(root, text="Posterior Fossa", variable=var1,bg='white').grid(row=4, sticky=W)
var2 = IntVar()
Checkbutton(root, text="Supratentorial", variable=var2,bg='white').grid(row=5, sticky=W)
def tumor_select():
#----------------- calculating the file length---------------------------------
csv_file_size = open(filename, 'rU')
dataforsize = csv.reader(csv_file_size, delimiter=',')
row_count = pl.sum(1 for row2 in dataforsize)
#------------------defining matrixes-------------------------------------------
csv_file = open(filename, 'rU')
# csv_file = open("/Users/Emsku/Documents/Python/modeldata5.csv", "rU")
data = csv.reader(csv_file, delimiter=',')
tumor = ["" for x in range(row_count)] # defining an empty string
region = ["" for y in range(row_count)] #defining an empty string
fit = np.zeros((row_count, 456)) #defining a int array
# data into arrays
f = 0
for row in data:
tumor[f] = row[0]
region[f] = row[1]
fit[f] = row[2:]
f += 1
#---------------- devining data into region and tumor types -------------------
atrt = [];atrtfit =[];atrtloc =[]
gbm = [];gbmfit = [];gbmloc = []
gng = [];gngfit = [];gngloc = []
dast = [];dastfit = [];dastloc = []
aast = [];aastfit = [];aastloc = []
carn = [];carnfit = [];carnloc = []
cpp = [];cppfit = [];cpploc = []
cnspri = [];cnsprifit = [];cnspriloc = []
dnt = [];dntfit = [];dntloc = []
acpp = [];acppfit = [];acpploc = []
past = [];pastfit = [];pastloc = []
pin = [];pinfit = [];pinloc = []
cpc = [];cpcfit = [];cpcloc = []
germ = [];germfit = [];germloc = []
epen = [];epenfit = [];epenloc = []
anepen = [];anepenfit = [];anepenloc = []
med = [];medfit = [];medloc = []
dnmed = [];dnmedfit = [];dnmedloc = []
lmed = [];lmedfit = [];lmedloc = []
ast = [];astfit = [];astloc = []
sepen = [];sepenfit = [];sepenloc = []
glicer = [];glicerfit = [];glicerloc = []
gcast = [];gcastfit = [];gcastloc = []
swm = [];swmfit = [];swmloc = []
pong = [];pongfit = [];pongloc = []
ppm = []
for index, type in enumerate(tumor):
if type == 'Atypical Teratoid - Rhabdoid Tumour':
atrt.append(index)
atrtfit.append(fit[index,])
atrtloc.append(region[index])
if type == 'Glioblastoma':
gbm.append(index)
gbmfit.append(fit[index,])
gbmloc.append(region[index])
if type == 'ganglioglioma':
gng.append(index)
gngfit.append(fit[index,])
gngloc.append(region[index])
if type == 'diffuse_astrocytoma':
dast.append(index)
dastfit.append(fit[index,])
dastloc.append(region[index])
# part of the code (same as above for other tumor types) not included here
ppm = fit[0,]
# ATRT tumor
atrt_pf=[];atrt_sp=[]
for index, type in enumerate(atrtloc):
if type == 'posterior fossa':
atrt_pf.append(atrtfit[index])
elif type == 'Supratentorial':
atrt_sp.append(atrtfit[index])
if len(atrt_pf)>1:
atrtave_pf = np.mean(atrt_pf, axis=0);atrtsd_pf = np.std(atrt_pf, axis=0)
elif len(atrt_pf)==1:
atrtave_pf = np.mean(atrt_pf, axis=0) ;atrtsd_pf = np.zeros((456, 1))
if len(atrt_sp)>1:
atrtave_sp = np.mean(atrt_sp, axis=0);atrtsd_sp = np.std(atrt_sp, axis=0)
elif len(atrt_sp)==1:
atrtave_sp = np.mean(atrt_sp, axis=0); atrtsd_sp = np.zeros((456, 1))
# Glioblastoma
gbm_pf=[]; gbm_sp=[]
for index, type in enumerate(gbmloc):
if type == 'posterior fossa':
gbm_pf.append(gbmfit[index])
elif type == 'Supratentorial':
gbm_sp.append(gbmfit[index])
if len(gbm_pf)>1:
gbmave_pf = np.mean(gbm_pf, axis=0);gbmsd_pf = np.std(gbm_pf, axis=0)
elif len(gbm_pf)==1:
gbmave_pf = np.mean(gbm_pf, axis=0) ;gbmsd_pf = np.zeros((456, 1))
if len(gbm_sp)>1:
gbmave_sp = np.mean(gbm_sp, axis=0);gbmsd_sp = np.std(gbm_sp, axis=0)
elif len(gbm_sp)==1:
gbmave_sp = np.mean(gbm_sp, axis=0); gbmsd_sp = np.zeros((456, 1))
# Ganglioglioma
gng_pf=[]; gng_sp=[]
for index, type in enumerate(gngloc):
if type == 'posterior fossa':
gng_pf.append(gngfit[index])
elif type == 'Supratentorial':
gng_sp.append(gngfit[index])
if len(gng_pf)>1:
gngave_pf = np.mean(gng_pf, axis=0);gngsd_pf = np.std(gng_pf, axis=0)
elif len(gng_pf)==1:
gngave_pf = np.mean(gng_pf, axis=0) ;gngsd_pf = np.zeros((456, 1))
if len(gng_sp)>1:
gngave_sp = np.mean(gng_sp, axis=0);gngsd_sp = np.std(gng_sp, axis=0)
elif len(gng_sp)==1:
gngave_sp = np.mean(gng_sp, axis=0); gngsd_sp = np.zeros((456, 1))
dast_pf=[]; dast_sp=[]
for index, type in enumerate(dastloc):
if type == 'posterior fossa':
dast_pf.append(dastfit[index])
elif type == 'Supratentorial':
dast_sp.append(dastfit[index])
if len(dast_pf)>1:
dastave_pf = np.mean(dast_pf, axis=0);dastsd_pf = np.std(dast_pf, axis=0)
elif len(dast_pf)==1:
dastave_pf = np.mean(dast_pf, axis=0) ;dastsd_pf = np.zeros((456, 1))
if len(dast_sp)>1:
dastave_sp = np.mean(dast_sp, axis=0);dastsd_sp = np.std(dast_sp, axis=0)
elif len(dast_sp)==1:
dastave_sp = np.mean(dast_sp, axis=0); dastsd_sp = np.zeros((456, 1))
# part of the code (same as above for other tumor types) not included here
var3 = StringVar(root)
# initial value
var3.set(' Select Tumor Type ')
choices = ['Atypical Teratoid Rhabdoid Tumour', 'Anaplastic astrocytoma','Anaplastic ependymoma','Atypical Choroid Plexus Papilloma', 'Craniopharyngioma adamantinomatous', 'Choroid Plexus Carcinoma', 'Choroid plexus papilloma', 'CNS_primitive_neuroectodermal_tumour_94733', 'Diffuse astrocytoma', 'Dysembryoplastic Neuroepithelial Tumour','Desmoplastic-Nodular Medulloblastoma','Ependymoma ', 'Glioblastoma', 'Gliomatosis cerberi', 'Ganglioglioma', 'Germinoma','Large Cell Medulloblastoma','Medulloblastoma ', 'Pilomyxoid astrocytoma', 'Pinoblastoma', 'Pontine glioma', 'Pilocytic astrocytoma ', 'Schwannoma', 'Subependymoma', 'Unbiopsied Subependymal Giant Cell Astrocytoma']
option =OptionMenu(root, var3, *choices).grid(row=10, sticky=W)
button = Button(root, text=" Plot average Spectra ", command=tumor_select,bg="alice blue").grid(row=12, sticky=W)
#button.pack(side='left', padx=20, pady=10)
close_button = Button(root, text=" Quit ", command=root.destroy).grid(row=16, sticky=W)
root.mainloop()
答案 0 :(得分:0)
检查输入文件的大小,因为内存不足。你有2个列表包含输入文件,还有3个列表只是输入文件拆分,然后是一些相同数据的numpy数组。此代码将csv文件转换为磁盘上的SQL数据库,因此文件/内存大小不是问题(为什么使用SQL数据库会更容易)。然后一个常见的函数模拟绘图,但打印相反,所以你会知道a)它是否按你想要的方式工作,b)如果程序仍然挂起,那么这段代码就不是问题了。请注意,我不知道输入数据是什么样的,因此您必须在必要时进行调整。一些教程http://zetcode.com/db/sqlitepythontutorial/和http://freshmeat.net/articles/sqlite-tutorial
"""obviously this is a stripped down version in the interest
of time spent
"""
import os
import random
import sqlite3 as sqlite
def tumor_select(cur):
""" select the specified tumors and get and print
for each of the regions that you want
"""
tumor_list=['Atypical Teratoid - Rhabdoid Tumour','Glioblastoma',
'ganglioglioma', 'diffuse_astrocytoma']
region_list=['posterior fossa', 'Supratentorial']
print "\n========== tumor function================="
for tumor in tumor_list:
## append to list to be used in calcs instead of print
for region in region_list:
print "-"*70
print "%7s %-38s %-15s %5s" % ("rec-num", "tumor",
"region", "fit")
## using the dictionary look up method which has advantages IMHO
cur.execute("select * from test_dbf where t_tumor=:d_tumor and t_region=:d_region",
{"d_tumor": tumor, "d_region": region})
found=cur.fetchall()
for row in found:
print "%7d %-38s %-15s %5s" % (row[0], row[1], row[2], row[3])
def open_file():
""" creates a new SQL file with the fields below and populates
it with the csv data each time the program is run
"""
f_name="./test_1.SQL"
if os.path.isfile(f_name):
os.remove(f_name)
con = sqlite.connect(f_name)
cur = con.cursor()
cur.execute('''CREATE TABLE test_dbf(t_rec_num int, t_tumor varchar, t_region varchar, t_fit varchar)''')
## add each rec to the SQL DB
with open("./test_1.csv", "r") as fp_in:
for rec_num, rec in enumerate(fp_in):
fields = rec.strip().split(",")
cur.execute('INSERT INTO test_dbf values (?,?,?,?)', tuple([rec_num]+fields))
con.commit()
return cur
def print_all_recs(cur):
cur.execute("select * from test_dbf")
recs_list=cur.fetchall()
for rec in recs_list:
print rec
## output some test data
tumor_list=['Atypical Teratoid - Rhabdoid Tumour','Glioblastoma',
'ganglioglioma', 'diffuse_astrocytoma',
'something else']
region_list=['posterior fossa', 'Supratentorial',
'something else']
with open("./test_1.csv", "w") as fp_out:
for ctr in range(100):
## don't knoe what "fit" is so just use a number
fp_out.write("%s,%s,%s%s\n" % (random.choice(tumor_list),
random.choice(region_list), "fit ", ctr))
cur = open_file()
print_all_recs(cur) ## while testing
tumor_select(cur)