Commit 04d8efa2 authored by Julio Tambara's avatar Julio Tambara
Browse files

Mudando a forma das estrutura de dados

Adicionado a classe graficos.
parent a5258ef3
import numpy as np
import Tkinter as tk
class Graficos:
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.
Nmr_serial= None
def __init__(self, Nmr):
self.Nmr_serial= Nmr
......@@ -3,9 +3,6 @@
# ****************************************************************
# Lines starting with # (first column) are comments
#
# The board number
BOARD_NUM 1
# path to the executable file of gnuplot
GNUPLOT_PATH ""
......@@ -14,9 +11,6 @@ GNUPLOT_PATH ""
# Save readout data into the Output File (0=don't save)
LOG_TO_FILE 1
#
# Readout data Output Filename ( meaningful only for LOG_TO_FILE!= 0)
#LOG_FILENAME "data.log"
#
# Maximum number of samples to acquire (-1 means no limit)
......@@ -38,13 +32,6 @@ ACQ_MODE 1
# LLD Threshold value [00..99]
LLD_THR_VAL 30
#
# Gnu plot refresh rate (msec)
#GNU_PLOT_REFRESH 2000
#
# Gnu plot X scale factor
#GNU_PLOT_X_SCALE 0.3
......@@ -53,4 +40,3 @@ LLD_THR_VAL 30
......@@ -36,6 +36,8 @@ const char* HISTO_FILENAME= "histo.dat";
// Global visible variables declaration
////////////////////////////////////////////
////////////////////////////////////////////
// File local methods declaration
////////////////////////////////////////////
......@@ -58,8 +60,11 @@ const char* HISTO_FILENAME= "histo.dat";
************************************************************************************************/
int main(int argc, char **argv)
{
{
int w;
unsigned int histograma[8192];
unsigned int temp = 0, lldt=10;
......@@ -69,7 +74,9 @@ int main(int argc, char **argv)
FILE* log;
short int fator = 1;
N957_UINT32 data32;
int ret_val= 0; // procedure exit value
int ret_val= 0;
N957_ConfigROM ROM;
// procedure exit value
user_setting_data user_setting; // user settings
N957_UINT16 *data_buff= NULL; // read data buffer
unsigned long *histo_buff= NULL; // Histogram data buffer
......@@ -81,6 +88,8 @@ int main(int argc, char **argv)
BOOL start=FALSE;
BOOL erro_9=FALSE;
for(w=0; w<8192; w++)
histograma[w] = 0;
......@@ -89,6 +98,11 @@ 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.
// init user setting module
......@@ -157,6 +171,9 @@ int main(int argc, char **argv)
}
if( kbhit()) {
switch( getch()) {
case 'q':
case 'Q':
goto exit_point;
case 's':
case 'S':
/// input parameter check
......@@ -353,9 +370,11 @@ int main(int argc, char **argv)
fclose(log);
break;
case 'k':
TRACE("OK\n");
N957_GetConfigROM( user_setting.m_N957_handle, &ROM);
//N957_ConfigROM.m_board_id=1;
TRACE1("%u \n",'N957_ConfigROM.m_board_id');
TRACE1("%u \n" ,ROM.m_serial);
break;
}
......
......@@ -3,7 +3,6 @@
import os
import sys
import pexpect
import numpy as np
import Tkinter as tk
import tkMessageBox
......@@ -11,35 +10,75 @@ import tkFileDialog
import matplotlib.pyplot as plt
import time
import subprocess
from User_Config import*
from Modulo import *
from Graficos import *
from pylab import *
#from clsbeep import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
##############################################################################
##############################################################################
# GLOBAL VARIABLES AND DEFINITIONS
f = plt.figure()
f2 = plt.figure()
a = f.add_subplot(111, axisbg='#777777')
a2 = f2.add_subplot(111, axisbg='#777777')
f.suptitle('# 1')
f2.suptitle('# 2')
xx = arange(0, 8192)
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)
Control = dict(t=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.)
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.)
FocusControl = dict( full_screen= False, aux_click='gg')
Data=dict(a=list(),b=list())
ROIs=list()
for j in range(8192):
Data['a'].insert(j, 0)
Data['b'].insert(j, 0)
Grafic=list()
M=list()
ROIs=list()
Interface = dict(frames=list(), buttons=list(), labels=list(), spinboxes=list(), entries=list(), labelframes=list())
Livetime = dict(ADC_Conversion=0 , Time=0. , LiveTime=0.)
###################################################################
# Ve quantas variaveis MC_ estão criadas no arquivo User_Config.py
# Define o modo de aquisição:1 ou 2 módulos (Implementar para n?)
try:
MCA
except NameError:
tkMessageBox.showinfo("Erro", "MCA não encontrado, nenhum módulo selecionado!")
sys.exit
else:
M.insert(0,Modulo('0'))
M[0].Nmr_serial= MCA
Grafic.insert(0,Graficos(M[0].Nmr_serial))
Grafic[0].f.suptitle('# 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
else:
M.insert(1,Modulo('1'))
M[1].Nmr_serial= MCA
Grafic.insert(1,Graficos(M[1].Nmr_serial))
Grafic[1].f.suptitle('# B')
time.sleep(1.5)
sys.setrecursionlimit(5000)
xx = arange(0, 8192)
##############################################################################
##############################################################################
......@@ -55,40 +94,7 @@ def change_conf(parametro, valor): # modifica um parametro da execução n957 (
arq.write(line)
arq.close()
##############################################################################
##############################################################################
# Subprocess variable
change_conf('BOARD_NUM',0)
child = pexpect.spawn('./N957Run') #inicia módulo, faz rodar o programa em C
time.sleep(0.5)
change_conf('BOARD_NUM',1)
child2 = pexpect.spawn('./N957Run') #inicia módulo, faz rodar o programa em C em paralelo
time.sleep(2)
sys.setrecursionlimit(5000)
def start():
global child , child2
child.send('s') #Manda o módulo iniciar (começa a comunicação com o Hardware)
child2.send('s')
if testeerro(child.readline().strip("\r\n")):
if not testeerro(child2.readline().strip("\r\n")):
return False
else:
return False
return True
def teste(): #usado para testar a comunicaç
child2.send('k')
print child2.readline().strip("\r\n")
child.send('k')
print child.readline().strip("\r\n")
##############################################################################
##############################################################################
# Main window
......@@ -168,12 +174,12 @@ class InterestRegion:
self.Area2 = 0
if int(self.xmax) == int(self.xmin):
self.Area = Data['a'][int(self.xmax)]
self.Area2 = Data['b'][int(self.xmax)]
self.Area = M[0].Data[int(self.xmax)]
self.Area2 = M[1].Data[int(self.xmax)]
else:
for n in range(self.xmin, self.xmax+1):
self.Area = self.Area + Data['a'][n]
self.Area2 = self.Area2 + Data['b'][n]
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)
else:
......@@ -217,61 +223,12 @@ def chage_focus(): #change the focus g1->g2->g1&g2->
##############################################################################
def set_fator(canais): # Define o fator para conversao do numero de canais
global Interface,child,child2
if int(canais) == 8192: # 8192 pontos
child.send('a')
child2.send('a')
Control['bmax'] = 8192
updateroi(8192)
elif int(canais) == 4096: # 4096 pontos
child.send('b')
child2.send('b')
Control['bmax'] = 4096
updateroi(4096)
elif int(canais) == 2048: # 2048 pontos
child.send('c')
child2.send('c')
updateroi(2048)
Control['bmax'] = 2048
elif int(canais) == 1024: # 1024 pontos
child.send('d')
child2.send('d')
Control['bmax'] = 1024
updateroi(1024)
elif int(canais) == 512: # 512 pontos
child.send('e')
child2.send('e')
Control['bmax'] = 512
updateroi(512)
elif int(canais) == 256: #256 pontos
child.send('f')
child2.send('f')
Control['bmax'] = 256
updateroi(256)
elif int(canais) == 128: #128 pontos
child.send('g')
child2.send('g')
Control['bmax'] = 128
updateroi(128)
elif int(canais) == 64:
child.send('h')
child2.send('h')
Control['bmax'] = 64
updateroi(64)
def settime(child, y): # pega o tempo vivo,tempo morto, nmr de conv.
Livetime['ADC_Conversion'] = int(child.readline().strip("\r\n"))
Livetime['Time'] = float(child.readline().strip("\r\n"))
Livetime['LiveTime'] = float(child.readline().strip("\r\n"))
if y == 0:
Interface['labels'][0].configure(text='ADC : %s' %str(Livetime['ADC_Conversion']))
Interface['labels'][1].configure(text='Total Time: %ss' %str(Livetime['Time']/1000))
Interface['labels'][2].configure(text='Live Time: %ss' %str(Livetime['LiveTime']/1000))
elif y == 1:
Interface['labels'][3].configure(text='ADC : %s' %str(Livetime['ADC_Conversion']))
Interface['labels'][4].configure(text='Total Time: %ss' %str(Livetime['Time']/1000))
Interface['labels'][5].configure(text='Live Time: %ss' %str(Livetime['LiveTime']/1000))
M[0].set_fator(canais)
M[1].set_fator(canais)
Control['bmax']= int(canais)
updateroi(int(canais))
def testeerro(Data): # mensagens de erros
if not Data == 'OK':
......@@ -322,45 +279,48 @@ def graphic2(Data, Data2): #trata as informações que foram salvas em graphic1
temp2.set_ydata(Data2)
if PlotLimControl['limupdtx'] or PlotLimControl['limupdty']:
if Control['Logaritmo']:
a.set_yscale('log')
Grafic[0].a.set_yscale('log')
else:
a.relim()
a.autoscale_view(scaley=PlotLimControl['limupdty'],scalex=PlotLimControl['limupdtx'])
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']:
a2.set_yscale('log')
Grafic[1].a.set_yscale('log')
else:
a2.relim()
a2.autoscale_view(scaley=PlotLimControl['limupdt_by'],scalex=PlotLimControl['limupdt_bx'])
Grafic[1].a.relim()
Grafic[1].a.autoscale_view(scaley=PlotLimControl['limupdt_by'],scalex=PlotLimControl['limupdt_bx'])
if PlotLimControl['limupdtx'] == True:
grid(a, int(Interface['spinboxes'][0].get()))
grid(Grafic[0].a, int(Interface['spinboxes'][0].get()))
if PlotLimControl['limupdt_bx'] == True:
grid(a2, int(Interface['spinboxes'][0].get()))
f.canvas.draw()
f2.canvas.draw()
grid(Grafic[1].a, int(Interface['spinboxes'][0].get()))
Grafic[0].f.canvas.draw()
Grafic[1].f.canvas.draw()
def graphic(): # Le os dados provenientes dos módulos
global child, Data, child2
testeerro(child.readline().strip("\r\n"))
Data['a'] = eval(child.readline().strip("\r\n"))
settime(child, 0)
testeerro(child2.readline().strip("\r\n"))
Data['b'] = eval(child2.readline().strip("\r\n"))
settime(child2, 1)
graphic2(Data['a'], Data['b'])
def dump(): # Sinal para programa coletor enviar os dados
global child , child2
child.send('i')
child2.send('i')
testeerro(M[0].Read_Data())
testeerro(M[1].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))
graphic2(M[0].Data, M[1].Data)
def realtimeplot(): # Funcao recursiva para plot em tempo real
global ROIs
if not Control['paused']:
dump()
M[0].dump()
M[1].dump()
try:
root.after(Control['t'], realtimeplot)
root.after(Control['Refresh'], realtimeplot)
graphic()
for n in range(len(Control['ROIctrl'])):
if Control['ROIctrl'][n] == 1:
......@@ -397,16 +357,12 @@ def hide_graphic(): #a= hide 1#, b=hide 2#, x= unhide
FocusControl['full_screen']=True
def reset(i, ii): # Zera o vetor de aquisicao
if i:
for k in range(int(Interface['spinboxes'][0].get())):
Data['a'][k] = 0
child.send('r')
if ii:
for a in range(int(Interface['spinboxes'][0].get())):
Data['b'][a] = 0
child2.send('r')
graphic2(Data['a'],Data['b'])
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)
def change_variable():
if Control['Logaritmo']:
......@@ -417,18 +373,19 @@ def change_variable():
def pause(): # Para/Continua a aquisicao de dados
global child,child2
if not Control['start']:
if start():
Control['paused']= not Control['paused']
Control['start']= not Control['start']
Interface['buttons'][1]['text'] = 'Pause'
Interface['labels'][6]['text'] = 'Acquiring'
realtimeplot()
if M[0].start():
if M[1].start():
Control['paused']= not Control['paused']
Control['start']= not Control['start']
Interface['buttons'][1]['text'] = 'Pause'
Interface['labels'][6]['text'] = 'Acquiring'
realtimeplot()
else:
Control['paused'] = not Control['paused']
child.send('p')
child2.send('p')
M[0].pause()
M[1].pause()
if Control['paused']:
Interface['buttons'][1]['text'] = 'Resume'
Interface['labels'][6]['text'] = 'Paused'
......@@ -444,13 +401,13 @@ def save(grafico): # Salva os dados no arquivo selecionado (grafico= g1(salva g1
if grafico == 'g1' or grafico =='g12':
fname = open(Control['filename']+'.'+str(Control['count'])+'_A', mode = 'w')
for n in range(int(Interface['spinboxes'][0].get())):
fname.write(str(n+1)+' '+str(Data['a'][n])+'\n')
fname.write(str(n+1)+' '+str(M[0].Data[n])+'\n')
fname.close()
Interface['labels'][5]['text'] = '%s.%d' %(Control['filename'], Control['count'])
if grafico == 'g2' or grafico =='g12':
fname = open(Control['filename']+'.'+str(Control['count'])+'_B', mode = 'w')
for n in range(int(Interface['spinboxes'][0].get())):
fname.write(str(n+1)+' '+str(Data['b'][n])+'\n')
fname.write(str(n+1)+' '+str(M[1].Data[n])+'\n')
fname.close()
#Interface['labels'][5]['text'] = '%s.%d' %(Control['filename'], Control['count'])
......@@ -458,7 +415,7 @@ def save(grafico): # Salva os dados no arquivo selecionado (grafico= g1(salva g1
def saveas(grafico): # Salva os dados no arquivo selecionado
global child, Data
temp = tkFileDialog.asksaveasfilename(title='Save as')
if temp != str():
......@@ -467,20 +424,20 @@ def saveas(grafico): # Salva os dados no arquivo selecionado
if grafico == 'g1' or grafico =='g12':
fname = open(Control['filename']+'.'+str(Control['count'])+'_A', mode = 'w')
for n in range(int(Interface['spinboxes'][0].get())):
fname.write(str(n+1)+' '+str(Data['a'][n])+'\n')
fname.write(str(n+1)+' '+str(M[0].Data[n])+'\n')
fname.close()
Interface['labels'][5]['text'] = '%s.%d' %(Control['filename'], Control['count'])
if grafico == 'g2' or grafico =='g12':
fname = open(Control['filename']+'.'+str(Control['count'])+'_B', mode = 'w')
for n in range(int(Interface['spinboxes'][0].get())):
fname.write(str(n+1)+' '+str(Data['b'][n])+'\n')
fname.write(str(n+1)+' '+str(M[1].Data[n])+'\n')
fname.close()
#Interface['labels'][5]['text'] = '%s.%d' %(Control['filename'], Control['count'])
Control['count'] = Control['count'] + 1
Interface['labels'][8].configure(text='%s.%d' %(Control['filename'], Control['count']))
def load(a): # Manda os dados carregados para leitura
global child
newfile = tkFileDialog.askopenfilename()
filefile = np.loadtxt(newfile)
tempfile = open('save.dat','w+')
......@@ -489,9 +446,9 @@ def load(a): # Manda os dados carregados para leitura
tempfile.write(str(int(h))+'\n')
tempfile.close()
if a == 1 or a == 3:
child.send('y')
M[0].load()
if a == 2 or a == 3:
child2.send('y')
M[1].load()
def refreshrate(): # Define a frequencia de atualizacao do grafico
rrwin = tk.Tk()
......@@ -504,12 +461,12 @@ def refreshrate(): # Define a frequencia de atualizacao do grafico
def setrr():
if rrent.get().isdigit():
if int(rrent.get()) > 99: # Valores muito baixos causam stack overflow
Control['t'] = int(rrent.get())
Interface['labels'][4].configure(text = ' Refresh Rate %dms' %Control['t'])
Control['Refresh'] = int(rrent.get())
Interface['labels'][4].configure(text = ' Refresh Rate %dms' %Control['Refresh'])
rrwin.destroy()
else:
tkMessageBox.showinfo("Warning", "This refresh rate is likely to reach maximum recursion depht!")
Control['t'] = 99
Control['Refresh'] = 99
else:
tkMessageBox.showinfo("Error", "Invalid value")
......@@ -555,12 +512,10 @@ def lldt(): #Definir o lower level detection trueshot
lldtlab.pack(side='left')
def setlldt():
global child
if lldtent.get().isdigit():
if int(lldtent.get()) < 100: # Percentual
child.send('j')
child.send(chr(int(lldtent.get())/10))
child.send(chr(int(lldtent.get())%10))
M[0].LLDT(lldtent.get())
lldtwin.destroy()
else:
tkMessageBox.showinfo("Error", "Invalid value; Percent based")
......@@ -612,14 +567,14 @@ tk.Checkbutton(Interface['labelframes'][2], text="Log Scale",takefocus=0,command
'''figbuffer = figure()
abuff = figbuffer.add_subplot(111)
M1, = abuff.plot(xx, xx*0, 'r.', lw=0.9)
M2, = abuff.plot(xx, xx*0, 'b', lw=0.9)
M[0], = abuff.plot(xx, xx*0, 'r.', lw=0.9)
M[1], = abuff.plot(xx, xx*0, 'b', lw=0.9)
def loadbuffer():
arquivo=tkFileDialog.askopenfilename()
amostra=np.loadtxt(arquivo)
M1.set_xdata(amostra[:,0])
M1.set_ydata(amostra[:,1])
M[0].set_xdata(amostra[:,0])
M[0].set_ydata(amostra[:,1])
abuff.relim()
abuff.autoscale_view()
figbuffer.canvas.draw()
......@@ -628,10 +583,10 @@ def loadbuffer():
def loadbuffer2():
amostra=np.loadtxt(Data)
M1.set_xdata(amostra[:,0])
M1.set_ydata(amostra[:,1])
M2.set_xdata(amostra[:,0])
M2.set_ydata(amostra[:,1])
M[0].set_xdata(amostra[:,0])
M[0].set_ydata(amostra[:,1])
M[1].set_xdata(amostra[:,0])
M[1].set_ydata(amostra[:,1])
abuff.relim()
abuff.autoscale_view()
......@@ -654,13 +609,13 @@ settings.add_command(label="Regions of Interest", command = lambda i=i: roiroi()