mouse events, get data and disconnect

Hello,
I don’t know what I’m doing wrong, but it don’t work for me.
I have to open different sets of data, plot it, select an initial point, make some calculations and save all the data.
Each plot have a diferente initial point, so I thought of do this with a for sentences, opening each plot, doing all and so on.

But I open the first one, and then it plots the second one, but don’t let me select the original point, it catches the previos one. And the same for the rest.
And I don’t know why it doesn’t work.

Here you have all the program:

···

#!/usr/bin/python

-- encoding: latin1 --

#Importamos los módulos necesarios:

import Numeric as num
import pylab
import random

import array
import sys
from matplotlib.widgets import SpanSelector
from matplotlib.widgets import Cursor

#Leemos el fichero que contiene el valor de la energia y la suma de los espines:

def readfiles(filename):

"""
Lee el fichero donde estan los datos. La primera fila del fichero nos da la temperatura y el numero de puntos.
Las dos columnas tienen la energia y la suma de los spines.
"""


fin = open (filename, 'r')
fields = fin.readline()
fin.close()
labels = fields[1:].split()
t = eval(labels[1])
n = eval(labels[6])

datos = pylab.load(filename,comments='#')

energia =datos[:,0]
sumspines =datos[:,1]

return t, n, energia, sumspines

def filelist(filename):
fin = open(filename,‘r’)
files =
for line in fin:

            files.append(line[:-1]),
    return files

def writefile(filename,start,cv,mag,t):
“”"
Escribimos en un fichero todos los datos de punto de corte, calores especificos,

    magnetizacion y temperatura
    """
    fout = open(filename,'w')
    fout.write ("#punto de corte    cv    magnetizacion    temperatura")
    for i in range (len(start)):

            fout.write("%f \t %f \t %f \t %f \n"  %  (start[i],cv[i], mag[i], t[i]))
    fout.close()

def cv(energia,T,n,g,start):
“”"
Calculamos el calor específico segun la formula:

Cv= k*B**2/(nx*ny)*(<H²> - <H>²
donde:
<H>² = (sumatorio H/n) **2
<H²> = (sumatorio H) **2 /n
"""
hp = sum(energia[start:])/(n*g*g*2.)
energia2 = num.asarray(energia)
hp2 = sum(energia2[start:]**2)/n*(g*g*2)**2

print 'Algunos valores de la energia: ',energia[start:start+10]

return (hp2-hp**2)/(g*g*T**2)

def mag(sumspines,n,g,start):

"""
Calculamos la magnetizacion, usando la formula:
<M> = (sumatorio S) /n
"""

print 'Algunos valores de sumspines: ', sumspines[start:start+10]

print 'la n es: ', n

return sum(sumspines[start:]) /(n*g*g)

def grid(zn):
im1 = pylab.imshow(zn, cmap=pylab.cm.gray, interpolation=‘nearest’)
pylab.show()

def plotear(energia):
fig=pylab.figure(figsize=(8,6))
ax = fig.add_subplot(111)
x=pylab.arange(0,len(energia),1)
ax.plot(x,energia,linewidth=2)
pylab.grid(True)

cursor = Cursor(ax, useblit=False, color='red', linewidth=2)

cursor.horizOn = False

def click(event):
global x
#x,y = event.x,event.y
if event.button == 1:
if event.inaxes:

print ‘coordenada x’, event.xdata

        x = event.xdata
        pylab.disconnect(cid)
        pylab.close()
return x

def main0 ():
global cid

filename = raw_input("Introduce el fichero de datos: ")

t= temperatura

n= numero de pasos

energia = valores de la energia, sin normalizar (hay que multiplicar por

1/( 2nxny)

sumspines= valor de la suma de los espines para cada energia

g = grid (nx =ny)

t, n, energia, sumspines =  readfiles(filename)
g = float(filename[(filename.find('-')+1):])

plotear(energia)
cid = pylab.connect('button_press_event', click)
pylab.show()
x1 = int(x)
print 'Coordenada x: ',x1

print 'El calor especifico es: ',cv(energia,t, n,g,x1)
print 'La magnetizacion es: ', mag(sumspines,n,g,x1)

def main1():
global x, cid
filename = raw_input("Introduce el fichero con la lista: ")
files = filelist(filename)
start=
cvall=
magall=

    ts=[]
    for i in range(len(files)):
            t,n,energia,sumspines= readfiles(files[i])
            g = float(files[1][(files[1].find('-')+1):])
            plotear(energia)

            cid = pylab.connect('button_press_event', click)
            pylab.show()
            x1 = int(x)
            start.append(x1)
            cv1=cv(energia,t, n,g,start[i])

            mag1= mag(sumspines,n,g,start[i])

            cvall.append(cv1)
            magall.append(mag1)
            ts.append(t)
            print 'Coordenada x: ',x1

            print 'El calor especifico es: ',cv1
            print 'La magnetizacion es: ', mag1
           
    filename2='resultados_globales.%s' % (g)
    writefile(filename2,start,cvall,magall,ts)

def main2():
print “todavia no esta hecho”

if name == “main”:

print "Selecciona una de las siguientes opciones: \n "
print "Un solo fichero de datos (0)"

print "Lista de ficheros de datos (1)"
print "Lista de ficheros de datos y valores de corte (2)"

option = input()

if option ==0:
        main0()
if option == 1:

        main1()
if option ==2:
        main2()

2007/6/27, Matthias Michler <
MatthiasMichler@…361…>:

Hello darkside,

I’m a little confused that you are sending the email directly to me …

and I’m not sure I really understand your problem, but I set up an example
that hopefully satify your needs and shows that it works in principle :


import pylab

def click(event):
global x # allow to change global variable
if event.button == 1:
if event.inaxes:
x = event.xdata # change global variable

        print " x - intern = ", x
        pylab.disconnect(cid)
        pylab.close()

xlist = # list for x values
global x
for i in xrange(8):
pylab.figure
()
pylab.subplot(111)
pylab.draw()
cid = pylab.connect(‘button_press_event’, click)
pylab.show()
print " x - extern = ", x
xlist.append(x)

pylab.figure()

pylab.subplot(111)
pylab.plot(xlist, ‘b+’, ms=8, mew=4) # plot ensemble of x values
pylab.show()


If this example is not sufficient for you, please set up a little example of
your problem, which can be executed from here, too.
This you may send to mpl mailing-list.

I have already tried this example and it doesn’t work for me. It catches the same x for all the plots.

Thank you for you kind help.

P.D. I send the previous message to you because I clicked the reply button and I didn’t see that it was only you, sorry.

Hello,
I don’t know what I’m doing wrong, but it don’t work for me.
I have to open different sets of data, plot it, select an initial point, make some calculations and save all the data.

Each plot have a diferente initial point, so I thought of do this with a for sentences, opening each plot, doing all and so on.

But I open the first one, and then it plots the second one, but don’t let me select the original point, it catches the previos one. And the same for the rest.
And I don’t know why it doesn’t work.

Here you have all the program:

···

#!/usr/bin/python

-- encoding: latin1 --

#Importamos los módulos necesarios:

import Numeric as num
import pylab
import random

import array
import sys
from matplotlib.widgets import SpanSelector
from matplotlib.widgets import Cursor

#Leemos el fichero que contiene el valor de la energia y la suma de los espines:

def readfiles(filename):

"""
Lee el fichero donde estan los datos. La primera fila del fichero nos da la temperatura y el numero de puntos.
Las dos columnas tienen la energia y la suma de los spines.
"""


fin = open (filename, 'r')
fields = fin.readline()
fin.close()
labels = fields[1:].split()
t = eval(labels[1])
n = eval(labels[6])

datos = pylab.load(filename,comments='#')

energia =datos[:,0]
sumspines =datos[:,1]

return t, n, energia, sumspines

def filelist(filename):
fin = open(filename,‘r’)
files =
for line in fin:

            files.append(line[:-1]),
    return files

def writefile(filename,start,cv,mag,t):
“”"
Escribimos en un fichero todos los datos de punto de corte, calores especificos,

    magnetizacion y temperatura
    """
    fout = open(filename,'w')
    fout.write ("#punto de corte    cv    magnetizacion    temperatura")
    for i in range (len(start)):

            fout.write("%f \t %f \t %f \t %f \n"  %  (start[i],cv[i], mag[i], t[i]))
    fout.close()

def cv(energia,T,n,g,start):
“”"
Calculamos el calor específico segun la formula:

Cv= k*B**2/(nx*ny)*(<H²> - <H>²
donde:
<H>² = (sumatorio H/n) **2
<H²> = (sumatorio H) **2 /n
"""
hp = sum(energia[start:])/(n*g*g*2.)

energia2 = num.asarray(energia)
hp2 = sum(energia2[start:]**2)/n*(g*g*2)**2

print 'Algunos valores de la energia: ',energia[start:start+10]

return (hp2-hp**2)/(g*g*T**2)

def mag(sumspines,n,g,start):

"""
Calculamos la magnetizacion, usando la formula:
<M> = (sumatorio S) /n
"""

print 'Algunos valores de sumspines: ', sumspines[start:start+10]

print 'la n es: ', n

return sum(sumspines[start:]) /(n*g*g)

def grid(zn):
im1 = pylab.imshow(zn, cmap=pylab.cm.gray, interpolation=‘nearest’)
pylab.show()

def plotear(energia):
fig=pylab.figure(figsize=(8,6))
ax = fig.add_subplot(111)
x=pylab.arange(0,len(energia),1)
ax.plot(x,energia,linewidth=2)
pylab.grid(True)

cursor = Cursor(ax, useblit=False, color='red', linewidth=2)

cursor.horizOn = False

def click(event):
global x
#x,y = event.x,event.y
if event.button == 1:
if event.inaxes:

print ‘coordenada x’, event.xdata

        x = event.xdata
        pylab.disconnect(cid)
        pylab.close()
return x

def main0 ():
global cid

filename = raw_input("Introduce el fichero de datos: ")

t= temperatura

n= numero de pasos

energia = valores de la energia, sin normalizar (hay que multiplicar por

1/( 2nxny)

sumspines= valor de la suma de los espines para cada energia

g = grid (nx =ny)

t, n, energia, sumspines =  readfiles(filename)
g = float(filename[(filename.find('-')+1):])

plotear(energia)
cid = pylab.connect('button_press_event', click)

pylab.show()
x1 = int(x)
print 'Coordenada x: ',x1

print 'El calor especifico es: ',cv(energia,t, n,g,x1)
print 'La magnetizacion es: ', mag(sumspines,n,g,x1)

def main1():
global x, cid
filename = raw_input("Introduce el fichero con la lista: ")
files = filelist(filename)
start=
cvall=
magall=

    ts=[]
    for i in range(len(files)):
            t,n,energia,sumspines= readfiles(files[i])
            g = float(files[1][(files[1].find('-')+1):])

            plotear(energia)

            cid = pylab.connect('button_press_event', click)
            pylab.show()
            x1 = int(x)
            start.append(x1)
            cv1=cv(energia,t, n,g,start[i])

            mag1= mag(sumspines,n,g,start[i])

            cvall.append(cv1)
            magall.append(mag1)
            ts.append(t)
            print 'Coordenada x: ',x1

            print 'El calor especifico es: ',cv1
            print 'La magnetizacion es: ', mag1
           
    filename2='resultados_globales.%s' % (g)
    writefile(filename2,start,cvall,magall,ts)

def main2():
print “todavia no esta hecho”

if name == “main”:

print "Selecciona una de las siguientes opciones: \n "
print "Un solo fichero de datos (0)"

print "Lista de ficheros de datos (1)"
print "Lista de ficheros de datos y valores de corte (2)"

option = input()

if option ==0:
        main0()
if option == 1:

        main1()
if option ==2:
        main2()

2007/6/27, Matthias Michler <

MatthiasMichler@…361…>:

Hello darkside,

I’m a little confused that you are sending the email directly to me …

and I’m not sure I really understand your problem, but I set up an example
that hopefully satify your needs and shows that it works in principle :


import pylab

def click(event):
global x # allow to change global variable
if event.button == 1:
if event.inaxes:
x = event.xdata # change global variable

        print " x - intern = ", x
        pylab.disconnect(cid)
        pylab.close()

xlist = # list for x values
global x
for i in xrange(8):

pylab.figure

()
pylab.subplot(111)
pylab.draw()
cid = pylab.connect(‘button_press_event’, click)
pylab.show()
print " x - extern = ", x
xlist.append(x)

pylab.figure()

pylab.subplot(111)
pylab.plot(xlist, ‘b+’, ms=8, mew=4) # plot ensemble of x values
pylab.show()


If this example is not sufficient for you, please set up a little example of
your problem, which can be executed from here, too.
This you may send to mpl mailing-list.

I have already tried this example and it doesn’t work for me. It catches the same x for all the plots.

Thank you for you kind help.

P.D. I send the previous message to you because I clicked the reply button and I didn’t see that it was only you, sorry.