Commit d343134d authored by Julio Tambara's avatar Julio Tambara
Browse files

Cursor add, ROI arrumada, DeadTime modificado

Verção para organizar o repositório git
parent 04d8efa2
import numpy as np
import Tkinter as tk
import matplotlib.pyplot as plt
class Graficos:
def __init__(self, Nmr):
self.Nmr_serial= Nmr
self.limupdtx=True
self.limupdty=True
self.limupdt=True
self.limctrl=False
self.x0=0
self.y0=0
self.x1=512
self.y1=0
self.pressx=0.
self.pressy=0.
self.limtrans=False
self.dx=0.
self.dy=0.
self.Nmr_serial= None
self.f= plt.figure()
self.title=None # poderia tirar direto do grafico
self.a= self.f.add_subplot(111, axisbg='#555555')
self.temp=None
self.dataPlot=None
self.Frame=None
self.Cursor=dict(x=256,line=self.a.axvline(x=256,color='red'))
......@@ -9,23 +9,21 @@ from array import *
class Modulo:
Data=array('L',[0]*8192)
Controle=dict(pause=1,Nmr_serial=0,Nmr_canais=512, ON=0)
Livetime = dict(ADC_Conversion=0 , Time=0. , LiveTime=0.)
child= None
def __init__(self, Nmr_modulo):
self.child = pexpect.spawn('./N957Run '+ Nmr_modulo)
#self.Controle['Nmr_serial']=Serial
self.Data=array('L',[0]*8192)
self.Controle=dict(pause=1,Nmr_serial=0,Nmr_canais=512, ON=0)
self.Livetime = dict(ADC_Conversion=0 , Time=0. , DeadTime=0.)
def start(self):
self.child.send('s')
msg=(self.child.readline().strip("\r\n"))
if msg == 'OK':
return 1
else:
return msg
......@@ -65,17 +63,18 @@ class Modulo:
self.Data = eval(self.child.readline().strip("\r\n"))
self.Livetime['ADC_Conversion'] = int(self.child.readline().strip("\r\n"))
self.Livetime['Time'] = float(self.child.readline().strip("\r\n"))
self.Livetime['LiveTime'] = float(self.child.readline().strip("\r\n"))
self.Livetime['DeadTime'] = (self.Livetime['Time'] - float(self.child.readline().strip("\r\n")))*100/self.Livetime['Time']
return msg
def dump(self): # Sinal para programa coletor enviar os dados
self.child.send('i')
def reset(self,size):
for k in range(size):
self.Data[k] = 0
def reset(self):
self.child.send('r')
for k in range(self.Controle['Nmr_canais']):
self.Data[k] = 0
def pause(self):
self.child.send('p')
......
MCA = 113
#MCB = 175
#MCC = 174
......@@ -11,7 +11,6 @@ import tkMessageBox
import tkFileDialog
import matplotlib.pyplot as plt
import time
import subprocess
from pylab import *
from os.path import basename
#from clsbeep import *
......@@ -23,6 +22,7 @@ from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolb
# implement the default mpl key bindings
from matplotlib.figure import Figure
import sys
if sys.version_info[0] < 3:
import Tkinter as Tk
......@@ -30,6 +30,7 @@ else:
import tkinter as Tk
Plot=dict( Data=dict(), Plotbuttons=list(), Pcontrol=list(), Name=list() )
Interface = dict(frames=list(), buttons=list(), labels=list(), spinboxes=list(), entries=list(), labelframes=list())
......@@ -39,12 +40,23 @@ n=0;#numero de botoes removidos (facilita)
Axis=dict( x_max=int , x_min=int, y_max=int, y_min=int, x_click=float, y_click=float)
root = Tk.Tk()
root.minsize(825,640)
root.wm_title("Buffer")
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
f = plt.Figure(figsize=(5,4), dpi=100)
a = f.add_subplot(111)
......@@ -76,16 +88,15 @@ def plot_select(name_plot, button):
Plot['Pcontrol'][j] = 1
refresh()
def add_plot():
def add_plot(Name):
global j, Plot
newfile = tkFileDialog.askopenfilename()
Plot['Data'][j] = np.loadtxt(newfile)
Plot['Data'][j] = np.loadtxt(Name)
Plot['Pcontrol'].insert(j,1)
Plot['Name'].insert(j,basename(newfile))
Plot['Plotbuttons'].insert(j, tk.Button(pltbutfrm, text=basename(newfile), height=1,relief='sunken', command = lambda j=j : plot_select(basename(newfile),Plot['Plotbuttons'])))
Plot['Name'].insert(j,basename(Name))
Plot['Plotbuttons'].insert(j, tk.Button(pltbutfrm, text=basename(Name), height=1,relief='sunken', command = lambda j=j : plot_select(basename(Name),Plot['Plotbuttons'])))
#Plot['Plotbuttons'][j].grid( row = len(Plot['Plotbuttons']))
Plot['Plotbuttons'][j].pack(fill='x')
remove_menu.add_command(label=basename(newfile), command=lambda:remove_plot(basename(newfile)))
remove_menu.add_command(label=basename(Name), command=lambda:remove_plot(basename(Name)))
j = j + 1
refresh()
......@@ -110,13 +121,14 @@ def remove_plot(name_plot):
refresh()
########################################################################
########################################################################
# Menu
menubar = Tk.Menu(root, relief='raised', bd=2)
filemenu = Tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Open",command = lambda:add_plot())
filemenu.add_command(label="Open",command = lambda:add_plot(tkFileDialog.askopenfilename()))
filemenu.add_command(label ="Save") #, command = lambda i=i: save('g12'))
filemenu.add_command(label ="Save As") #, command = lambda i=i: saveas('g12'))
filemenu.add_command(label="Exit",command = lambda:_quit()) #, command = _quit)
......@@ -183,11 +195,23 @@ Interface['frames'][3].bind("<ButtonRelease-3>", mouse_TR )#top_right
########################################################################
########################################################################
try:
add_plot('Buffer.MCA')
except IOError:
print tkMessageBox.askretrycancel("ERRO", "ERRO_10 ")
_quit()
try:
add_plot('Buffer.MCB')
except IOError:
None
try:
add_plot('Buffer.MCC')
except IOError:
None
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
......
File mode changed from 100644 to 100755
......@@ -98,10 +98,6 @@ int main(int argc, char **argv)
/////////////////////////////////////////
memset( &user_setting, 0, sizeof( user_setting));
if((argc+'0')>= 2)
user_setting.m_bd_num= atoi(argv[1]);
else
user_setting.m_bd_num=0; // tem problemas "falha de segmentação", mas eu n to usando.
......@@ -130,6 +126,12 @@ int main(int argc, char **argv)
}
memset( histo_buff, 0, N957_MAX_HISTO_SAMPLES* sizeof( *histo_buff));
if((argc+'0')>= 2)
user_setting.m_bd_num= atoi(argv[1]);
else
user_setting.m_bd_num=0; // tem problemas "falha de segmentação", mas eu n to usando.
do_exit= FALSE;
while( !do_exit) {
......@@ -177,11 +179,12 @@ int main(int argc, char **argv)
case 's':
case 'S':
/// input parameter check
if( !user_settings_parse_input_param( &user_setting, argc, (char**)argv))
if( !parse_config_file( &user_setting))
{
TRACE("erro_2\n");
N957_End(user_setting.m_N957_handle);
break;
//goto exit_point;
}
/////////////////////////////////////////
......@@ -198,20 +201,19 @@ int main(int argc, char **argv)
{
TRACE("erro_3");
break;
//goto exit_point;
}
}
if( N957_GetScaler(user_setting.m_N957_handle, &data32))
{
TRACE("erro_5");
//goto exit_point;
break;
}
if(N957_StartAcquire( user_setting.m_N957_handle, user_setting.m_mode))
{
TRACE("erro_6");
//goto exit_point;
break;
}
if( user_setting.m_debug) {
......@@ -219,10 +221,17 @@ int main(int argc, char **argv)
{
TRACE("erro_7");
//goto exit_point;
break;
}
}
if((N957_StopAcquire( user_setting.m_N957_handle)))
{
TRACE("erro_24\n");
goto exit_point;
}
start= TRUE;
paused=TRUE;
TRACE("OK\n");
break;
......@@ -296,6 +305,7 @@ int main(int argc, char **argv)
case 'a': // 8192 canais
fator = 1;
break;
case 'b':// 4096 canais
fator = 2;
break;
......
......@@ -8,7 +8,9 @@ import Tkinter as tk
import tkMessageBox
import tkFileDialog
import matplotlib.pyplot as plt
from matplotlib import pyplot, lines
import time
import pexpect
import subprocess
from User_Config import*
from Modulo import *
......@@ -27,16 +29,10 @@ from matplotlib.figure import Figure
##############################################################################
# GLOBAL VARIABLES AND DEFINITIONS
Control = dict(Refresh=600, bmin=0, bmax=8192, bmaxold=512, j=0, filename='temp', count=0, paused=True, ROIctrl=list(),CALIctrl=list(), start=False, Logaritmo=False, graphic1=True, graphic2=True)
PlotLimControl = dict(limupdtx=True, limupdty=True, limupdt=True, limctrl=False, x0=0, y0=0, x1=512, y1=0, pressx=0., pressy=0., limtrans=False, dx=0., dy=0., limupdt_b=True, limupdt_bx=True, limupdt_by=True, limctrl_b=False, x0_b=0, y0_b=0, x1_b=512, y1_b=0, pressx_b=0., pressy_b=0., limtrans_b=False, dx_b=0., dy_b=0.)
Control = dict(text_cursor='Cursor:',Refresh=600, bmin=0, bmax=8192, bmaxold=64, j=0, filename='temp', count=0, paused=True, ROIctrl=list(),CALIctrl=list(), Logaritmo=False, graphic1=True, graphic2=True, G_cursor=None)
FocusControl = dict( full_screen= False, aux_click='gg')
Grafic=list()
M=list()
Grafico=list()
M=list() #lista com módulos, instancias da classe (arquivo Modulo)
ROIs=list()
Interface = dict(frames=list(), buttons=list(), labels=list(), spinboxes=list(), entries=list(), labelframes=list())
......@@ -54,32 +50,44 @@ except NameError:
else:
M.insert(0,Modulo('0'))
M[0].Nmr_serial= MCA
Grafic.insert(0,Graficos(M[0].Nmr_serial))
Grafic[0].f.suptitle('# A')
Grafico.insert(0,Graficos(M[0].Nmr_serial))
Grafico[0].f.suptitle('# A')
Grafico[0].title=('A')
time.sleep(0.5)
try:
MCB
except NameError:
tkMessageBox.showinfo("Não implementado", "Colocar modo de aquisição para um módulo!")
sys.exit
None
else:
M.insert(1,Modulo('1'))
M[1].Nmr_serial= MCA
Grafic.insert(1,Graficos(M[1].Nmr_serial))
Grafic[1].f.suptitle('# B')
M[1].Nmr_serial= MCB
Grafico.insert(1,Graficos(M[1].Nmr_serial))
Grafico[1].f.suptitle('# B')
Grafico[1].title=('B')
try:
MCC
except NameError:
None
else:
M.insert(2,Modulo('2'))
M[2].Nmr_serial=MCC
Grafico.insert(2,Graficos(M[2].Nmr_serial))
Grafico[2].f.suptitle('# C')
Grafico[2].title=('C')
time.sleep(1.5)
sys.setrecursionlimit(5000)
sys.setrecursionlimit(5000)
xx = arange(0, 8192)
##############################################################################
##############################################################################
......@@ -144,9 +152,18 @@ def updateroi(fator):
Control['bmaxold'] = fator
class InterestRegion:
def __init__(self, labfrm, j):
self.Area = 0
self.Area2 = 0
self.Area=list()
for x in range(len(M)):
self.Area.insert(x, 0)
self.text= ""
for x in range(len(M)):
self.text=self.text + 'Conts#'+ str(x+1) +' '+ str(self.Area[x])
if not(x == 0):
self.text=self.text +'\n'
self.xmin = 0
self.xmax = Control['bmax']-1
self.xmine = tk.Entry(labfrm)
......@@ -157,31 +174,35 @@ class InterestRegion:
self.xmaxe = tk.Entry(labfrm)
self.xmaxe.pack(side='left')
self.xmaxe.insert(0, self.xmax)
self.label2 = tk.Label(labfrm, text=('Counts #1: %d\n' %self.Area + 'Counts #2: %d' %self.Area2))
self.label2 = tk.Label(labfrm, text=self.text)
self.label2.pack(side='bottom')
def ROIme(self):
global M, Grafico
if self.xmine.get().isdigit() and self.xmaxe.get().isdigit() and int(self.xmine.get()) >= 0 and int(self.xmaxe.get()) >= 0 and int(self.xmaxe.get()) < int(Interface['spinboxes'][0].get()) and int(self.xmine.get()) < int(Interface['spinboxes'][0].get()):
for xx in range(len(M)):
if int(self.xmaxe.get()) >= int(self.xmine.get()):
self.xmin = int(self.xmine.get())
self.xmax = int(self.xmaxe.get())
self.Area = 0
self.Area2 = 0
elif int(self.xmaxe.get()) < int(self.xmine.get()):
self.xmin = int(self.xmaxe.get())
self.xmax = int(self.xmine.get())
self.Area = 0
self.Area2 = 0
for x in range(len(M)):
self.Area[x] = 0
if int(self.xmax) == int(self.xmin):
self.Area = M[0].Data[int(self.xmax)]
self.Area2 = M[1].Data[int(self.xmax)]
for Mod in M:
self.Area[M.index(Mod)] = Mod.Data[int(self.xmax)]
else:
for n in range(self.xmin, self.xmax+1):
self.Area = self.Area + M[0].Data[n]
self.Area2 = self.Area2 + M[1].Data[n]
self.label2['text']=('Counts #1: %d\n' %self.Area + 'Counts #2: %d' %self.Area2)
for Mod in M:
self.Area[M.index(Mod)] = self.Area[M.index(Mod)] + Mod.Data[n]
self.text=''
for xx in range(len(M)):
self.text=self.text + 'Conts#'+ str(xx+1) +' '+ str(self.Area[xx])
if not(x == 0):
self.text=self.text +'\n'
self.label2['text']=self.text
else:
self.label2['text']="Invalid values"
......@@ -207,26 +228,16 @@ def roiroi():
addROI()
roiwin.mainloop()
def chage_focus(): #change the focus g1->g2->g1&g2->
if (g1_show and g2_show):
if Controlfocus['g1_sel']:
if Controlfocus['g2_sel']:
return
#proximo = g1
#else:
#proximo =g2
if Controlfocus['g2_sel']:
return
#proximo =g1eg2
##############################################################################
##############################################################################
def set_fator(canais): # Define o fator para conversao do numero de canais
M[0].set_fator(canais)
M[1].set_fator(canais)
for Mod in M:
Mod.set_fator(canais)
Control['bmax']= int(canais)
updateroi(int(canais))
......@@ -272,53 +283,52 @@ def testeerro(Data): # mensagens de erros
else:
return True
def graphic2(Data, Data2): #trata as informações que foram salvas em graphic1
temp.set_xdata(range(int(Interface['spinboxes'][0].get())))
temp.set_ydata(Data)
temp2.set_xdata(range(int(Interface['spinboxes'][0].get())))
temp2.set_ydata(Data2)
if PlotLimControl['limupdtx'] or PlotLimControl['limupdty']:
def graphic2(): #trata as informações que foram salvas em graphic1
for G in Grafico:
G.temp.set_xdata(range(int(M[Grafico.index(G)].Controle['Nmr_canais'])))
G.temp.set_ydata(M[Grafico.index(G)].Data)
for G in Grafico:
if G.limupdtx or G.limupdty:
if Control['Logaritmo']:
Grafic[0].a.set_yscale('log')
G.a.set_yscale('log')
G.a.grid(False)
else:
Grafic[0].a.relim()
Grafic[0].a.autoscale_view(scaley=PlotLimControl['limupdty'],scalex=PlotLimControl['limupdtx'])
if PlotLimControl['limupdt_bx'] or PlotLimControl['limupdt_by'] :
if Control['Logaritmo']:
Grafic[1].a.set_yscale('log')
G.a.relim()
G.a.autoscale_view(scaley=G.limupdty,scalex=G.limupdtx)
else:
Grafic[1].a.relim()
Grafic[1].a.autoscale_view(scaley=PlotLimControl['limupdt_by'],scalex=PlotLimControl['limupdt_bx'])
if PlotLimControl['limupdtx'] == True:
grid(Grafic[0].a, int(Interface['spinboxes'][0].get()))
if PlotLimControl['limupdt_bx'] == True:
grid(Grafic[1].a, int(Interface['spinboxes'][0].get()))
Grafic[0].f.canvas.draw()
Grafic[1].f.canvas.draw()
for G in Grafico:
if G.limupdtx == True and Control['Logaritmo'] == False:
grid(G.a, int(M[Grafico.index(G)].Nmr_canais))
def graphic(): # Le os dados provenientes dos módulos
Control['text_cursor']='Cursor '
for G in Grafico:
Control['text_cursor']= Control['text_cursor'] + G.title + ':(' +str(G.Cursor['x']) + ','+str(M[Grafico.index(G)].Data[G.Cursor['x']])+ ') '
G.f.canvas.draw()
Interface['labels'][1+3*len(Grafico)].configure(text= Control['text_cursor'])
def graphic(): # Le os dados provenientes dos módulos
testeerro(M[0].Read_Data())
testeerro(M[1].Read_Data())
for Mod in M:
testeerro(Mod.Read_Data())
Interface['labels'][0].configure(text='ADC : %s' %str(M[0].Livetime['ADC_Conversion']))
Interface['labels'][1].configure(text='Total Time: %ss' %str(M[0].Livetime['Time']/1000))
Interface['labels'][2].configure(text='Live Time: %ss' %str(M[0].Livetime['LiveTime']/1000))
Interface['labels'][3].configure(text='ADC : %s' %str(M[1].Livetime['ADC_Conversion']))
Interface['labels'][4].configure(text='Total Time: %ss' %str(M[1].Livetime['Time']/1000))
Interface['labels'][5].configure(text='Live Time: %ss' %str(M[1].Livetime['LiveTime']/1000))
aux=0;
for Mod in M:
Interface['labels'][aux].configure(text='ADC : %s' %str(Mod.Livetime['ADC_Conversion']))
Interface['labels'][aux+1].configure(text='Total Time: %ss' %str(Mod.Livetime['Time']/1000))
Interface['labels'][aux+2].configure(text='Dead Time: %.5f %%' %(Mod.Livetime['DeadTime']))
aux=aux+3 #CUIDADO para implementar + de 2 módulos Interface['labels'] deve ser re-organizado
graphic2(M[0].Data, M[1].Data)
graphic2()
def realtimeplot(): # Funcao recursiva para plot em tempo real
global ROIs
if not Control['paused']:
M[0].dump()
M[1].dump()
for Mod in M:
Mod.dump()
try:
root.after(Control['Refresh'], realtimeplot)
graphic()
......@@ -335,34 +345,33 @@ def realtimeplot(): # Funcao recursiva para plot em tempo real
def hide_graphic(): #a= hide 1#, b=hide 2#, x= unhide
print Control['Logaritmo']
if FocusControl['full_screen']==True:
Interface['frames'][11].place_forget()
Interface['frames'][10].place_forget()
Interface['frames'][10].place(anchor='nw',relheight=0.99, relwidth=0.5)
Interface['frames'][11].place(anchor='nw',relheight=0.99, relwidth=0.5, relx = 0.5)
rig_but_menu.entryconfig('Unhide graphic',label ='Hide graphic')
FocusControl['full_screen']=False
elif FocusControl['aux_click']=='g1':
Interface['frames'][10].place_forget()
Interface['frames'][11].place_configure(anchor='n',relwidth=0.99,relheight=0.99)
rig_but_menu.entryconfig('Hide graphic',label ='Unhide graphic')
FocusControl['full_screen']=True
elif FocusControl['aux_click']=='g2':
Interface['frames'][11].place_forget()
Interface['frames'][10].place_forget()
Interface['frames'][10].place_configure(anchor='n',relwidth=0.99,relx=0.5,relheight=0.99)
rig_but_menu.entryconfig('Hide graphic',label ='Unhide graphic')
FocusControl['full_screen']=True
def reset(M_1, M_2): # Zera o vetor de aquisicao
if M_1:
M[0].reset(int(Interface['spinboxes'][0].get()))
if M_2:
M[1].reset(int(Interface['spinboxes'][0].get()))
graphic2(M[0].Data,M[1].Data)
# if FocusControl['full_screen']==True:
# Interface['frames'][11].place_forget()
# Interface['frames'][10].place_forget()
# Interface['frames'][10].place(anchor='nw',relheight=0.99, relwidth=0.5)
# Interface['frames'][11].place(anchor='nw',relheight=0.99, relwidth=0.5, relx = 0.5)
# rig_but_menu.entryconfig('Unhide graphic',label ='Hide graphic')
# FocusControl['full_screen']=False
# elif FocusControl['aux_click']=='g1':
# Interface['frames'][10].place_forget()
# Interface['frames'][11].place_configure(anchor='n',relwidth=0.99,relheight=0.99)
# rig_but_menu.entryconfig('Hide graphic',label ='Unhide graphic')
# FocusControl['full_screen']=True
# elif FocusControl['aux_click']=='g2':
# Interface['frames'][11].place_forget()