1

I am working on an program to identify significant frequencies in a power density spectrum. I have found a list of significant peaks in a automated way. But now I want to look at them visually and add / delete peaks from a plot using fig.canvas.mpl_connect('key_press_event', ontype) (http://matplotlib.org/users/event_handling.html)

As I want to add multiple peaks I want to update the used list. Though I get a UnboundLocalError: local variable 'frequencyLIST' referenced before assignment error.

def interactiveMethod(frequency,PDS, frequencyLIST,figureName):
#frequency and PDS is the input list of data, frequencyLIST is my found list of
#frequencies and figureName is the figure I previously made which I want to use the
#event on.

 def ontype(event):
  if event.key == 'a':
   #Getting the event xdata
   x = event.xdata      
   frequencyCut = frequency[np.where((frequency > x - 2) & (frequency < x + 2))]
   PDSCut = PDS[np.where((frequency > x - 2) & (frequency < x + 2))]

   #Find the maximum PDS, as this corresponds to a peak
   PDSMax = np.max(PDSCut)
   frequencyMax = frequencyCut[np.where(PDSCut == PDSMax)][0]

   #Updating the new list using the found frequency
   frequencyLIST = np.append(frequencyLIST,frequencyMax)

 figureName.canvas.mpl_connect('key_press_event',ontype)

I have no idea where I should put this frequencyLIST so I can update it.

python version: 2.7.3 32bit

matplotlib version: 1.3.0

numpy version: 1.7.1

ubuntu 13.1

I also have enthough canopy (not sure which version)

bramb
  • 213
  • 2
  • 14

1 Answers1

0

You are passing the frequencyLIST variable to the outermost method (interactiveMethod) but not to the inner method (ontype). A quick fix is to add the following line to the inner method:

def ontype(event):
    global frequencyLIST
    # ... following lines unaltered ...

You can read more on the way Python scopes variables, and a quirk similar to yours, in this Stack Overflow question

Community
  • 1
  • 1
logc
  • 3,813
  • 1
  • 18
  • 29
  • It doesn't seem fixed. It gives me the error message *NameError: global name 'frequencyLIST' is not defined*. I am running out of ideas. I will test if I can pass multiple arguments to the mpl_connect but I doubt it. – bramb Feb 18 '14 at 10:21
  • Apparently it is a problem with np.array or np.append. When I work with normal lists there is no problem. – bramb Feb 18 '14 at 11:22
  • Yes, the `np.append` does not change the list in-place. It returns a new list (array) with the new element at the end. Is working with normal lists enough for your solution? – logc Feb 18 '14 at 11:30
  • Yes. Working with normal lists is no problem. It makes bookkeeping only a little bit less clear. As the frequencyLIST in my actual code is a 6 by N matrix. But is the way to go! – bramb Feb 18 '14 at 12:03