...
 
Commits (1)
......@@ -2,7 +2,9 @@
import Tkinter as tk
from PTE import *
from numpy import ones
from pylab import *
from numpy import zeros
import os
Edict = dict()
Ebuttons = list()
......@@ -28,7 +30,7 @@ def elem_callback(x, edict , ebutton, Labelmass, LabelZ, Labelname, Labelsymbol,
##############################################################################
# Element selection
def elem_select(i, button, Labelmass, LabelZ, Labelname, Labelsymbol, Entrymass, EntryZ, Entryname, Entrysymbol):
def elem_select(i, button, Labelmass, LabelZ, Labelname, Labelsymbol, LabelLS, Entrymass, EntryZ, Entryname, Entrysymbol,EntryLS):
global Econtrol, Edict
button[Econtrol]['relief']='raised'
......@@ -39,34 +41,33 @@ def elem_select(i, button, Labelmass, LabelZ, Labelname, Labelsymbol, Entrymass,
LabelZ.configure(text = 'Z - %f' %Edict[i]['Z'])
Labelname.configure(text = '%s' %Edict[i]['name'])
Labelsymbol.configure(text = 'Symbol - %s' %Edict[i]['symbol'])
LabelLS.configure(text = 'Line Shape α - %f' %Edict[i]['LineShape'])
Entrymass.delete (0, len(Entrymass.get()))
Entryname.delete (0, len(Entryname.get()))
EntryZ.delete (0, len(EntryZ.get()))
Entrysymbol.delete (0, len(Entrysymbol.get()))
EntryLS.delete (0, len(EntryLS.get()))
Entrymass.insert(0, Edict[int(Econtrol)]['mass'])
Entryname.insert(0, Edict[int(Econtrol)]['name'])
EntryZ.insert(0, Edict[int(Econtrol)]['Z'])
EntryZ.insert(0, int(Edict[int(Econtrol)]['Z']))
Entrysymbol.insert(0, Edict[int(Econtrol)]['symbol'])
#if Edict[i]['name'] == 'New':
# butPTE.invoke()
EntryLS.insert(0, Edict[int(Econtrol)]['LineShape'])
##############################################################################
# Init
def ewin_build(window, xmax, xstep):
##############################################################################
# Element addition
def create():
global i, Edict, Ebuttons
Edict[i] = dict(name = "New", symbol = "Hf", mass = 178.00, Z = 72, dist = ones(int(xmax/xstep)), control = 0, LineShape = 200.)
Ebuttons.insert(i, tk.Button(Eframe, text=i, width=1, height=1, command = lambda i=i : elem_select(i,Ebuttons,Labelmass,LabelZ,Labelname,Labelsymbol,Entrymass,EntryZ,Entryname,Entrysymbol)))
Ebuttons[i].pack(side='left')
Edict[i] = dict(name = "Element X", symbol = "Hf", mass = 178.00, Z = 72, dist = zeros(int(xmax/xstep)), control = 0, LineShape = 200.)
Ebuttons.insert(i, tk.Button(Eframe, text=i, width=1, height=1, command = lambda i=i : elem_select(i,Ebuttons,Labelmass,LabelZ,Labelname,Labelsymbol,LabelLS,Entrymass,EntryZ,Entryname,Entrysymbol,EntryLS)))
Ebuttons[i].grid(column = ((len(Ebuttons)-1)%15), row = int(math.floor((len(Ebuttons)-1)/15)))
i=i+1
##############################################################################
......@@ -86,16 +87,19 @@ def ewin_build(window, xmax, xstep):
##############################################################################
# Element Frames
Labelprop = tk.LabelFrame(window, text = 'Properties', relief='raised', bd=2)
Labelprop.pack(side = 'top')
Label1 = tk.LabelFrame(window, text = 'Elements', relief='raised', bd=2)
Label1.pack()
Label1.pack(side = 'top')
Eframe = tk.Canvas(Label1)
Eframe.pack(fill='both',expand=0)
##############################################################################
# Init
create()
##############################################################################
# Properties
......@@ -109,14 +113,11 @@ def ewin_build(window, xmax, xstep):
Labelname.configure(text = '%s' %Edict[i]['name'])
Edict[i]['symbol'] = str(Entrysymbol.get())
Labelsymbol.configure(text = 'Symbol - %s' %Edict[i]['symbol'])
#Edict[i]['LineShape'] = float(EntryLS.get())
#LabelLS.configure(text = 'Line Shape α - %f' %Edict[i]['LineShape'])
Edict[i]['LineShape'] = float(EntryLS.get())
LabelLS.configure(text = 'Line Shape α - %f' %Edict[i]['LineShape'])
Edict[i]['dist'] = np.loadtxt(Edict[i]['symbol']+".prof")
print Edict[i]
Labelprop = tk.LabelFrame(window, text = 'Properties', relief='raised', bd=2)
#Labelprop.pack()
Labelprop.place(anchor='w', y=100, x=5)
LpFrame1 = tk.Frame(Labelprop)
LpFrame1.pack(side='left')
LpFrame2 = tk.Frame(Labelprop)
......@@ -134,32 +135,27 @@ def ewin_build(window, xmax, xstep):
EPframee2 = tk.Frame(LpFrame2)
EPframee2.pack(side='right')
Labelname = tk.Label(EPframel, width=20, pady=2, text='%s' %Edict[int(Econtrol)]['name'])
Labelmass = tk.Label(EPframel, width=20, pady=2, text='Mass - %f' %Edict[int(Econtrol)]['mass'])
LabelZ = tk.Label(EPframel, width=20, pady=2, text='Z - %f' %Edict[int(Econtrol)]['Z'])
Labelsymbol = tk.Label(EPframel, width=20, pady=2, text= 'Symbol - %s' %Edict[int(Econtrol)]['symbol'])
#LabelLS = tk.Label(EPframel, width=30, pady=2, text='Line Shape α - %f' %Edict[int(Econtrol)]['LineShape'])
Labelname = tk.Label(EPframel, width=26, pady=2, text='%s' %Edict[int(Econtrol)]['name'])
Labelmass = tk.Label(EPframel, width=26, pady=2, text='Mass - %f' %Edict[int(Econtrol)]['mass'])
LabelZ = tk.Label(EPframel, width=26, pady=2, text='Z - %f' %Edict[int(Econtrol)]['Z'])
Labelsymbol = tk.Label(EPframel, width=26, pady=2, text= 'Symbol - %s' %Edict[int(Econtrol)]['symbol'])
LabelLS = tk.Label(EPframel, width=26, pady=2, text='Line Shape α - %f' %Edict[int(Econtrol)]['LineShape'])
Labelname.pack()
Labelmass.pack()
LabelZ.pack()
Labelsymbol.pack()
#LabelLS.pack()
LabelLS.pack()
Entryname = tk.Entry(EPframee, width=15)
Entrymass = tk.Entry(EPframee, width=15)
EntryZ = tk.Entry(EPframee, width=15)
Entrysymbol = tk.Entry(EPframee, width=15)
#EntryLS = tk.Entry(EPframee, width=22)
Entryname = tk.Entry(EPframee, width=18)
Entrymass = tk.Entry(EPframee, width=18)
EntryZ = tk.Entry(EPframee, width=18)
Entrysymbol = tk.Entry(EPframee, width=18)
EntryLS = tk.Entry(EPframee, width=18)
Entryname.pack()
Entrymass.pack()
EntryZ.pack()
Entrysymbol.pack()
#EntryLS.pack()
BUpdate = tk.Button(EPframee2, text ='Update properties', command=lambda i=int(Econtrol) :update(i), width=15)
BUpdate.pack()#side='right')
BUpdateD = tk.Button(EPframee2, text ='Update Distribution', command=lambda i=int(Econtrol) :update(i), width=15)
BUpdateD.pack()#side='left')
EntryLS.pack()
but = tk.Button(EPframel2, command=create, text='Add element', bd=1, height=1,width=15)
but.pack()#side='left')
......@@ -170,55 +166,15 @@ def ewin_build(window, xmax, xstep):
butPTE = tk.Button(EPframel2, text='Show PTE', bd=1, width=15, command=lambda i=i :elem_callback(Econtrol,Edict,Ebuttons,Labelmass,LabelZ,Labelname,Labelsymbol,Entrymass,EntryZ,Entryname,Entrysymbol))
butPTE.pack()#side='left')
##############################################################################
# Init
Entrymass.insert(0, Edict[int(Econtrol)]['mass'])
Entryname.insert(0, Edict[int(Econtrol)]['name'])
EntryZ.insert(0, Edict[int(Econtrol)]['Z'])
Entrysymbol.insert(0, Edict[int(Econtrol)]['symbol'])
#EntryLS.insert(0, Edict[int(Econtrol)]['LineShape'])
BUpdate = tk.Button(EPframel2, text ='Update properties', command=lambda i=int(Econtrol) :update(i), width=15)
BUpdate.pack()#side='right')
##############################################################################
# Canvas callback
def point(event):
Distcanvas.create_oval(event.x, event.y, event.x+1, event.y+1, fill="black")
points.append(event.x)
points.append(event.y)
return points
def canxy(event):
print event.x, event.y
def graph(event):
global theline
Distcanvas.create_line(points, tags="theline")
def toggle(event):
global spline
if spline == 0:
Distcanvas.itemconfigure(tag1, smooth=1)
spline = 1
elif spline == 1:
Distcanvas.itemconfigure(tag1, smooth=0)
spline = 0
print event.x, event.y
return spline
BUpdateD = tk.Button(EPframel2, text ='Distribution', command =lambda i=int(Econtrol) : os.system("python profiler.py %s &" %Edict[int(Econtrol)]['symbol']), width=15)
BUpdateD.pack()#side='left')
##############################################################################
# Drawing Canvas
Label2 = tk.LabelFrame(window, text = 'Distribution', bd=1)
#Label2.pack()
Label2.place(anchor='w', y=320, x=5)
Distcanvas = tk.Canvas(Label2, bg="white", width=800, height= 300)
#Distcanvas.configure(cursor="crosshair")
Distcanvas.grid_columnconfigure(999, weight = 1)
Distcanvas.grid_rowconfigure(999, weight = 1)
Distcanvas.pack()
Distcanvas.bind("<Button-1>", point)
Distcanvas.bind("<Button-3>", graph)
Distcanvas.bind("<Button-2>", toggle)
# Init
Ebuttons[0].invoke()
##############################################################################
......@@ -7,7 +7,7 @@ import sys
##############################################################################
# Initial parameters
param = dict(dedx=192. ,Theta_out=70., dW2dx=20740., E0= 100000., Theta_in=0.) #, FWHM0=180.)
param = dict(dedx=192. ,Theta_out=70., dW2dx=20740., E0= 100000., Theta_in=0., FWHM0=180.)
ionb = dict(Z=1, mass=1.0079)
##############################################################################
......@@ -21,7 +21,7 @@ def init_calc():
param['Theta_out'] = float(EntryT_out.get())
param['Theta_in'] = float(EntryT_in.get())
param['E0'] = float(EntryE0.get())
#param['FWHM0'] = float(EntryFWHM0.get())
param['FWHM0'] = float(EntryFWHM0.get())
ionb['mass'] = float(Entryionmass.get())
ionb['Z'] = float(EntryionZ.get())
......@@ -31,29 +31,27 @@ def init_calc():
# Main window
root = tk.Tk()
root.minsize(375,270)
root.minsize(730,460)
root.title('Open Flatus')
root.geometry('375x270+200+400')
##############################################################################
# Elements window
ewin = tk.Tk()
ewin.minsize(810,550)
ewin.title('Elements')
ewin.geometry('600x400+600+400')
##############################################################################
# Frames
MasterFrame1 = tk.Frame(root)
MasterFrame1.pack(side='left')
MasterFrame2 = tk.Frame(root)
MasterFrame2.pack(side='top')
Label2 = tk.LabelFrame(MasterFrame1, text = 'Parameters', relief='raised', bd=2)
Label2.pack(side='top')
Label3 = tk.LabelFrame(MasterFrame1, text = 'Ion parameters', relief='raised', bd=2)
Label3.pack(side='left')
Label4 = tk.LabelFrame(root, text = 'Energy loss model', relief='raised', bd=2)
Label4.pack(side='right')
Label3.pack(side='top')
Label4 = tk.LabelFrame(MasterFrame1, text = 'Energy loss model', relief='raised', bd=2)
Label4.pack(side='top')
# Elements frame
Label1 = tk.Frame(MasterFrame2)
Label1.pack(side='top')
Pframel = tk.Frame(Label2)
Pframel.pack(side='left')
......@@ -72,7 +70,7 @@ Labeldedx = tk.Label(Pframel, width=9, text='dƐ/dx', pady=2)
LabeldW2dx = tk.Label(Pframel, width=9, text='dω²/dx', pady=2)
LabelT_out = tk.Label(Pframel, width=9, text='θ out', pady=2)
LabelT_in = tk.Label(Pframel, width=9, text='θ in', pady=2)
#LabelFWHM0 = tk.Label(Pframel, width=9, text='FWHM0')
LabelFWHM0 = tk.Label(Pframel, width=9, text='FWHM0')
LabelEmin = tk.Label(Pframel, width=9, text='Emin', pady=2)
LabelEmax = tk.Label(Pframel, width=9, text='Emax', pady=2)
LabelEstep = tk.Label(Pframel, width=9, text='Estep', pady=2)
......@@ -81,7 +79,7 @@ Labeldedx.pack()
LabeldW2dx.pack()
LabelT_out.pack()
LabelT_in.pack()
#LabelFWHM0.pack()
LabelFWHM0.pack()
LabelEmin.pack()
LabelEmax.pack()
LabelEstep.pack()
......@@ -92,7 +90,7 @@ Entrydedx = tk.Entry(Pframee, width=11)
EntrydW2dx = tk.Entry(Pframee, width=11)
EntryT_out = tk.Entry(Pframee, width=11)
EntryT_in = tk.Entry(Pframee, width=11)
#EntryFWHM0 = tk.Entry(Pframee, width=11)
EntryFWHM0 = tk.Entry(Pframee, width=11)
EntryEmin = tk.Entry(Pframee, width=11)
EntryEmax = tk.Entry(Pframee, width=11)
EntryEstep = tk.Entry(Pframee, width=11)
......@@ -101,7 +99,7 @@ Entrydedx.pack()
EntrydW2dx.pack()
EntryT_out.pack()
EntryT_in.pack()
#EntryFWHM0.pack()
EntryFWHM0.pack()
EntryEmin.pack()
EntryEmax.pack()
EntryEstep.pack()
......@@ -127,7 +125,7 @@ EntrydW2dx.insert(0,param['dW2dx'])
EntryT_out.insert(0,param['Theta_out'])
EntryT_in.insert(0,param['Theta_in'])
EntryE0.insert(0,param['E0'])
#EntryFWHM0.insert(0,param['FWHM0'])
EntryFWHM0.insert(0,param['FWHM0'])
EntryEmin.insert(0,70000)
EntryEmax.insert(0,100000)
EntryEstep.insert(0,20)
......@@ -155,22 +153,22 @@ C1.select()
##############################################################################
CalcButton = tk.Button(Label4, text = 'Calculate', command = init_calc, bd=4, width=20, height=4)
CalcButton = tk.Button(Label4, text = 'Calculate', command = init_calc, bd=4, width=17, height=2)
CalcButton.pack()
ExitButton = tk.Button(Label4, text = 'Exit', command = sys.exit, bd=4, width=20, height=2)
ExitButton = tk.Button(Label4, text = 'Exit', command = sys.exit, bd=4, width=17, height=2)
ExitButton.pack(side='bottom')
##############################################################################
# Elements callback
ewin_build(ewin, 15, float(EntryDstep.get()))
ewin_build(Label1, 15, float(EntryDstep.get()))
##############################################################################
spectro(param, 'gaussiana', ionb, float(EntryEmin.get()), float(EntryEmax.get()), float(EntryEstep.get()), float(EntryDstep.get()), int(LSvar.get()) )
root.mainloop()
ewin.mainloop()
Label1.mainloop()
##############################################################################
from pylab import *
#####################################################################################################
# Funcoes que corrigem erros de arredondamento
def fix1(y, x):
for k in arange(1, (len(y)-1)):
if y[k] == 0:
if y[k-1] and y[k+1] != 0:
y[k] = y[k-1]
def fix2(y, x):
for k in arange(1, (len(y)-1)):
if y[k] == 0:
if y[k-1] and y[k+1] != 0:
if y[k-1] == y[k+1]:
y[k] = y[k-1]
else:
y[k] = (y[k+1]+y[k-1])/2
#####################################################################################################
def montaperfil( xy , step, modo):
u = 0.
yu = 0.
profundidade = arange(0, max(xy[:,0]), step)
concent = profundidade*0
if modo == 'step':
for i in xy:
for j in arange (u, i[0], step):
if j>max(xy[:,0])/2 and j<=len(xy) :
concent[math.ceil(j/step)] = i[1]
else :
concent[math.floor(j/step)] = i[1]
u = i[0]
fix1(concent, profundidade)
if modo == 'reta':
for i in xy:
for j in arange (u, round(i[0],2), step):
concent[round(j/step)] = yu + (j-u)*(i[1] - yu)/(i[0] - u)
u = round(i[0],2)
yu = i[1]
fix2(concent, profundidade)
return concent
#-*- coding: utf-8 -*-
# Comparação do espectros de espalhamento baseados na função modificada de Bessel do primeiro tipo de ordem 1
# com o modelo Gaussiano.
# Incluída convolução com forma de linha originária da colisão frontal
#
# Referência: R. P. Pezzi, et al. Applied Physics Letters, 92 164102 (2008)
from pylab import *
from scipy.special import i1
PI=math.pi
######## Definindo a Seção de Choque #######
def CSRf(Z1, Z2, Ein, M1, M2, Theta):
if M1 < M2:
return ((Z1*Z2*4.8e-20*1e8)/(4*Ein))**2 * sin(Theta)**-4 * (sqrt(1-((M1/M2)*sin(Theta))**2)+cos(Theta))**2 / sqrt(1-((M1/M2)*sin(Theta))**2)
else:
return 0
############################################
######## Função de convolução com forma de linha #######
def convoluiF0(espectro, alpha,passoE):
areaantes=espectro.sum()
temp=espectro[::-1]
eixo=arange(0,12.*alpha,passoE)
lineshape=alpha*exp(-eixo/alpha)
# ls_plt=plt.plot(lineshape/lineshape.sum(),lw=2)
# sig_plt=plt.plot(temp/temp.sum(),lw=2)
temp = convolve(temp/temp.sum(), lineshape/lineshape.sum())
temp.resize(len(espectro))
# result_plt=plt.plot(temp/temp.sum(),'o')
# legend([ls_plt,sig_plt,result_plt],["Lineshape","Sinal","Resultado"])
return temp[::-1]*areaantes
#########################################################
#### Parâmetros iniciais ####
# Feixe:
E0=100000 #eV
mi=1.
Zi=1.
# Alvo:
dedx=192. # eV/nm
dw2dx=20740. # eV^2/nm
Theta_in=0.
Theta_out=70.
Theta_s = PI - (Theta_in + Theta_out)*PI/180
espessura=2
# Cálculo:
deltaE=20000
passoE=20
passox=0.02
e = arange(E0-deltaE, E0, passoE)
totalbessel=e*0
totalbessel_ls=e*0
totalgaussiana=e*0
## TODO: - Otimizar os cálculos de cada componente: evitar cálculos (de zeros) em energias desnecessários
## - Definir o intervalo de plotagem do espectro independente do deltaE
#############################
## Define a composição da amostra ##
elementos=[[72.,178.49,217.],[14.,28.,121.],[8.,16.,102]] # Hf, Si e O
#elementos=[[72.,178.49,217.]]#,[14.,28.,121.],[8.,16.,102]] # Hf, Si e O
# Esta lista deve incluir a distribuição
# em profundidade do elemento
####################################
## Calcula o espectro de cada elemento da amostra
for componente in elementos:
mt=componente[1];
Zt=componente[0];
alpha_lineshape=componente[2]
k = ((sqrt (mt**2+mi**2*(sin(Theta_s)**2)) + mi*cos(Theta_s) ) / (mi+mt) )**2
dedxef=dedx*(k/cos(Theta_in*PI/180.) + 1/cos(Theta_out*PI/180.))
dw2dxef=dw2dx*(k**2./cos(Theta_in*PI/180.)+1./cos(Theta_out*PI/180.))
sinalbessel=e*0
sinalgaussiana=e*0
# Calcula a contribuição de cada camada
for x in arange(passox,espessura,passox):
# Bessel:
# Ainda falta incluir a delta de Dirac na origem e a convolução com a resolução experimental
# Existe um valor máximo em energia no qual a função de Bessel pode ser computada em função
# da precisão numérica. Uma possível solução pode ser trabalhar em outras unidades que não
# resultem em argumentos tão grandes para a função exponencial.
# Também temos um problema com a primeira camada, que tem profundidade zero.
# Perceba que os cálculos de Bessel correspondentes às camadas mais fundas estão truncados
# para uma perda de energia maior que 25 keV. (Observado com Theta_in=70, para x > 30)
# Este truncamento resulta de valores NaN (Not a Number) que aparecem no vetor. Foi incluida uma
# operação para remover os NaN do vetor de Bessel
#
# CSRf(Z1, Z2, Ein, M1, M2, Theta):
secchoque=CSRf(Zi, Zt,k*E0-dedxef*x,mi,mt, Theta_s)*passox
# É multiplicada pelo passo para manter a escala do gráfico
# independente do mesmo.
alpha=dedxef*(2./dw2dxef)
m=alpha*dedxef
lbd=m*x*alpha
besselcamada = lbd*exp(-m*x-alpha*(k*E0-e))*i1(2.*sqrt(lbd*(k*E0-e)))/(sqrt(lbd*(k*E0-e)))
### Removendo Not A Number do vetor ###
ondeestaoNaN = isnan(besselcamada);
besselcamada[ondeestaoNaN] = 0
### Incluir o sinal correspondente à ausência de colisões (Delta de Dirac em k*E0)
# Pode ser feito adicionando uma gaussiana de largura muito pequeno em k*E0 para circundar o
# fato de kE0 poder não cair exatamente em uma posição discreta do vetor
sinalbessel=besselcamada*secchoque+sinalbessel
## Plotar o sinal da camada
#plt.plot(e,besselcamada)
# Gaussiana:
Em=k*E0-x*dedxef
sigma=x*dw2dxef
gaussianacamada = exp((-(e-Em)**2)/(2.*sigma))/sqrt(2.*PI*sigma)
sinalgaussiana=gaussianacamada*secchoque+sinalgaussiana
#plt.plot(e,gaussianacamada)
# plt.plot(e, sinalbessel)
# plt.plot(e, sinalgaussiana)
### Convoluir com forma de linha da colisão frontal:
sinalbessel_ls=convoluiF0(sinalbessel,alpha_lineshape,passoE)
totalbessel=sinalbessel+totalbessel
totalbessel_ls=sinalbessel_ls+totalbessel_ls
totalgaussiana=sinalgaussiana+totalgaussiana
#####################################
# Mostra o Gráfico
bes=plt.plot(e,totalbessel,lw=2,color="red")
besls=plt.plot(e,totalbessel_ls,lw=2,color="blue")
gaus=plt.plot(e,totalgaussiana,lw=2,color="green")
#plt.plot(e,totalbessel*10,lw=2, color="blue")
#plt.plot(e,totalgaussiana*10,lw=2, color="green")
plt.legend([bes,besls,gaus],["Bessel","Bessel+lineshape","Gaussiana"],loc= "upper left", shadow=True)
plt.xlabel("Energia dos Ions (eV)")
plt.ylabel("Rendimento (contagens)")
#print totalbessel
show()
##################
# draggable rectangle with the animation blit techniques; see
# http://www.scipy.org/Cookbook/Matplotlib/Animations
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
from concentracao import *
import sys
lista = list()
listay = list()
listax = list()
drs = []
fig = plt.figure()
ax = fig.add_subplot(111)
filename2 = sys.argv[1]+".prof" #raw_input()
filename = sys.argv[1]+".dat" #raw_input()
print "nome dos arquivos "+filename+" e "+ filename2
fig.canvas.set_window_title(filename)
dxstep = 0.01
profundidademax = 20.
xx = arange(0,20, dxstep) # we'll create an x-axis from 0 to 2 pi
temp, = plot(xx,xx*0) # this is our initial plot, and does nothing
modo = 'step'
#modo = 'reta'
#######################################################################################################
# Add square
def add_square(x, y):
global listay, drs, ax
rect = ax.bar(x, 0.02, width=0.3)
for rec in rect:
dr = DraggableRectangle(rec)
dr.connect()
drs.append(dr)
rec.set_y(y)#-0.01)
listay.append(dr.rect.xy[1])
listax.append(dr.rect.xy[0])
dr.updateplot()
ylim([0,1])
xlim([0,profundidademax])
def add_immovable_square(x, y):
global listay, drs, ax
rect = ax.bar(x, 0.02, width=0.3)
for rec in rect:
dr = DraggableRectangle(rec)
drs.append(dr)
rec.set_y(y)#-0.01)
listay.append(dr.rect.xy[1])
listax.append(dr.rect.xy[0])
ylim([0,1])
xlim([0,profundidademax])
def remove_square():
global listay, drs
listay.pop()
drs.pop()
print listay, drs
def clear_figure():
global fig
fig.clf()
#######################################################################################################
class voidfunctions:
def __init__(self, rect):
self.rect = rect
def connect(self):
'connect to all the events we need'
self.cida = self.rect.figure.canvas.mpl_connect(
'key_release_event', self.on_a)
self.cidr = self.rect.figure.canvas.mpl_connect(
'key_release_event', self.on_r)
self.cidc = self.rect.figure.canvas.mpl_connect(
'key_release_event', self.on_c)
def on_a(self, event):
if event.key=='a':
if not event.inaxes: return
add_square(float(event.xdata), float(event.ydata))
# NAO FUNCIONA
def on_r(self, event):
if event.key=='r':
if not event.inaxes: return
remove_square()
def on_c(self, event):
if event.key=='c':
if not event.inaxes: return
clear_figure()
def disconnect(self):
'disconnect all the stored connection ids'
self.rect.figure.canvas.mpl_disconnect(self.cida)
self.rect.figure.canvas.mpl_disconnect(self.cidr)
self.rect.figure.canvas.mpl_disconnect(self.cidc)
#######################################################################################################
class DraggableRectangle:
lock = None # only one can be animated at a time
......@@ -13,6 +105,34 @@ class DraggableRectangle:
self.press = None
self.background = None
def updateplot(self):
global listax, listay, temp, drs, dxstep, modo
xytemp = list(drs)
for i in range(len(drs)):
xytemp[i] = drs[i].rect.xy
xytemp.sort(key=lambda s: s[0])
for i in range(len(listay)):
(listax[i], listay[i]) = xytemp[i]
data = open(filename , 'w')
for i in range(len(listay)):
print>>data, listax[i], listay[i]
data.close()
xydata = np.loadtxt(filename)
xy = montaperfil( xydata, dxstep, modo)
data2 = open(filename2 , 'w')
for i in range(len(xy)):
print>>data2, xy[i]
data2.close()
temp.set_ydata(montaperfil( xydata, dxstep, modo)) # update the plot data
draw() # redraw the canvas
ylim([0,1])
xlim([0,profundidademax])
def connect(self):
'connect to all the events we need'
self.cidpress = self.rect.figure.canvas.mpl_connect(
......@@ -24,10 +144,11 @@ class DraggableRectangle:
def on_press(self, event):
'on button press we will see if the mouse is over us and store some data'
if event.inaxes != self.rect.axes: return
if event.inaxes != self.rect.axes: return
if DraggableRectangle.lock is not None: return
contains, attrd = self.rect.contains(event)
if not contains: return
#print 'event contains', self.rect.xy
x0, y0 = self.rect.xy
self.press = x0, y0, event.xdata, event.ydata
......@@ -42,14 +163,12 @@ class DraggableRectangle:
# now redraw just the rectangle
axes.draw_artist(self.rect)
# and blit just the redrawn area
canvas.blit(axes.bbox)
def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if DraggableRectangle.lock is not self:
return
if DraggableRectangle.lock is not self: return
if event.inaxes != self.rect.axes: return
x0, y0, xpress, ypress = self.press
dx = event.xdata - xpress
......@@ -64,14 +183,14 @@ class DraggableRectangle:
# redraw just the current rectangle
axes.draw_artist(self.rect)
# blit just the redrawn area
canvas.blit(axes.bbox)
#self.updateplot()
def on_release(self, event):
'on release we reset the press data'
if DraggableRectangle.lock is not self:
return
if DraggableRectangle.lock is not self: return
self.press = None
DraggableRectangle.lock = None
......@@ -82,11 +201,7 @@ class DraggableRectangle:
# redraw the full figure
self.rect.figure.canvas.draw()
for i in range(10):
lista[i] = drs[i].rect.xy
print lista
self.updateplot()
def disconnect(self):
'disconnect all the stored connection ids'
......@@ -94,19 +209,26 @@ class DraggableRectangle:
self.rect.figure.canvas.mpl_disconnect(self.cidrelease)
self.rect.figure.canvas.mpl_disconnect(self.cidmotion)
fig = plt.figure()
ax = fig.add_subplot(111)
rects = ax.bar(range(10), (1 + 0.01*np.random.rand(10)))
drs = []
for rect in rects:
dr = DraggableRectangle(rect)
dr.connect()
drs.append(dr)
lista.append(dr.rect.xy)
#######################################################################################################
voidrect = ax.bar(0, 0, width=0)
for void in voidrect:
vf = voidfunctions(void)
vf.connect()
add_immovable_square(0,0)
add_immovable_square(20,0)
ylim([0,50])
xlim([0,50])
try:
f = np.loadtxt(filename)
except IOError:
pass
else:
for initial in range( len(f) ):
add_square(f[initial][0],f[initial][1])
#######################################################################################################
plt.show()