class MatPlot_Window(wx.Window):
    def __init__(self, *args, **kwargs):
        wx.Window.__init__(self, *args, **kwargs)
        self.signals = []
        self.figure = Figure()
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
        self.canvas.callbacks.connect('button_press_event', self.mouseDown)
        self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion)
        self.canvas.callbacks.connect('button_release_event', self.mouseUp)
        self.state = None

        self.Bind(wx.EVT_SIZE, self.sizeHandler)

    def sizeHandler(self, *args, **kwargs):
        self.canvas.SetSize(self.GetSize())

    def mouseDown(self, event):
        self.state = None
        for i, signal in enumerate(self.signals):
            if signal in self.figure.hitlist(event):
                self.state = i + 1
                self.x0 = event.xdata
                self.y0 = event.ydata
                if abs(self.x0) < 1.e-8:
                    self.x0 = 1.e-8

                # get all the initial values
                self.CI = []
                for C in self.Controls:
                    self.CI.append(C.value)
                break

    def mouseUp(self, event):
        self.state = None

    def Set_Knob_Value(self, value):
        XY = self.compute()
        for i, xy in enumerate(XY):
            setp(self.signals[i], xdata=xy[0], ydata=xy[1])
        self.canvas.draw()
class FourierDemoWindow(wx.Window, Knob):
    def __init__(self, *args, **kwargs):
        wx.Window.__init__(self, *args, **kwargs)
        self.lines = []
        self.imgs = []
        self.bkgrnd = []
        self.mean = []
        self.figure = Figure()
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
        self.canvas.callbacks.connect('button_press_event', self.mouseDown)
        self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion)
        self.canvas.callbacks.connect('button_release_event', self.mouseUp)

        self.state = ''
        self.mov = cb.load('movies/demoMovie.tif', fr=20)
        with np.load('results_analysis.npz') as ld:
            self.comps = np.transpose(
                np.reshape(ld['A2'], (ld['d1'], ld['d2'], -1), order='F'),
                [2, 0, 1])

        self.mean = np.mean(self.mov, 0)
        self.mouseInfo = (None, None, None, None)
        self.f0 = Param(np.percentile(self.mean, 95),
                        minimum=np.min(self.mean),
                        maximum=np.max(self.mean))
        self.A = Param(1, minimum=0, maximum=self.mov.shape[0], step=1)
        self.toggle_background = BoolParam(True)
        self.draw()

        # Not sure I like having two params attached to the same Knob,
        # but that is what we have here... it works but feels kludgy -
        # although maybe it's not too bad since the knob changes both params
        # at the same time (both f0 and A are affected during a drag)
        self.f0.attach(self)
        self.A.attach(self)
        self.toggle_background.attach(self)

        self.Bind(wx.EVT_SIZE, self.sizeHandler)

    def sizeHandler(self, *args, **kwargs):
        self.canvas.SetSize(self.GetSize())

    def mouseDown(self, evt):
        if self.lines[0] in self.figure.hitlist(evt):
            self.state = 'frequency'
        elif self.lines[1] in self.figure.hitlist(evt):
            self.state = 'time'
        else:
            self.state = ''
        self.mouseInfo = (evt.xdata, evt.ydata, max(self.f0.value,
                                                    .1), self.A.value)

    def mouseMotion(self, evt):
        if self.state == '':
            return
        x, y = evt.xdata, evt.ydata
        if x is None:  # outside the axes
            return
        x0, y0, f0Init, AInit = self.mouseInfo
        self.A.set(AInit + (AInit * (y - y0) / y0), self)
        if self.state == 'frequency':
            self.f0.set(f0Init + (f0Init * (x - x0) / x0))
        elif self.state == 'time':
            if (x - x0) / x0 != -1.:
                self.f0.set(1. / (1. / f0Init + (1. / f0Init * (x - x0) / x0)))

    def mouseUp(self, evt):
        self.state = ''

    def draw(self):
        if not hasattr(self, 'subplot1'):
            self.subplot1 = self.figure.add_subplot(121)
            self.subplot2 = self.figure.add_subplot(122)
        x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
        color = (1., 0., 0.)

        self.bkgrnd = self.subplot1.imshow(self.mean,
                                           cmap='gray',
                                           vmax=self.f0.value)
        #        self.lines += self.subplot2.plot(x2, y2, color=color, linewidth=2)
        self.img = self.subplot2.imshow(self.mov[0], cmap='gray')

        #Set some plot attributes
        self.subplot1.set_title("Overlaid components", fontsize=12)
        self.subplot2.set_title("Movie frames", fontsize=12)


#        self.subplot1.set_ylabel("Frequency Domain Waveform X(f)", fontsize = 8)
#        self.subplot1.set_xlabel("frequency f", fontsize = 8)
#        self.subplot2.set_ylabel("Time Domain Waveform x(t)", fontsize = 8)
#        self.subplot2.set_xlabel("time t", fontsize = 8)
#        self.subplot1.set_xlim([-6, 6])
#        self.subplot1.set_ylim([0, 1])
#        self.subplot2.set_xlim([-2, 2])
#        self.subplot2.set_ylim([-2, 2])
#        self.subplot1.text(0.05, .95, r'$X(f) = \mathcal{F}\{x(t)\}$', \
#            verticalalignment='top', transform = self.subplot1.transAxes)
#        self.subplot2.text(0.05, .95, r'$x(t) = a \cdot \cos(2\pi f_0 t) e^{-\pi t^2}$', \
#            verticalalignment='top', transform = self.subplot2.transAxes)

    def compute(self, f0, A):
        f = np.arange(-6., 6., 0.02)
        t = np.arange(-2., 2., 0.01)
        x = A * np.cos(2 * np.pi * f0 * t) * np.exp(-np.pi * t**2)
        X = A / 2 * (np.exp(-np.pi * (f - f0)**2) + np.exp(-np.pi *
                                                           (f + f0)**2))
        return f, X, t, x

    def repaint(self):
        self.canvas.draw()

    def setKnob(self, value):
        # Note, we ignore value arg here and just go by state of the params
        #        x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)

        #setp(self.lines[0], xdata=np.arange(100), ydata=np.random.random((100,)))

        if self.toggle_background.value == True:
            self.bkgrnd.set_data(self.mean)
            self.bkgrnd.set_clim(vmax=self.f0.value)
        else:
            self.bkgrnd.set_data(self.mean * np.nan)

        self.img.set_data(self.mov[np.int(self.A.value)])

        self.repaint()
class FourierDemoWindow(wx.Window, Knob):
    def __init__(self, *args, **kwargs):
        wx.Window.__init__(self, *args, **kwargs)
        self.lines = []
        self.figure = Figure()
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
        self.canvas.callbacks.connect('button_press_event', self.mouseDown)
        self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion)
        self.canvas.callbacks.connect('button_release_event', self.mouseUp)
        self.state = ''
        self.mouseInfo = (None, None, None, None)
        self.f0 = Param(2., minimum=0., maximum=6.)
        self.A = Param(1., minimum=0.01, maximum=2.)
        self.draw()

        # Not sure I like having two params attached to the same Knob,
        # but that is what we have here... it works but feels kludgy -
        # although maybe it's not too bad since the knob changes both params
        # at the same time (both f0 and A are affected during a drag)
        self.f0.attach(self)
        self.A.attach(self)
        self.Bind(wx.EVT_SIZE, self.sizeHandler)

        self.Bind(wx.EVT_PAINT, self.OnPaint)

    def OnPaint(self, event):
        self.canvas.draw()
        event.Skip()

    def sizeHandler(self, *args, **kwargs):
        self.canvas.SetSize(self.GetSize())

    def mouseDown(self, evt):
        if self.lines[0] in self.figure.hitlist(evt):
            self.state = 'frequency'
        elif self.lines[1] in self.figure.hitlist(evt):
            self.state = 'time'
        else:
            self.state = ''
        self.mouseInfo = (evt.xdata, evt.ydata,
                          max(self.f0.value, .1),
                          self.A.value)

    def mouseMotion(self, evt):
        if self.state == '':
            return
        x, y = evt.xdata, evt.ydata
        if x is None:  # outside the axes
            return
        x0, y0, f0Init, AInit = self.mouseInfo
        self.A.set(AInit + (AInit * (y - y0) / y0), self)
        if self.state == 'frequency':
            self.f0.set(f0Init + (f0Init * (x - x0) / x0))
        elif self.state == 'time':
            if (x - x0) / x0 != -1.:
                self.f0.set(1. / (1. / f0Init + (1. / f0Init * (x - x0) / x0)))

    def mouseUp(self, evt):
        self.state = ''

    def draw(self):
        if not hasattr(self, 'subplot1'):
            self.subplot1 = self.figure.add_subplot(211)
            self.subplot2 = self.figure.add_subplot(212)
        x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
        color = (1., 0., 0.)
        self.lines += self.subplot1.plot(x1, y1, color=color, linewidth=2)
        self.lines += self.subplot2.plot(x2, y2, color=color, linewidth=2)
        # Set some plot attributes
        self.subplot1.set_title(
            "Click and drag waveforms to change frequency and amplitude",
            fontsize=12)
        self.subplot1.set_ylabel("Frequency Domain Waveform X(f)", fontsize=8)
        self.subplot1.set_xlabel("frequency f", fontsize=8)
        self.subplot2.set_ylabel("Time Domain Waveform x(t)", fontsize=8)
        self.subplot2.set_xlabel("time t", fontsize=8)
        self.subplot1.set_xlim([-6, 6])
        self.subplot1.set_ylim([0, 1])
        self.subplot2.set_xlim([-2, 2])
        self.subplot2.set_ylim([-2, 2])
        self.subplot1.text(0.05, .95,
                           r'$X(f) = \mathcal{F}\{x(t)\}$',
                           verticalalignment='top',
                           transform=self.subplot1.transAxes)
        self.subplot2.text(0.05, .95,
                           r'$x(t) = a \cdot \cos(2\pi f_0 t) e^{-\pi t^2}$',
                           verticalalignment='top',
                           transform=self.subplot2.transAxes)

    def compute(self, f0, A):
        f = np.arange(-6., 6., 0.02)
        t = np.arange(-2., 2., 0.01)
        x = A * np.cos(2 * np.pi * f0 * t) * np.exp(-np.pi * t ** 2)
        X = A / 2 * \
            (np.exp(-np.pi * (f - f0) ** 2) + np.exp(-np.pi * (f + f0) ** 2))
        return f, X, t, x

    def repaint(self):
        self.canvas.draw()

    def setKnob(self, value):
        # Note, we ignore value arg here and just go by state of the params
        x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
        setp(self.lines[0], xdata=x1, ydata=y1)
        setp(self.lines[1], xdata=x2, ydata=y2)
        self.repaint()
Exemple #4
0
class FourierDemoWindow(wx.Window, Knob):
    def __init__(self, *args, **kwargs):
        wx.Window.__init__(self, *args, **kwargs)
        self.lines = []
        self.figure = Figure()
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
        self.canvas.callbacks.connect('button_press_event', self.mouseDown)
        self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion)
        self.canvas.callbacks.connect('button_release_event', self.mouseUp)
        self.state = ''
        self.mouseInfo = (None, None, None, None)
        self.f0 = Param(2., minimum=0., maximum=6.)
        self.A = Param(1., minimum=0.01, maximum=2.)
        self.draw()

        # Not sure I like having two params attached to the same Knob,
        # but that is what we have here... it works but feels kludgy -
        # although maybe it's not too bad since the knob changes both params
        # at the same time (both f0 and A are affected during a drag)
        self.f0.attach(self)
        self.A.attach(self)
        self.Bind(wx.EVT_SIZE, self.sizeHandler)

    def sizeHandler(self, *args, **kwargs):
        self.canvas.SetSize(self.GetSize())

    def mouseDown(self, evt):
        if self.lines[0] in self.figure.hitlist(evt):
            self.state = 'frequency'
        elif self.lines[1] in self.figure.hitlist(evt):
            self.state = 'time'
        else:
            self.state = ''
        self.mouseInfo = (evt.xdata, evt.ydata, max(self.f0.value, .1), self.A.value)

    def mouseMotion(self, evt):
        if self.state == '':
            return
        x, y = evt.xdata, evt.ydata
        if x is None:  # outside the axes
            return
        x0, y0, f0Init, AInit = self.mouseInfo
        self.A.set(AInit+(AInit*(y-y0)/y0), self)
        if self.state == 'frequency':
            self.f0.set(f0Init+(f0Init*(x-x0)/x0))
        elif self.state == 'time':
            if (x-x0)/x0 != -1.:
                self.f0.set(1./(1./f0Init+(1./f0Init*(x-x0)/x0)))

    def mouseUp(self, evt):
        self.state = ''

    def draw(self):
        if not hasattr(self, 'subplot1'):
            self.subplot1 = self.figure.add_subplot(211)
            self.subplot2 = self.figure.add_subplot(212)
        x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
        color = (1., 0., 0.)
        self.lines += self.subplot1.plot(x1, y1, color=color, linewidth=2)
        self.lines += self.subplot2.plot(x2, y2, color=color, linewidth=2)
        # Set some plot attributes
        self.subplot1.set_title("Click and drag waveforms to change frequency and amplitude", fontsize=12)
        self.subplot1.set_ylabel("Frequency Domain Waveform X(f)", fontsize=8)
        self.subplot1.set_xlabel("frequency f", fontsize=8)
        self.subplot2.set_ylabel("Time Domain Waveform x(t)", fontsize=8)
        self.subplot2.set_xlabel("time t", fontsize=8)
        self.subplot1.set_xlim([-6, 6])
        self.subplot1.set_ylim([0, 1])
        self.subplot2.set_xlim([-2, 2])
        self.subplot2.set_ylim([-2, 2])
        self.subplot1.text(0.05, .95, r'$X(f) = \mathcal{F}\{x(t)\}$', \
            verticalalignment='top', transform=self.subplot1.transAxes)
        self.subplot2.text(0.05, .95, r'$x(t) = a \cdot \cos(2\pi f_0 t) e^{-\pi t^2}$', \
            verticalalignment='top', transform=self.subplot2.transAxes)

    def compute(self, f0, A):
        f = np.arange(-6., 6., 0.02)
        t = np.arange(-2., 2., 0.01)
        x = A*np.cos(2*np.pi*f0*t)*np.exp(-np.pi*t**2)
        X = A/2*(np.exp(-np.pi*(f-f0)**2) + np.exp(-np.pi*(f+f0)**2))
        return f, X, t, x

    def repaint(self):
        self.canvas.draw()

    def setKnob(self, value):
        # Note, we ignore value arg here and just go by state of the params
        x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
        setp(self.lines[0], xdata=x1, ydata=y1)
        setp(self.lines[1], xdata=x2, ydata=y2)
        self.repaint()
Exemple #5
0
class CanvasFrame(wx.Frame):
    def __init__(self, rc, str_):
        wx.Frame.__init__(self,
                          None,
                          title="Real Time " + str_ + " Comparison",
                          size=DefaultSize)
        self.figure = Figure(facecolor=ColorBackground,
                             edgecolor=ColorBackground)
        self.lines = []
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.axes = self.figure.add_subplot(111)
        self.canvas.callbacks.connect('button_press_event', self.mouseDown)
        self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion)
        self.canvas.callbacks.connect('button_release_event', self.mouseUp)
        self.state = ''
        self.mouseInfo = (None, None, None, None)
        if str_ == "Gold":
            select = "gold_t"
        else:
            select = "xp_t"
        self.str = str_
        PlayersStats = []
        for i in range(10):
            PlayersStats.append(rc["players"][i][select])
        PlayersStats = np.asarray(PlayersStats)
        RadiantStats = sum(PlayersStats[0:5])
        DireStats = sum(PlayersStats[5:10])
        RadiantAdv = (RadiantStats - DireStats).tolist()
        x = []
        base = []
        for i in range(len(RadiantAdv)):
            x.append(i)
            base.append(0)
        x = np.asarray(x)
        base = np.asarray(base)
        self.lower = min(RadiantAdv)
        self.upper = max(RadiantAdv)
        RadiantAdv = np.asarray(RadiantAdv)
        self.axes.plot(x,
                       RadiantAdv,
                       x,
                       base,
                       color=ColorText,
                       mec=ColorBackground,
                       mfc=ColorBackground)
        self.axes.fill_between(x,
                               RadiantAdv,
                               base,
                               where=RadiantAdv >= base,
                               facecolor=ColorRadiant,
                               interpolate=True)
        self.axes.fill_between(x,
                               RadiantAdv,
                               base,
                               where=RadiantAdv <= base,
                               facecolor=ColorDire,
                               interpolate=True)
        self.axes.set_xlabel('time/minute', {'color': ColorText})
        self.axes.set_ylabel('Radiant ' + str_ + ' Adv', {'color': ColorText})
        self.axes.set_facecolor(ColorBackground)
        self.axes.set_xticklabels(self.axes.get_xticks(), color=ColorText)
        self.axes.set_yticklabels(self.axes.get_yticks(), color=ColorText)
        self.axes.tick_params(axis='both', color=ColorText)
        self.axes.set_frame_on(False)
        self.f0 = Param(0., minimum=0., maximum=float(len(x)))
        self.RadiantAdv = RadiantAdv
        self.draw()
        self.f0.attach(self)
        self.Bind(wx.EVT_SIZE, self.sizeHandler)

    def sizeHandler(self, *args, **kwargs):
        self.canvas.SetSize(self.GetSize())

    def mouseDown(self, evt):
        if self.lines[0] in self.figure.hitlist(evt):
            self.state = 'frequency'
        else:
            self.state = ''
        self.mouseInfo = (evt.xdata, evt.ydata, self.f0.value)

    def mouseMotion(self, evt):
        if self.state == '':
            return
        x, y = evt.xdata, evt.ydata
        if x is None:
            return
        x0, y0, f0Init = self.mouseInfo
        if self.state == 'frequency':
            self.f0.set((x - x0) + f0Init)

    def mouseUp(self, evt):
        self.state = ''

    def draw(self):
        x1, y1 = self.compute(self.f0.value)
        self.lines += self.axes.plot(x1, y1, color=ColorText, linewidth=1)
        time = self.f0.value
        preIndex = math.floor(time)
        posIndex = math.ceil(time)
        RadiantAdv = (self.RadiantAdv[posIndex] -
                      self.RadiantAdv[preIndex]) * (time - preIndex)
        RadiantWinRate = 0.5
        self.text1 = self.axes.text(0.05,
                                    .95,
                                    "time: " + str(time),
                                    verticalalignment='top',
                                    transform=self.axes.transAxes,
                                    color=ColorText)
        self.text2 = self.axes.text(0.05,
                                    .90,
                                    "adv: " + str(RadiantAdv),
                                    verticalalignment='top',
                                    transform=self.axes.transAxes,
                                    color=ColorText)
        self.text3 = self.axes.text(0.05,
                                    .85,
                                    "winRate: " + str(RadiantWinRate),
                                    verticalalignment='top',
                                    transform=self.axes.transAxes,
                                    color=ColorText)

    def compute(self, f0):
        x = np.arange(self.lower, self.upper, 10)
        f = np.full(x.shape, f0)
        return f, x

    def repaint(self):
        time = self.f0.value
        preIndex = math.floor(time)
        posIndex = math.ceil(time)
        RadiantAdv = (self.RadiantAdv[posIndex] - self.RadiantAdv[preIndex]
                      ) * (time - preIndex) + self.RadiantAdv[preIndex]
        time_ratio = time / len(self.RadiantAdv)
        if self.str == "Gold":
            if time_ratio < 0.2:
                RadiantWinRate = LR_g2.predict_proba(RadiantAdv)[0][1]
            elif time_ratio < 0.4:
                RadiantWinRate = LR_g4.predict_proba(RadiantAdv)[0][1]
            elif time_ratio < 0.4:
                RadiantWinRate = LR_g6.predict_proba(RadiantAdv)[0][1]
            elif time_ratio < 0.4:
                RadiantWinRate = LR_g8.predict_proba(RadiantAdv)[0][1]
            else:
                RadiantWinRate = LR_g0.predict_proba(RadiantAdv)[0][1]
        else:
            if time_ratio < 0.2:
                RadiantWinRate = LR_x2.predict_proba(RadiantAdv)[0][1]
            elif time_ratio < 0.4:
                RadiantWinRate = LR_x4.predict_proba(RadiantAdv)[0][1]
            elif time_ratio < 0.4:
                RadiantWinRate = LR_x6.predict_proba(RadiantAdv)[0][1]
            elif time_ratio < 0.4:
                RadiantWinRate = LR_x8.predict_proba(RadiantAdv)[0][1]
            else:
                RadiantWinRate = LR_x0.predict_proba(RadiantAdv)[0][1]
        self.text1.set_text("time: " + str(time))
        self.text2.set_text("adv: " + str(RadiantAdv))
        self.text3.set_text("winRate: " + str(RadiantWinRate))
        self.canvas.draw()

    def setKnob(self, value):
        x1, y1 = self.compute(self.f0.value)
        setp(self.lines[0], xdata=x1, ydata=y1)
        self.repaint()
Exemple #6
0
class ImageSegmentAdjustWindow(wx.Window, Knob):
    def __init__(self, *args, **kwargs):
        wx.Window.__init__(self, *args, **kwargs)
        self.image_file = '.\\static\\images\\number_systems\\mayadays.gif'
        self.lines = []
        self.figure = Figure()
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
        self.canvas.callbacks.connect('button_press_event', self.mouseDown)
        self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion)
        self.canvas.callbacks.connect('button_release_event', self.mouseUp)
        self.state = ''
        self.mouseInfo = (None, None, None, None)
        self.f0 = Param(2., minimum=0., maximum=6.)
        self.A = Param(1., minimum=0.01, maximum=2.)
        self.draw()

        # Not sure I like having two params attached to the same Knob,
        # but that is what we have here... it works but feels kludgy -
        # although maybe it's not too bad since the knob changes both params
        # at the same time (both f0 and A are affected during a drag)
        self.f0.attach(self)
        self.A.attach(self)
        self.Bind(wx.EVT_SIZE, self.sizeHandler)

    def sizeHandler(self, *args, **kwargs):
        self.canvas.SetSize(self.GetSize())

    def mouseDown(self, evt):
        if self.lines[0] in self.figure.hitlist(evt):
            self.state = 'frequency'
        elif self.lines[1] in self.figure.hitlist(evt):
            self.state = 'time'
        else:
            self.state = ''
        self.mouseInfo = (evt.xdata, evt.ydata, max(self.f0.value, .1), self.A.value)

    def mouseMotion(self, evt):
        if self.state == '':
            return
        x, y = evt.xdata, evt.ydata
        if x is None:  # outside the axes
            return
        x0, y0, f0Init, AInit = self.mouseInfo
        self.A.set(AInit+(AInit*(y-y0)/y0), self)
        if self.state == 'frequency':
            self.f0.set(f0Init+(f0Init*(x-x0)/x0))
        elif self.state == 'time':
            if (x-x0)/x0 != -1.:
                self.f0.set(1./(1./f0Init+(1./f0Init*(x-x0)/x0)))

    def mouseUp(self, evt):
        self.state = ''

    def draw(self):
        if not hasattr(self, 'ax'):
            self.axOriginal = self.figure.add_subplot(221)
            self.axGreyScale = self.figure.add_subplot(222)
            self.axFiltered = self.figure.add_subplot(223)
            self.axSegments = self.figure.add_subplot(224)
            self.image = data.coins()
#            self.image = imread(self.image_file)

        self.axOriginal.set_title("Original Image", fontsize=12)
        self.axOriginal.imshow(self.image)
        
        self.axGreyScale.set_title("Greyscale Image", fontsize=12)
        self.grey_image = color.rgb2grey(self.image)
        self.axGreyScale.imshow(self.grey_image, cmap = cm.Greys_r)

        self.filter_image()
#        thresh = threshold_otsu(self.grey_image)
#        self.bw_image = closing(self.grey_image > thresh, square(1))
#        self.axThreshold.imshow(self.bw_image)
        
        self.axSegments.set_title("Segmented Image", fontsize=12)
        
        self.label_image = label(self.filtered)
#        borders = np.logical_xor(self.bw_image, self.cleared)
#        self.label_image[borders] = -1
        
#        fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
        self.axSegments.imshow(self.label_image, cmap='jet')
        
        for region in regionprops(self.label_image, ['Area', 'BoundingBox']):
        
            # skip small images
            if region['Area'] < 100:
                continue
        
            # draw rectangle around segmented coins
            minr, minc, maxr, maxc = region['BoundingBox']
            rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=2)
            self.axSegments.add_patch(rect)
    
#        x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
#        color = (1., 0., 0.)
#        self.lines += self.subplot1.plot(x1, y1, color=color, linewidth=2)
#        self.lines += self.subplot2.plot(x2, y2, color=color, linewidth=2)
#        #Set some plot attributes
#        self.subplot1.set_title("Click and drag waveforms to change frequency and amplitude", fontsize=12)
#        self.subplot1.set_ylabel("Frequency Domain Waveform X(f)", fontsize = 8)
#        self.subplot1.set_xlabel("frequency f", fontsize = 8)
#        self.subplot2.set_ylabel("Time Domain Waveform x(t)", fontsize = 8)
#        self.subplot2.set_xlabel("time t", fontsize = 8)
#        self.subplot1.set_xlim([-6, 6])
#        self.subplot1.set_ylim([0, 1])
#        self.subplot2.set_xlim([-2, 2])
#        self.subplot2.set_ylim([-2, 2])
#        self.subplot1.text(0.05, .95, r'$X(f) = \mathcal{F}\{x(t)\}$', \
#            verticalalignment='top', transform = self.subplot1.transAxes)
#        self.subplot2.text(0.05, .95, r'$x(t) = a \cdot \cos(2\pi f_0 t) e^{-\pi t^2}$', \
#            verticalalignment='top', transform = self.subplot2.transAxes)

    def filter_image(self):
        filter = self.GetParent().cb_filter.GetValue() 
        if filter == 'threshold': 
            self.axFiltered.set_title("Threshold Image", fontsize=12)
            thresh = threshold_otsu(self.grey_image)
#            self.bw_image = closing(self.grey_image > thresh, square(1))
#            self.axFiltered.imshow(self.bw_image)
#            self.cleared = self.bw_image.copy()
#            clear_border(self.cleared)        
            self.filtered = closing(self.grey_image > thresh, square(1))
            clear_border(self.filtered) 
            self.axFiltered.imshow(self.filtered)
#            self.cleared = self.bw_image.copy()
            
        elif filter == 'canny':
            self.axFiltered.set_title("Canny", fontsize=12)
#            self.grey_image = PIL.ImageOps.invert(self.grey_image)
            self.edges = canny(self.grey_image/255.)
#            self.filtered = ndimage.binary_fill_holes(self.edges)
            self.filtered = self.grey_image.copy()
            self.filtered[self.edges] = 0
            self.axFiltered.imshow(self.filtered, cmap = cm.Greys_r)
                

    def compute(self, f0, A):
        f = np.arange(-6., 6., 0.02)
        t = np.arange(-2., 2., 0.01)
        x = A*np.cos(2*np.pi*f0*t)*np.exp(-np.pi*t**2)
        X = A/2*(np.exp(-np.pi*(f-f0)**2) + np.exp(-np.pi*(f+f0)**2))
        return f, X, t, x

    def repaint(self):
        self.canvas.draw()

    def setKnob(self, value):
        # Note, we ignore value arg here and just go by state of the params
        x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
        setp(self.lines[0], xdata=x1, ydata=y1)
        setp(self.lines[1], xdata=x2, ydata=y2)
        self.repaint()
class FourierDemoWindow(wx.Window, Knob):
    def __init__(self, *args, **kwargs):
        wx.Window.__init__(self, *args, **kwargs)
        self.lines = []
        self.imgs = []
        self.bkgrnd = []
        self.mean = []
        self.figure = Figure()
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
        self.canvas.callbacks.connect('button_press_event', self.mouseDown)
        self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion)
        self.canvas.callbacks.connect('button_release_event', self.mouseUp)
        
        self.state = ''
        self.mov=cb.load('movies/demoMovie.tif',fr=20)
        with np.load('results_analysis.npz')  as ld:
            self.comps=np.transpose(np.reshape(ld['A2'],(ld['d1'],ld['d2'],-1),order='F'),[2,0,1])
            
        self.mean = np.mean(self.mov,0)
        self.mouseInfo = (None, None, None, None)
        self.f0 = Param(np.percentile(self.mean,95), minimum=np.min(self.mean), maximum=np.max(self.mean))
        self.A = Param(1, minimum=0, maximum=self.mov.shape[0],step=1)
        self.toggle_background = BoolParam(True)
        self.draw()
        
        # Not sure I like having two params attached to the same Knob,
        # but that is what we have here... it works but feels kludgy -
        # although maybe it's not too bad since the knob changes both params
        # at the same time (both f0 and A are affected during a drag)
        self.f0.attach(self)
        self.A.attach(self)
        self.toggle_background.attach(self)
        
        self.Bind(wx.EVT_SIZE, self.sizeHandler)
       
    def sizeHandler(self, *args, **kwargs):
        self.canvas.SetSize(self.GetSize())
        
    def mouseDown(self, evt):
        if self.lines[0] in self.figure.hitlist(evt):
            self.state = 'frequency'
        elif self.lines[1] in self.figure.hitlist(evt):
            self.state = 'time'
        else:
            self.state = ''
        self.mouseInfo = (evt.xdata, evt.ydata, max(self.f0.value, .1), self.A.value)

    def mouseMotion(self, evt):
        if self.state == '':
            return
        x, y = evt.xdata, evt.ydata
        if x is None:  # outside the axes
            return
        x0, y0, f0Init, AInit = self.mouseInfo
        self.A.set(AInit+(AInit*(y-y0)/y0), self)
        if self.state == 'frequency':
            self.f0.set(f0Init+(f0Init*(x-x0)/x0))
        elif self.state == 'time':
            if (x-x0)/x0 != -1.:
                self.f0.set(1./(1./f0Init+(1./f0Init*(x-x0)/x0)))
                    
    def mouseUp(self, evt):
        self.state = ''

    def draw(self):
        if not hasattr(self, 'subplot1'):
            self.subplot1 = self.figure.add_subplot(121)
            self.subplot2 = self.figure.add_subplot(122)
        x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
        color = (1., 0., 0.)
        
        self.bkgrnd = self.subplot1.imshow(self.mean, cmap='gray',vmax=self.f0.value)
#        self.lines += self.subplot2.plot(x2, y2, color=color, linewidth=2)
        self.img = self.subplot2.imshow(self.mov[0], cmap='gray')

        #Set some plot attributes
        self.subplot1.set_title("Overlaid components", fontsize=12)
        self.subplot2.set_title("Movie frames", fontsize=12)
#        self.subplot1.set_ylabel("Frequency Domain Waveform X(f)", fontsize = 8)
#        self.subplot1.set_xlabel("frequency f", fontsize = 8)
#        self.subplot2.set_ylabel("Time Domain Waveform x(t)", fontsize = 8)
#        self.subplot2.set_xlabel("time t", fontsize = 8)
#        self.subplot1.set_xlim([-6, 6])
#        self.subplot1.set_ylim([0, 1])
#        self.subplot2.set_xlim([-2, 2])
#        self.subplot2.set_ylim([-2, 2])
#        self.subplot1.text(0.05, .95, r'$X(f) = \mathcal{F}\{x(t)\}$', \
#            verticalalignment='top', transform = self.subplot1.transAxes)
#        self.subplot2.text(0.05, .95, r'$x(t) = a \cdot \cos(2\pi f_0 t) e^{-\pi t^2}$', \
#            verticalalignment='top', transform = self.subplot2.transAxes)

    def compute(self, f0, A):
        f = np.arange(-6., 6., 0.02)
        t = np.arange(-2., 2., 0.01)
        x = A*np.cos(2*np.pi*f0*t)*np.exp(-np.pi*t**2)
        X = A/2*(np.exp(-np.pi*(f-f0)**2) + np.exp(-np.pi*(f+f0)**2))
        return f, X, t, x

    def repaint(self):
        self.canvas.draw()

    def setKnob(self, value):
        # Note, we ignore value arg here and just go by state of the params
#        x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)

        #setp(self.lines[0], xdata=np.arange(100), ydata=np.random.random((100,)))

        
        if self.toggle_background.value == True:
            self.bkgrnd.set_data(self.mean)
            self.bkgrnd.set_clim(vmax=self.f0.value)
        else:
            self.bkgrnd.set_data(self.mean*np.nan)
            
        self.img.set_data(self.mov[np.int(self.A.value)])

        self.repaint()