#       wxapp.py
#       
#       Copyright 2009 dan collins <quaninux@gmail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Mon Sep 15 19:43:15 2008
 
import wx
import os
#~ from matplotlib import use
#~ use('WXAgg')
#~ from pylab import *
#~ from pdf2py import data,channel,listparse, pdf, readwrite, tapbuild, lA2array, headshape
#~ from mri import img, viewmri, transform, mr2vtk, vtkview, sourcesolution2img,pydicom, mr2nifti
#~ from nifti import *
#~ from gui import file
#~ 
#~ from meg import megcontour, offset, leadfield, timef, \
#~ plotvtk, sensors, sourcespaceprojection, trigger, averager, epoch, fftmeg, badchannels, \
#~ density
from numpy import array, append, size, shape
#~ from scipy import ndimage
#~ #from rpy import *
#~ from meg import weightfit
import time
from time import sleep
import subprocess
#~ from meg import dbscan
#~ from pdf2py import tap, channel
#~ from mswtools import projectdu
 
# begin wxGlade: extracode
# end wxGlade
import sys
 
 
# end of class frame
 
 
class MyFrameDENSITY(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameDENSITY.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.label_27 = wx.StaticText(self, -1, "--Dipole Density Setup--")
        self.GOF = wx.StaticText(self, -1, "GOF scale:")
        self.gofval = wx.TextCtrl(self, -1, ".8")
        self.Sigma = wx.StaticText(self, -1, "Sigma:")
        self.sigmaval = wx.TextCtrl(self, -1, "3")
        self.LPA = wx.StaticText(self, -1, "LPA:")
        self.lpa_loc = wx.StaticText(self, -1, "[NA,NA,NA]")
        self.RPA = wx.StaticText(self, -1, "RPA:")
        self.rpa_loc = wx.StaticText(self, -1, "[NA,NA,NA]")
        self.NAS = wx.StaticText(self, -1, "NAS:")
        self.nas_loc = wx.StaticText(self, -1, "[NA,NA,NA]")
        self.numofdips = wx.StaticText(self, -1, "Num of Dipoles:")
        self.numdipolesval = wx.StaticText(self, -1, "No Dipoles Loaded")
        self.apply = wx.Button(self, wx.ID_APPLY, "")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_BUTTON, self.run, self.apply)
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: MyFrameDENSITY.__set_properties
        self.SetTitle("Dipole Density")
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
 
    def __do_layout(self):
        # begin wxGlade: MyFrameDENSITY.__do_layout
        sizer_41 = wx.BoxSizer(wx.VERTICAL)
        grid_sizer_5 = wx.GridSizer(1, 2, 2, 2)
        grid_sizer_6 = wx.GridSizer(4, 2, 0, 0)
        grid_sizer_7 = wx.FlexGridSizer(3, 2, 2, 2)
        sizer_41.Add(self.label_27, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_7.Add(self.GOF, 0, 0, 0)
        grid_sizer_7.Add(self.gofval, 0, 0, 0)
        grid_sizer_7.Add(self.Sigma, 0, 0, 0)
        grid_sizer_7.Add(self.sigmaval, 0, 0, 0)
        grid_sizer_7.AddGrowableRow(0)
        grid_sizer_5.Add(grid_sizer_7, 1, wx.EXPAND, 0)
        grid_sizer_6.Add(self.LPA, 0, 0, 0)
        grid_sizer_6.Add(self.lpa_loc, 0, 0, 0)
        grid_sizer_6.Add(self.RPA, 0, 0, 0)
        grid_sizer_6.Add(self.rpa_loc, 0, 0, 0)
        grid_sizer_6.Add(self.NAS, 0, 0, 0)
        grid_sizer_6.Add(self.nas_loc, 0, 0, 0)
        grid_sizer_6.Add(self.numofdips, 0, 0, 0)
        grid_sizer_6.Add(self.numdipolesval, 0, 0, 0)
        grid_sizer_5.Add(grid_sizer_6, 1, wx.EXPAND, 0)
        sizer_41.Add(grid_sizer_5, 1, wx.EXPAND, 12)
        sizer_41.Add(self.apply, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        self.SetSizer(sizer_41)
        sizer_41.Fit(self)
        self.Layout()
        # end wxGlade
 
 
    def OnClose(self, event):
        print 'closing win'
        self.Hide()
 
    def run(self, event): # wxGlade: MyFrameDENSITY.<event_handler>
        from pdf2py import readwrite
        from meg import density
        from mri import transform
        from scipy import ndimage
        from nifti import NiftiImage
        from numpy import float32, int16
        print "Event handler `run'"
        print 'dipoles', frame1.points
        report = {}
        #self.points = array([[0,0,0],[10,0,0],[0,20,0]])#DEBUG-----------------
        xyz = transform.meg2mri(frame1.lpa,frame1.rpa,frame1.nas, dipole=frame1.points)
        print xyz
        readwrite.writedata(xyz, os.path.dirname(frame1.mripath)+'/'+'xyz')
        print 'lpa, rpa, nas', frame1.lpa, frame1.rpa, frame1.nas
        print frame1.mr.pixdim
        print frame1.VoxDim
        xyzscaled = (xyz/frame1.VoxDim).T
        print xyzscaled
        d = density.calc(xyz)
        gofscale = float32(self.gofval.GetValue())
        print 'gofscale',gofscale
        s= frame1.gof-gofscale
        sf=(1/(1-gofscale))*s
        ds = d*sf
 
        #ds = d #DEBUG-----------------
 
        report['points'] = frame1.points
        report['gof'] = frame1.gof
        report['density'] = ds
        readwrite.writedata(report, os.path.dirname(frame1.mripath)+'/'+'DensityReport')
 
        z = density.val2img(frame1.mr.data, ds, xyzscaled)
        sigma = float32(self.sigmaval.GetValue())
        print 'sigma',sigma
        #sigma = 3
        print 'filtering 1st dimension'
        f = ndimage.gaussian_filter1d(z, sigma*1/frame1.VoxDim[0], axis=0)
        print 'filtering 2nd dimension'
        f = ndimage.gaussian_filter1d(f, sigma*1/frame1.VoxDim[1], axis=1)
        print 'filtering 3rd dimension'
        f = ndimage.gaussian_filter1d(f, sigma*1/frame1.VoxDim[2], axis=2)
 
        scaledf = int16((z.max()/f.max())*f*1000)
        print 'writing nifti output image'
        overlay = NiftiImage(int16(scaledf))
 
        overlay.setDescription(frame1.mr.description)
        overlay.setFilename(frame1.mr.filename+'dd')
        overlay.setQForm(frame1.mr.getQForm())
 
        text = "Select a save file name"
        suffix='*dd.nii.gz'; filter='*dd.nii.gz'
        dialog = wx.FileDialog(None, text, os.getcwd(), suffix, filter, wx.SAVE)
 
        if dialog.ShowModal() == wx.ID_OK:
            fn = (dialog.GetPaths())
            print fn
            overlay.save(str(fn[0]))
        else:
            print 'Nothing was choosen'
        dialog.Destroy()
 
# end of class MyFrameDENSITY
 
 
 
class Guage(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: Guage.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.gauge_1 = wx.Gauge(self, -1, 10, style=wx.GA_HORIZONTAL|wx.GA_SMOOTH)
 
        self.__set_properties()
        self.__do_layout()
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: Guage.__set_properties
        self.SetTitle("guage")
        self.gauge_1.SetMinSize((400, 20))
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: Guage.__do_layout
        sizer_36 = wx.BoxSizer(wx.VERTICAL)
        sizer_36.Add(self.gauge_1, 42, 0, 0)
        self.SetSizer(sizer_36)
        sizer_36.Fit(self)
        self.Layout()
        # end wxGlade
 
 
    def start(self, value):
        max = value
        app = wx.PySimpleApp()
        dlg = wx.ProgressDialog("Progress dialog","test",maximum = max,style = wx.PD_ELAPSED_TIME| wx.PD_ESTIMATED_TIME| wx.PD_REMAINING_TIME)
 
        keepGoing = True
        skip = False
        count = 0
 
        while keepGoing and count < max:
            count += 1
            #wx.MilliSleep(1000)
            #time.sleep(1)
            newtext = "(before) count: %s, index: %s, skip: %s " % \
            (count, keepGoing, skip)
            #print newtext
            (keepGoing, skip) = dlg.Update(count, newtext)
            newtext = "(after) count: %s, index: %s, skip: %s " % \
            (count, keepGoing, skip)
            #print newtext
        dlg.Destroy()
 
 
 
 
# end of class Guage
 
 
 
class MyFramePROJECTUTILS(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFramePROJECTUTILS.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.frame_ProjectUtils_statusbar = self.CreateStatusBar(1, 0)
        self.tree_ctrl_2 = wx.TreeCtrl(self, -1, style=wx.TR_HAS_BUTTONS|wx.TR_NO_LINES|wx.TR_DEFAULT_STYLE|wx.SUNKEN_BORDER)
 
        self.__set_properties()
        self.__do_layout()
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: MyFramePROJECTUTILS.__set_properties
        self.SetTitle("Project UTILS")
        self.frame_ProjectUtils_statusbar.SetStatusWidths([-1])
        # statusbar fields
        frame_ProjectUtils_statusbar_fields = ["statusbar"]
        for i in range(len(frame_ProjectUtils_statusbar_fields)):
            self.frame_ProjectUtils_statusbar.SetStatusText(frame_ProjectUtils_statusbar_fields[i], i)
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFramePROJECTUTILS.__do_layout
        sizer_39 = wx.BoxSizer(wx.VERTICAL)
        sizer_40 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_40.Add(self.tree_ctrl_2, 1, wx.EXPAND, 0)
        sizer_39.Add(sizer_40, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_39)
        sizer_39.Fit(self)
        self.Layout()
        # end wxGlade
 
# end of class MyFramePROJECTUTILS
 
 
class TAPWIN(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: TAPWIN.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
 
        # Menu Bar
        self.frameTAPWIN_menubar = wx.MenuBar()
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(1, "Generate-Template", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(2, "Save-Template", "", wx.ITEM_NORMAL)
        self.frameTAPWIN_menubar.Append(wxglade_tmp_menu, "File")
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(3, "Avg Contour", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(4, "Avg Projection", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(wx.NewId(), "item", "", wx.ITEM_NORMAL)
        self.frameTAPWIN_menubar.Append(wxglade_tmp_menu, "View")
        self.SetMenuBar(self.frameTAPWIN_menubar)
        # Menu Bar end
        self.frameTAPWIN_statusbar = self.CreateStatusBar(1, 0)
        self.label_01 = wx.StaticText(self, -1, "template")
        self.choice_1 = wx.Choice(self, -1, choices=[])
        self.button_27 = wx.Button(self, -1, "Get Posted Run")
        self.radio_box_3 = wx.RadioBox(self, -1, "realtime view", choices=["average", "continious"], majorDimension=1, style=wx.RA_SPECIFY_ROWS)
        self.text_ctrl_13 = wx.TextCtrl(self, -1, "")
        self.label_23 = wx.StaticText(self, -1, "number of samples\n after trigger to epoch")
        self.static_line_6 = wx.StaticLine(self, -1)
        self.label_26 = wx.StaticText(self, -1, "Display Parameters")
        self.checkbox_11 = wx.CheckBox(self, -1, "contour")
        self.text_ctrl_14 = wx.TextCtrl(self, -1, "")
        self.checkbox_13 = wx.CheckBox(self, -1, "source projection")
        self.text_ctrl_15 = wx.TextCtrl(self, -1, "")
        self.checkbox_12 = wx.CheckBox(self, -1, "butterfly")
        self.checkbox_14 = wx.CheckBox(self, -1, "current source density")
        self.button_28 = wx.ToggleButton(self, -1, "Tap Data")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_MENU, self.maketemplate, id=1)
        self.Bind(wx.EVT_MENU, self.savetemplate, id=2)
        self.Bind(wx.EVT_MENU, self.avgcontour, id=3)
        self.Bind(wx.EVT_MENU, self.avgprojection, id=4)
        self.Bind(wx.EVT_CHOICE, self.selchoice, self.choice_1)
        self.Bind(wx.EVT_BUTTON, self.getposted, self.button_27)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.tapit, self.button_28)
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: TAPWIN.__set_properties
        self.SetTitle("frameTAPWIN")
        self.frameTAPWIN_statusbar.SetStatusWidths([-1])
        # statusbar fields
        frameTAPWIN_statusbar_fields = ["statusbar"]
        for i in range(len(frameTAPWIN_statusbar_fields)):
            self.frameTAPWIN_statusbar.SetStatusText(frameTAPWIN_statusbar_fields[i], i)
        self.radio_box_3.SetSelection(0)
        self.checkbox_11.SetValue(1)
        self.text_ctrl_14.SetToolTipString("ms post trigger")
        self.checkbox_13.Enable(False)
        self.text_ctrl_15.SetToolTipString("ms post trigger")
        self.checkbox_12.Enable(False)
        self.checkbox_12.SetValue(1)
        self.checkbox_14.Enable(False)
        self.checkbox_14.SetValue(1)
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        #self.scantemplates = dbscan.run()
        try:
            pass
            #self.choice_1.SetItems(self.scantemplates)
        except TypeError:
            print 'something wrong with your msw data dir structure'
 
 
    def __do_layout(self):
        # begin wxGlade: TAPWIN.__do_layout
        sizer_31 = wx.BoxSizer(wx.VERTICAL)
        sizer_38_copy_1_copy = wx.BoxSizer(wx.HORIZONTAL)
        sizer_38_copy_1 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_38_copy = wx.BoxSizer(wx.HORIZONTAL)
        sizer_38 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_37 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_35 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_35.Add(self.label_01, 0, wx.ALL, 15)
        sizer_35.Add(self.choice_1, 0, wx.ALL, 16)
        sizer_31.Add(sizer_35, 1, wx.EXPAND, 0)
        sizer_31.Add(self.button_27, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_31.Add(self.radio_box_3, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_37.Add(self.text_ctrl_13, 0, 0, 0)
        sizer_37.Add(self.label_23, 0, 0, 0)
        sizer_31.Add(sizer_37, 1, wx.EXPAND, 0)
        sizer_31.Add(self.static_line_6, 0, wx.EXPAND, 0)
        sizer_31.Add(self.label_26, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 11)
        sizer_38.Add(self.checkbox_11, 0, 0, 0)
        sizer_38.Add(self.text_ctrl_14, 0, 0, 0)
        sizer_31.Add(sizer_38, 0, wx.ALIGN_CENTER_VERTICAL|wx.SHAPED, 0)
        sizer_38_copy.Add(self.checkbox_13, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_38_copy.Add(self.text_ctrl_15, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_31.Add(sizer_38_copy, 0, 0, 0)
        sizer_38_copy_1.Add(self.checkbox_12, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_31.Add(sizer_38_copy_1, 0, 0, 0)
        sizer_38_copy_1_copy.Add(self.checkbox_14, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_31.Add(sizer_38_copy_1_copy, 0, 0, 0)
        sizer_31.Add(self.button_28, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        self.SetSizer(sizer_31)
        sizer_31.Fit(self)
        self.Layout()
        # end wxGlade
 
 
    def OnClose(self, event):
        print 'closing win'
        self.Hide()
 
    def maketemplate(self, event): # wxGlade: TAPWIN.<event_handler>
        print "Event handler `maketemplate' not implemented!"
        frame1.openfile(event)
 
 
    def loadtemplate(self, event): # wxGlade: TAPWIN.<event_handler>
        print "Event handler `loadtemplate' not implemented!"
 
 
    def savetemplate(self, event): # wxGlade: TAPWIN.<event_handler>
        from pdf2py import readwrite
 
        print "Event handler `savetemplate' not implemented"
        os.environ['pymeg']
        taptemplate = readwrite.readdata('taptemplate')
        readwrite.writedata()
 
    def selchoice(self, event): # wxGlade: TAPWIN.<event_handler>
        print "Event handler `selchoice' "
        print 'selecting',self.choice_1.GetStringSelection()
        print self.scantemplates[str(self.choice_1.GetStringSelection())]
        ch = channel.index(self.scantemplates[str(self.choice_1.GetStringSelection())], 'meg')
 
    def getposted(self, event): # wxGlade: TAPWIN.<event_handler>
        print "Event handler `getposted' "
        p = subprocess.Popen('get_posted_sel', stdout=subprocess.PIPE)
        out = p.stdout.readlines()
        s = out[0];
        print 's', s
 
        self.stage = os.environ['STAGE']
        datastring = out[0].strip('\n').replace('/','%').replace('@','/').replace(' ','@')
        self.posted = [self.stage+'/data/sam_data0/'+datastring]
        print 'posted',self.posted
        self.SetStatusText(str(self.posted), 0)
 
 
    def tapit(self, event): # wxGlade: TAPWIN.<event_handler>
        print "Event handler `tapit' "
        if self.button_28.GetValue() == True:
            template = self.scantemplates[str(self.choice_1.GetStringSelection())]
            datafilename = template.split('/')[-1]
            print datafilename
            ch=channel.index(template, 'meg')
            acqfile = self.posted[0]+'/'+datafilename
            print 'acqfile', acqfile
            tapped = tapbuild.get(acqfile, template)
            epochwidth = int(self.text_ctrl_13.GetLineText(0))#20 #number of samples after the trigger you wish to call an epoch
 
            if self.checkbox_11.IsChecked() == True:
                if type(int(self.text_ctrl_14.GetLineText(0))) == int:
                    contour = int(self.text_ctrl_14.GetLineText(0))
                    print 'contour val', contour
            else:
                contour = None
                print 'no contour'
 
            if self.checkbox_13.IsChecked() == True:
                if type(int(self.text_ctrl_15.GetLineText(0))) == int:
                    sp = int(self.text_ctrl_15.GetLineText(0))
                    print 'sp val', sp
            else:
                sp = None
                print 'no sp'
            tapped.avg(epochwidth, ch, contour=None, butterfly=None, csd=None, sp=None)
 
 
    def avgcontour(self, event): # wxGlade: TAPWIN.<event_handler>
        print "Event handler `avgcontour' not implemented"
        event.Skip()
 
    def avgprojection(self, event): # wxGlade: TAPWIN.<event_handler>
        print "Event handler `avgprojection' not implemented"
        event.Skip()
 
# end of class TAPWIN
 
 
class MyFrameBADCH(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameBADCH.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.frameBADCH_statusbar = self.CreateStatusBar(1, 0)
        self.label_1 = wx.StaticText(self, -1, "Frequency based bad channel detection. \n Calculate FFT first on channels of interest.")
        self.static_line_5 = wx.StaticLine(self, -1)
        self.label_25 = wx.StaticText(self, -1, "Difference Ratio:")
        self.text_ctrl_12 = wx.TextCtrl(self, -1, "2")
        self.checkbox_2 = wx.CheckBox(self, -1, "HighPass Cutoff:")
        self.text_ctrl_2 = wx.TextCtrl(self, -1, "3")
        self.label_2 = wx.StaticText(self, -1, "hz")
        self.checkbox_3 = wx.CheckBox(self, -1, "LowPass Cutoff:")
        self.text_ctrl_3 = wx.TextCtrl(self, -1, "200")
        self.label_3 = wx.StaticText(self, -1, "hz")
        self.checkbox_4 = wx.CheckBox(self, -1, "PowerLine Notch:")
        self.label_24 = wx.StaticText(self, -1, "60,120,180")
        self.label_3_copy = wx.StaticText(self, -1, "hz")
        self.button_25 = wx.Button(self, -1, "Calculate Bad Channels")
        self.list_box_3 = wx.ListBox(self, -1, choices=["No Bad Channels Calculated"], style=wx.LB_HSCROLL)
        self.button_26 = wx.Button(self, -1, "Remove Bad Channels from Selected")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_BUTTON, self.calcbadch, self.button_25)
        self.Bind(wx.EVT_BUTTON, self.removechsel, self.button_26)
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: MyFrameBADCH.__set_properties
        self.SetTitle("frameBADCH")
        self.SetBackgroundColour(wx.Colour(143, 143, 188))
        self.frameBADCH_statusbar.SetStatusWidths([-1])
        # statusbar fields
        frameBADCH_statusbar_fields = ["no bad channels removed"]
        for i in range(len(frameBADCH_statusbar_fields)):
            self.frameBADCH_statusbar.SetStatusText(frameBADCH_statusbar_fields[i], i)
        self.checkbox_2.SetValue(1)
        self.checkbox_3.SetValue(1)
        self.checkbox_4.SetValue(1)
        self.list_box_3.SetMinSize((120, 163))
        self.list_box_3.SetSelection(0)
        self.button_26.Enable(False)
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
 
    def __do_layout(self):
        # begin wxGlade: MyFrameBADCH.__do_layout
        sizer_32 = wx.BoxSizer(wx.VERTICAL)
        sizer_33_copy_copy = wx.BoxSizer(wx.HORIZONTAL)
        sizer_33_copy = wx.BoxSizer(wx.HORIZONTAL)
        sizer_33 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_34 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_32.Add(self.label_1, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_32.Add(self.static_line_5, 0, wx.EXPAND, 0)
        sizer_34.Add(self.label_25, 0, 0, 0)
        sizer_34.Add(self.text_ctrl_12, 0, 0, 0)
        sizer_32.Add(sizer_34, 1, wx.EXPAND, 0)
        sizer_33.Add(self.checkbox_2, 0, 0, 0)
        sizer_33.Add(self.text_ctrl_2, 0, 0, 0)
        sizer_33.Add(self.label_2, 0, 0, 0)
        sizer_32.Add(sizer_33, 1, wx.EXPAND, 0)
        sizer_33_copy.Add(self.checkbox_3, 0, 0, 0)
        sizer_33_copy.Add(self.text_ctrl_3, 0, 0, 0)
        sizer_33_copy.Add(self.label_3, 0, 0, 0)
        sizer_32.Add(sizer_33_copy, 1, wx.EXPAND, 0)
        sizer_33_copy_copy.Add(self.checkbox_4, 0, 0, 0)
        sizer_33_copy_copy.Add(self.label_24, 0, 0, 0)
        sizer_33_copy_copy.Add(self.label_3_copy, 0, 0, 0)
        sizer_32.Add(sizer_33_copy_copy, 1, wx.EXPAND, 0)
        sizer_32.Add(self.button_25, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_32.Add(self.list_box_3, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_32.Add(self.button_26, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        self.SetSizer(sizer_32)
        sizer_32.Fit(self)
        self.Layout()
        # end wxGlade
 
    def OnClose(self, event):
        print 'closing win'
        self.Hide()
 
    def calcbadch(self, event): # wxGlade: MyFrameBADCH.<event_handler>
        print "Event handler `calcbadch'"
 
        try:
            frame1.fftpow
        except AttributeError:
            dlg = wx.MessageDialog(self, 'First Calculate FFT.', 'fft error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return
 
        thresh = int(self.text_ctrl_12.GetLineText(0))
        if self.checkbox_2.IsChecked() == True:
            minhz = int(self.text_ctrl_2.GetLineText(0))
            print minhz
        if self.checkbox_3.IsChecked() == True:
            maxhz = int(self.text_ctrl_3.GetLineText(0))
            print maxhz
        if self.checkbox_4.IsChecked() == True:
            powernotch = 'yes'
        else:
            powernotch = 'no'
 
        data,frame1.badch,badmat,badmax= badchannels.calc(frame1.datapdf, frame1.fftpow, frame1.ch, thresh=thresh, freqarray=frame1.fftfreqs, minhz=minhz, maxhz=maxhz, powernotch=powernotch)
        self.list_box_3.SetItems(frame1.badch)
 
 
        self.button_26.Enable(True)
 
 
    def removechsel(self, event): # wxGlade: MyFrameBADCH.<event_handler>
        print "Event handler `removechsel'  "
        for c in range(0,size(frame1.badch)):
            frame1.d.ch2keep(frame1.ch.channelsortedlabels != frame1.badch[c])
            frame1.ch.channelsortedlabels = frame1.ch.channelsortedlabels[frame1.ch.channelsortedlabels != frame1.badch[c]]
            frame1.chantypeind = frame1.chantypeind[frame1.ch.channelsortedlabels != frame1.badch[c]]
            frame1.chanlabel = frame1.chanlabel[frame1.ch.channelsortedlabels != frame1.badch[c]]
            frame1.d.numofchannels = size(frame1.ch.channelsortedlabels)
            frame1.fftpow = frame1.fftpow[:,frame1.ch.channelsortedlabels != frame1.badch[c]]
            frame1.ch.chanlocs = frame1.ch.chanlocs[:, frame1.ch.channelsortedlabels != frame1.badch[c]]
 
        frame1.data_block = frame1.d.data_block
        print shape(eval('frame1.'+frame1.selitem))
        self.SetStatusText("removed channels from: %s" % frame1.selitem)
 
 
 
 
# end of class MyFrameBADCH
 
 
class MyFrameFFT(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameFFT.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.frameFFT_statusbar = self.CreateStatusBar(2, 0)
        self.button_18 = wx.Button(self, -1, "Get Selected Data")
        self.radio_box_1 = wx.RadioBox(self, -1, "FFT from...", choices=["Single Channel", "All Channels", "ICA Component", "Projection"], majorDimension=0, style=wx.RA_SPECIFY_ROWS)
        self.list_box_2 = wx.ListBox(self, -1, choices=["test", "test2"], style=wx.LB_MULTIPLE|wx.LB_EXTENDED|wx.LB_NEEDED_SB)
        self.label_21 = wx.StaticText(self, -1, "number of epochs")
        self.text_ctrl_11 = wx.TextCtrl(self, -1, "")
        self.button_19 = wx.Button(self, -1, "run fft")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_RADIOBOX, self.getselected, self.radio_box_1)
        self.Bind(wx.EVT_LISTBOX_DCLICK, self.getclick, self.list_box_2)
        self.Bind(wx.EVT_LISTBOX, self.getclick, self.list_box_2)
        self.Bind(wx.EVT_BUTTON, self.runfft, self.button_19)
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: MyFrameFFT.__set_properties
        self.SetTitle("FFT config")
        self.SetSize((295, 302))
        self.frameFFT_statusbar.SetStatusWidths([-1, -1])
        # statusbar fields
        frameFFT_statusbar_fields = ["No Data Selected:", "No Items Selected:"]
        for i in range(len(frameFFT_statusbar_fields)):
            self.frameFFT_statusbar.SetStatusText(frameFFT_statusbar_fields[i], i)
        self.button_18.Enable(False)
        self.button_18.Hide()
        self.radio_box_1.SetSelection(0)
        self.list_box_2.SetSelection(0)
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
    def __do_layout(self):
        # begin wxGlade: MyFrameFFT.__do_layout
        sizer_23 = wx.BoxSizer(wx.VERTICAL)
        sizer_26 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_23.Add(self.button_18, 0, 0, 0)
        sizer_26.Add(self.radio_box_1, 0, 0, 0)
        sizer_26.Add(self.list_box_2, 0, wx.ALL|wx.EXPAND, 10)
        sizer_23.Add(sizer_26, 1, wx.EXPAND, 0)
        sizer_23.Add(self.label_21, 0, 0, 0)
        sizer_23.Add(self.text_ctrl_11, 0, wx.BOTTOM, 20)
        sizer_23.Add(self.button_19, 0, 0, 0)
        self.SetSizer(sizer_23)
        self.Layout()
        # end wxGlade
 
    def OnClose(self, event):
        print 'closing win'
        self.Hide()
 
    def getselecteddata(self, event): # wxGlade: MyFrameFFT.<event_handler>
        print "Event handler `getseleted'"
        self.SetStatusText("You selected data: %s" % frame1.selitem, 0)
 
    def getselected(self, event): # wxGlade: MyFrameFFT.<event_handler>
        print "Event handler `getseleted'"
        try:
            frame1.selitem
            self.list_box_2.SetItems(frame1.chanlabel)
        except AttributeError:
            print 'no data selected'
            dlg = wx.MessageDialog(self, 'Select some data first from workspace.', 'data select error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return
 
        self.srate = 1/frame1.p.hdr.header_data.sample_period
        print 'srate of file',self.srate
        if self.radio_box_1.GetSelection() == 0: #single channel
            self.list_box_2.Enable(True)
            self.list_box_2.SetSelection(1, select=True)
 
            self.fftdata = eval('frame1.'+frame1.selitem)[:,frame1.chanlabel == str(frame1.listitem)]
            print shape(self.fftdata)
        if self.radio_box_1.GetSelection() == 1: #all channels
            self.list_box_2.Enable(False)
            print 'fft of all channels from file', str(frame1.selitem)
            self.fftdata = eval('frame1.'+frame1.selitem)[:,:]
            print shape(self.fftdata)
        if self.radio_box_1.GetSelection() == 2: #ica
            pass
        if self.radio_box_1.GetSelection() == 3: #projection
            pass
        self.SetStatusText("You selected: %s" % frame1.selitem)
 
        self.list_box_2.SetItems(frame1.chanlabel)
 
    def getclick(self, event): # wxGlade: MyFrameFFT.<event_handler>
        print "Event handler `getclick' "
        self.listselecteditem = list(self.list_box_2.GetSelections())
        print type(self.listselecteditem), self.listselecteditem
        self.SetStatusText("You selected: %s" % str(self.listselecteditem), 1)
        print 'fft of', frame1.chanlabel[self.listselecteditem]
        self.fftdata = eval('frame1.'+frame1.selitem)[:,self.listselecteditem]
 
    def runfft(self, event): # wxGlade: MyFrameFFT.<event_handler>
        print "Event handler `runfft'"
        print self.text_ctrl_11.GetLineText(0)
        if self.text_ctrl_11.GetLineText(0) != '':
            epochs = int(eval(self.text_ctrl_11.GetLineText(0)))
        else:
            print 'fftepochs',str(eval('frame1.'+frame1.selitem+'epochs'))
            epochs=eval('frame1.'+frame1.selitem+'epochs')
        print 'num of epochs',epochs
        fft = fftmeg.calc(self.fftdata, self.srate, epochs=epochs)
        frame1.fftpow = fft.pow
        frame1.fftfreqs = fft.freq
        frame1.FFT = frame1.tree_ctrl_1.AppendItem(frame1.PROCESSES, 'fftpow')
        print shape(self.fftdata)
        self.Hide()
 
 
# end of class MyFrameFFT
 
 
class MyFrame2DPLOT(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrame2DPLOT.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.frame2DPLOT_statusbar = self.CreateStatusBar(1, 0)
        self.label_28 = wx.StaticText(self, -1, "Plot Data Type")
        self.checkbox_1 = wx.CheckBox(self, -1, "Signal")
        self.checkbox_2 = wx.CheckBox(self, -1, "Reference")
        self.checkbox_3 = wx.CheckBox(self, -1, "Trigger")
        self.checkbox_4 = wx.CheckBox(self, -1, "EEG")
        self.checkbox_5 = wx.CheckBox(self, -1, "Utility")
        self.checkbox_6 = wx.CheckBox(self, -1, "Derived")
        self.checkbox_7 = wx.CheckBox(self, -1, "Shorted")
        self.checkbox_8 = wx.CheckBox(self, -1, "Unknown")
        self.checkbox_10 = wx.CheckBox(self, -1, "FFT")
        self.checkbox_9 = wx.CheckBox(self, -1, "Misc Data")
        self.radio_box_2 = wx.RadioBox(self, -1, "Plot Type", choices=["Butterfly", "Spaced"], majorDimension=0, style=wx.RA_SPECIFY_ROWS)
        self.button_17 = wx.Button(self, -1, "plot")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_BUTTON, self.plotselected, self.button_17)
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
    def __set_properties(self):
        # begin wxGlade: MyFrame2DPLOT.__set_properties
        self.SetTitle("Plot Controller")
        self.frame2DPLOT_statusbar.SetStatusWidths([-1])
        # statusbar fields
        frame2DPLOT_statusbar_fields = ["plot statusbar"]
        for i in range(len(frame2DPLOT_statusbar_fields)):
            self.frame2DPLOT_statusbar.SetStatusText(frame2DPLOT_statusbar_fields[i], i)
        self.checkbox_1.Enable(False)
        self.checkbox_2.Enable(False)
        self.checkbox_3.Enable(False)
        self.checkbox_4.Enable(False)
        self.checkbox_5.Enable(False)
        self.checkbox_6.Enable(False)
        self.checkbox_7.Enable(False)
        self.checkbox_8.Enable(False)
        self.checkbox_10.Enable(False)
        self.radio_box_2.SetSelection(0)
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFrame2DPLOT.__do_layout
        sizer_22 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_27 = wx.BoxSizer(wx.VERTICAL)
        sizer_24 = wx.BoxSizer(wx.VERTICAL)
        sizer_25 = wx.BoxSizer(wx.VERTICAL)
        sizer_25.Add(self.label_28, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5)
        sizer_25.Add(self.checkbox_1, 0, 0, 0)
        sizer_25.Add(self.checkbox_2, 0, 0, 0)
        sizer_25.Add(self.checkbox_3, 0, 0, 0)
        sizer_25.Add(self.checkbox_4, 0, 0, 0)
        sizer_25.Add(self.checkbox_5, 0, 0, 0)
        sizer_25.Add(self.checkbox_6, 0, 0, 0)
        sizer_25.Add(self.checkbox_7, 0, 0, 0)
        sizer_25.Add(self.checkbox_8, 0, 0, 0)
        sizer_25.Add(self.checkbox_10, 0, wx.TOP, 10)
        sizer_25.Add(self.checkbox_9, 0, wx.BOTTOM, 10)
        sizer_22.Add(sizer_25, 1, wx.EXPAND, 0)
        sizer_24.Add(self.radio_box_2, 0, wx.TOP|wx.BOTTOM|wx.ALIGN_BOTTOM|wx.ALIGN_CENTER_HORIZONTAL, 29)
        sizer_22.Add(sizer_24, 1, wx.EXPAND, 0)
        sizer_27.Add(self.button_17, 0, wx.ALL|wx.ALIGN_BOTTOM|wx.ALIGN_CENTER_HORIZONTAL, 9)
        sizer_22.Add(sizer_27, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_22)
        sizer_22.Fit(self)
        self.Layout()
        # end wxGlade
 
    def OnClose(self, event):
        print 'closing win'
        #del self.tbIcon
        self.Hide()
 
    def typeselect(self, event): # wxGlade: MyFrame2DPLOT.<event_handler>
        print "Event handler `typeselect' "
        pass
 
    def checkandclear(self, event): # check and clear
        print "Event handler `checkandclear' "
        pass
 
 
    def plotselected(self, event): # wxGlade: MyFrame2DPLOT.<event_handler>
        print "Event handler `plotselected'"
        ind2plot = [];
        data2plot = eval('frame1.'+frame1.selitem)
        if size(data2plot,0) > 10000:
            print 'too many pnts to plot'
            return
        self.SetStatusText("selected to plot: %s" % frame1.selitem)
        self.Hide()
 
        def event_response(event):
            print event.name
            print event.xdata
            frame1.SetStatusText("You selected: %s" % event.xdata)
            indsel = fftmeg.nearest(frame1.timeaxis, event.xdata)
            print 'you selected index value',indsel
            event.xdata = indsel[0]
            frame1.SetPyData(int(event.xdata), data=data)
 
 
        figure();
        try:
            numplots = frame1.numplots
        except AttributeError:
            numplots = 1
 
        if self.checkbox_9.IsChecked() == True:
            numplots = 1
 
        print numplots
 
        print 'timeaxis shape',shape(frame1.timeaxis)
        for i in range(0, numplots):
            startval = (i)*frame1.timeaxis.size
            endval = (i+1)*frame1.timeaxis.size
            subplot(1,numplots,i+1)
            print i,startval,endval
            if self.checkbox_1.IsChecked() == True: frame1.chindex = frame1.chantypeind == 'meg'; plot(frame1.timeaxis, data2plot[startval:endval,frame1.chindex]);
            if self.checkbox_2.IsChecked() == True: frame1.chindex = frame1.chantypeind == 'ref'; plot(frame1.timeaxis, data2plot[startval:endval,frame1.chindex]);#plot(data2plot[:,frame1.chantypeind == 'ref']);
            if self.checkbox_3.IsChecked() == True: frame1.chindex = frame1.chantypeind == 'trig'; plot(frame1.timeaxis, data2plot[startval:endval,frame1.chindex]);#plot(data2plot[:,frame1.chantypeind == 'trig']);
            if self.checkbox_4.IsChecked() == True: frame1.chindex = frame1.chantypeind == 'eeg'; plot(frame1.timeaxis, data2plot[startval:endval,frame1.chindex]);#plot(data2plot[:,frame1.chantypeind == 'eeg']);
            if self.checkbox_5.IsChecked() == True: frame1.chindex = frame1.chantypeind == 'util'; plot(frame1.timeaxis, data2plot[startval:endval,frame1.chindex]);#plot(data2plot[:,frame1.chantypeind == 'util']);
            if self.checkbox_6.IsChecked() == True: frame1.chindex = frame1.chantypeind == 'derived'; plot(frame1.timeaxis, data2plot[startval:endval,frame1.chindex]);#plot(data2plot[:,frame1.chantypeind == 'derived']);
            if self.checkbox_7.IsChecked() == True: frame1.chindex = frame1.chantypeind == 'shorted'; plot(frame1.timeaxis, data2plot[startval:endval,frame1.chindex]);#plot(data2plot[:,frame1.chantypeind == 'shorted']);
            if self.checkbox_8.IsChecked() == True: frame1.chindex = frame1.chantypeind == 'unknown'; plot(frame1.timeaxis, data2plot[startval:endval,frame1.chindex]);#plot(data2plot[:,frame1.chantypeind == 'unknown']);
            if self.checkbox_9.IsChecked() == True: plot(data2plot[:,:]);#plot(data2plot[:,frame1.chantypeind == 'unknown']);
            if self.checkbox_10.IsChecked() == True: plot(frame1.timeaxis,data2plot[:,:]);
            #if i > 0: setp(gca(), 'yticklabels', [])
        cid = connect('button_press_event', event_response)
        subplots_adjust(wspace=0)
        show()
# end of class MyFrame2DPLOT
 
 
class MyFrameCHAN(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameCHAN.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.label_20 = wx.StaticText(self, -1, "Load Channels")
        self.signalbutton = wx.ToggleButton(self, -1, "signal")
        self.refbutton = wx.ToggleButton(self, -1, "reference")
        self.trigbutton = wx.ToggleButton(self, -1, "trigger")
        self.eegbutton = wx.ToggleButton(self, -1, "eeg")
        self.utilbutton = wx.ToggleButton(self, -1, "utility")
        self.derivedbutton = wx.ToggleButton(self, -1, "derived")
        self.shortedbutton = wx.ToggleButton(self, -1, "shorted")
        self.unknownbutton = wx.ToggleButton(self, -1, "unknown")
        self.editlabel = wx.StaticText(self, -1, "Edit Channels")
        self.list_ctrl_2 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.addchan = wx.StaticText(self, -1, "added channels")
        self.list_ctrl_3 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.button_24 = wx.Button(self, -1, "clear channels")
        self.getchanindices = wx.Button(self, -1, "Load Channels")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_TOGGLEBUTTON, self.getchind, self.signalbutton)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.getchind, self.refbutton)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.getchind, self.trigbutton)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.getchind, self.eegbutton)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.getchind, self.utilbutton)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.getchind, self.derivedbutton)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.getchind, self.shortedbutton)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.getchind, self.unknownbutton)
        self.Bind(wx.EVT_BUTTON, self.delchannels, self.button_24)
        self.Bind(wx.EVT_BUTTON, self.loadchannels, self.getchanindices)
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
 
    def __set_properties(self):
        # begin wxGlade: MyFrameCHAN.__set_properties
        self.SetTitle("Load Channels")
        self.SetBackgroundColour(wx.Colour(143, 143, 188))
        self.signalbutton.SetFocus()
        self.getchanindices.SetBackgroundColour(wx.Colour(182, 182, 238))
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFrameCHAN.__do_layout
        sizer_17 = wx.BoxSizer(wx.VERTICAL)
        sizer_19 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_21 = wx.BoxSizer(wx.VERTICAL)
        sizer_20 = wx.BoxSizer(wx.HORIZONTAL)
        grid_sizer_4 = wx.GridSizer(8, 1, 0, 0)
        sizer_17.Add(self.label_20, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 20)
        grid_sizer_4.Add(self.signalbutton, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_4.Add(self.refbutton, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_4.Add(self.trigbutton, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_4.Add(self.eegbutton, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_4.Add(self.utilbutton, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_4.Add(self.derivedbutton, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_4.Add(self.shortedbutton, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_4.Add(self.unknownbutton, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_20.Add(grid_sizer_4, 1, wx.EXPAND, 0)
        sizer_19.Add(sizer_20, 1, wx.EXPAND, 0)
        sizer_21.Add(self.editlabel, 0, 0, 0)
        sizer_21.Add(self.list_ctrl_2, 1, wx.EXPAND, 0)
        sizer_21.Add(self.addchan, 0, 0, 0)
        sizer_21.Add(self.list_ctrl_3, 1, wx.EXPAND, 0)
        sizer_19.Add(sizer_21, 1, wx.EXPAND, 0)
        sizer_17.Add(sizer_19, 1, wx.EXPAND, 0)
        sizer_17.Add(self.button_24, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_17.Add(self.getchanindices, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 19)
        self.SetSizer(sizer_17)
        sizer_17.Fit(self)
        self.Layout()
        # end wxGlade
 
    def OnClose(self, event):
        print 'closing win'
        self.Hide()
 
    def getchind(self, event, command='none'): # wxGlade: MyFrameCHAN.<event_handler>
        print "Event handler `getchind'"
 
        frame2DPLOT.Show()
        frame2DPLOT.Hide()
 
        frameCHAN.chdict = {};
 
        if self.signalbutton.GetValue() == True:
            frame1.meg = channel.index(frame1.datapdf, 'meg'); frameCHAN.chdict['meg'] = 'true'; frame2DPLOT.checkbox_1.Enable(True)
        if self.refbutton.GetValue() == True:
            frame1.ref = channel.index(frame1.datapdf, 'ref'); frameCHAN.chdict['ref'] = 'true'; frame2DPLOT.checkbox_2.Enable(True)
        if self.trigbutton.GetValue() == True:
            frame1.trig = channel.index(frame1.datapdf, 'trig'); frameCHAN.chdict['trig'] = 'true'; frame2DPLOT.checkbox_3.Enable(True)
        if self.eegbutton.GetValue() == True:
            frame1.eeg = channel.index(frame1.datapdf, 'eeg'); frameCHAN.chdict['eeg'] = 'true'; frame2DPLOT.checkbox_4.Enable(True)
        if self.utilbutton.GetValue() == True:
            frame1.util = channel.index(frame1.datapdf, 'util'); frameCHAN.chdict['util'] = 'true'; frame2DPLOT.checkbox_5.Enable(True)
        if self.derivedbutton.GetValue() == True:
            frame1.derived = channel.index(frame1.datapdf, 'derived'); frameCHAN.chdict['derived'] = 'true'; frame2DPLOT.checkbox_6.Enable(True)
        if self.shortedbutton.GetValue() == True:
            frame1.shorted = channel.index(frame1.datapdf, 'shorted'); frameCHAN.chdict['shorted'] = 'true'; frame2DPLOT.checkbox_7.Enable(True)
        if self.shortedbutton.GetValue() == True:
            frame1.shorted = channel.index(frame1.datapdf, 'shorted'); frameCHAN.chdict['shorted'] = 'true'; frame2DPLOT.checkbox_7.Enable(True)
 
    def loadchannels(self, event): # wxGlade: MyFrameCHAN.<event_handler>
        print "Event handler `loadchannels' "
 
        try:
            frame1.tree_ctrl_1.Delete(frame1.CHANNELS)
        except AttributeError:
            print 'cant delete item'
 
        #GET CHANNEL INDICES BY TYPE (ex MEG or REF)
        chanindices = []; chantype = []; chanlabel = [];
        print frameCHAN.chdict
        for type in frameCHAN.chdict: #concatanate channels
            chanindices.append(eval('frame1.'+type+'.channelindexhdr'))
            chantype.append(type)
            chanlabel.append(eval('frame1.'+type+'.channelsortedlabels'))
            frame1.tree_ctrl_1.AppendItem(frame1.DATA, str(type))
 
            #locals()[type] = 1
 
 
        chantypeind = []
        chanlabelsind = []
 
        for t in range(0, len(frameCHAN.chdict)):
            for i in range(0, len(chanindices[t])):
                chantypeind.append(chantype[t])
                #chanlabelsind.append(chanlabel[i])
 
        frame1.chanlabel = hstack(chanlabel)
 
        frame1.chantype = chantype
        chantypeind = array(chantypeind)
        frame1.chantypeind = chantypeind
        chanind = hstack(chanindices)
 
        #READ THE DATA
        frame1.d.getdata(0, frame1.d.pnts_in_file, chindex=chanind)#chindex=frame1.ch.channelindexhdr)
        frame1.SetPyData(event, 'd')
        frame1.data_block = frame1.d.data_block
        frame1.megdataepochs = frame1.d.numofepochs
        frame1.timeaxis = frame1.d.wintime
 
        #get meg channels for leadfield
        frame1.ch = channel.index(frame1.datapdf, 'meg')
        self.Hide()
 
    def delchannels(self, event): # wxGlade: MyFrameCHAN.<event_handler>
        print "Event handler `delchannels'  "
        del frameCHAN.chdict
 
# end of class MyFrameCHAN
 
 
class MyFrameCUT(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameCUT.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.frameCUT_statusbar = self.CreateStatusBar(1, 0)
        self.label_16 = wx.StaticText(self, -1, "Resize data relative to ...")
        self.combo_box_6 = wx.ComboBox(self, -1, choices=["Epochs", "Trigger"], style=wx.CB_DROPDOWN)
        self.resizewhat = wx.StaticText(self, -1, "Resize What...")
        self.combo_box_7 = wx.ComboBox(self, -1, choices=[], style=wx.CB_DROPDOWN)
        self.static_line_3 = wx.StaticLine(self, -1)
        self.label_17 = wx.StaticText(self, -1, "")
        self.label_18 = wx.StaticText(self, -1, "window start(ms)")
        self.text_ctrl_6 = wx.TextCtrl(self, -1, "")
        self.label_19 = wx.StaticText(self, -1, "window end(ms)")
        self.text_ctrl_7 = wx.TextCtrl(self, -1, "")
        self.button_15 = wx.Button(self, -1, "Epoch DATA")
        self.button_16 = wx.Button(self, -1, "Average DATA")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_TEXT, self.cuttype, self.combo_box_6)
        self.Bind(wx.EVT_BUTTON, self.epochdata, self.button_15)
        self.Bind(wx.EVT_BUTTON, self.averagedata, self.button_16)
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
 
    def __set_properties(self):
        # begin wxGlade: MyFrameCUT.__set_properties
        self.SetTitle("Resize Data")
        self.frameCUT_statusbar.SetStatusWidths([-1])
        # statusbar fields
        frameCUT_statusbar_fields = ["frameAVG_statusbar"]
        for i in range(len(frameCUT_statusbar_fields)):
            self.frameCUT_statusbar.SetStatusText(frameCUT_statusbar_fields[i], i)
        self.combo_box_6.SetToolTipString("select method to average. Epoch means file is already epoched")
        self.combo_box_6.SetSelection(-1)
        self.label_17.SetMinSize((300, 157))
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFrameCUT.__do_layout
        sizer_13 = wx.BoxSizer(wx.VERTICAL)
        sizer_18 = wx.BoxSizer(wx.HORIZONTAL)
        grid_sizer_3 = wx.GridSizer(2, 2, 2, 2)
        sizer_13.Add(self.label_16, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 12)
        sizer_13.Add(self.combo_box_6, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5)
        sizer_13.Add(self.resizewhat, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_13.Add(self.combo_box_7, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_13.Add(self.static_line_3, 0, wx.EXPAND, 0)
        sizer_13.Add(self.label_17, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 17)
        grid_sizer_3.Add(self.label_18, 0, wx.EXPAND, 0)
        grid_sizer_3.Add(self.text_ctrl_6, 0, wx.EXPAND, 0)
        grid_sizer_3.Add(self.label_19, 0, wx.EXPAND, 0)
        grid_sizer_3.Add(self.text_ctrl_7, 0, wx.EXPAND, 0)
        sizer_13.Add(grid_sizer_3, 1, wx.EXPAND, 0)
        sizer_18.Add(self.button_15, 0, wx.ALL, 11)
        sizer_18.Add(self.button_16, 0, wx.ALL, 11)
        sizer_13.Add(sizer_18, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_13)
        sizer_13.Fit(self)
        self.Layout()
        # end wxGlade
 
    def OnClose(self, event):
        print 'closing win'
        self.Hide()
 
    def cuttype(self, event): # wxGlade: MyFrameCUT.<event_handler>
        print "Event handler `cuttype' not implemented"
        self.populatebox()
        self.sel = self.combo_box_6.GetStringSelection()
 
        if frame1.p.hdr.header_data.total_epochs[0] > 1: #epoched
            self.epochduration = frame1.p.hdr.epoch_data[0].epoch_duration[0]*1000
            if frame1.p.hdr.event_data[0].start_lat == 0:
                self.label_17.SetLabel('if using trigger to average, start must be greater than 0, as the trigger appears to coincide with begin of each epoch')
        else:
            print 'either average or continious file'
            self.epochduration = frame1.d.pnts_in_file*frame1.p.hdr.header_data.sample_period*1000
 
        self.text_ctrl_6.SetValue('0')
        self.text_ctrl_7.SetValue(str(self.epochduration))
 
        if self.combo_box_6.GetStringSelection() == 'Epochs':
            print 'you selected epochs'
            if frame1.p.hdr.header_data.total_epochs[0] == 1:
                dlg = wx.MessageDialog(self, 'I dont think you meant to do that... File doesnt appear to be an epoch file', 'epoch error', wx.OK|wx.ICON_INFORMATION)
                dlg.ShowModal()
                dlg.Destroy()
                return
            else:
                frame1.ind = arange(0, frame1.d.pnts_in_file, frame1.d.wintime.shape[0])
            wins = self.text_ctrl_6.GetLineText(0)
            wine = self.text_ctrl_7.GetLineText(0)
 
        if self.combo_box_6.GetStringSelection() == 'Trigger':
            print 'you selected trigger based epoching'
            try:
                wins = frame1.ind - int(eval(self.text_ctrl_6.GetLineText(0)))
                wine = frame1.ind - int(eval(self.text_ctrl_7.GetLineText(0)))
                print wins, wine
                print frame1.ind
                self.timeaxis = arange(wins,wine,frame1.p.hdr.header_data.sample_period)
                print 'timeaxis',shape(self.timeaxis)
 
            except AttributeError:
                dlg = wx.MessageDialog(self, 'I think you mean to get triggers first...', 'trigger error', wx.OK|wx.ICON_INFORMATION)
                dlg.ShowModal()
                dlg.Destroy()
                frameTRIG.Show()
                return
 
    def averagedata(self, event): # wxGlade: MyFrameCUT.<event_handler>
        print "Event handler `averagedata' "
        self.epochdata(event)
        #frame1.avg = averager.on_epochs(frame1.d.data_block, frame1.p.hdr.header_data.total_epochs[0], self.skipfrom, self.skipto)
        reshapedepochs = frame1.epoch.reshape(frame1.epochtrials,frame1.epochpnts,  frame1.epochnumch)
        frame1.avg = mean(reshapedepochs, 0)
        print 'avg shape',frame1.avg.shape
        frame1.AVG = frame1.tree_ctrl_1.AppendItem(frame1.PROCESSES, 'avg')
        self.Hide()
 
    def populatebox(self): # wxGlade: MyFrameCUT.<event_handler>
        print "Event handler `populatebox' "
        self.combo_box_7.SetItems(frame1.chantype)
 
    def epochdata(self, event): # wxGlade: MyFrameCUT.<event_handler>
        print "Event handler `epochdata' "
        wins = self.text_ctrl_6.GetLineText(0)
        wine = self.text_ctrl_7.GetLineText(0)
        self.skipfrom = int(eval(wins))/(self.epochduration*frame1.p.hdr.header_data.sample_period)
        self.skipto = int(eval(wine))/(self.epochduration*frame1.p.hdr.header_data.sample_period)
        self.indfrom = int((eval(wins))/1000.0 * (1/frame1.p.hdr.header_data.sample_period))
        self.indto = int((eval(wine))/1000.0 * (1/frame1.p.hdr.header_data.sample_period))
        print self.indfrom, self.indto
 
        print int(eval(wine)), self.epochduration, frame1.p.hdr.header_data.sample_period
        print self.skipfrom,self.skipto
 
 
        epochs = size(frame1.ind)
        print epochs, shape(frame1.d.data_block)
 
        #if epoch
        if frame1.p.hdr.header_data.total_epochs[0] > 1:
            self.cutdata = eval('frame1.'+frame1.selitem)[:,:]
            frame1.epoch = epoch.epochs(self.cutdata, epochs, self.skipfrom, self.skipto)
        #if contin
        if frame1.p.hdr.header_data.total_epochs[0] == 1:
            self.cutdata = eval('frame1.'+frame1.selitem)[:,:]
            frame1.epoch = epoch.cont(self.cutdata, epochs, self.indfrom, self.indto, frame1.ind)
 
        frame1.epochtrials = epochs
        frame1.epochepochs = epochs
        frame1.epochpnts = self.indto - self.indfrom
        frame1.epochnumch = size(frame1.d.data_block,1)
        print shape(frame1.epoch)
        frame1.EPOCHED = frame1.tree_ctrl_1.AppendItem(frame1.PROCESSES, 'epoch')
        self.Hide()
 
# end of class MyFrameCUT
 
 
class MyFrameEPOCH(wx.Frame):
    def __init__(self, *args, **kwds):
        # content of this block not found: did you rename this class?
        pass
 
    def __set_properties(self):
        # content of this block not found: did you rename this class?
        pass
 
    def __do_layout(self):
        # content of this block not found: did you rename this class?
        pass
 
    def getaveragetype(self, event): # wxGlade: MyFrameEPOCH.<event_handler>
        print "Event handler `getaveragetype' not implemented!"
        event.Skip()
 
    def epochdata(self, event): # wxGlade: MyFrameEPOCH.<event_handler>
        print "Event handler `epochdata' "
        print self.combo_box_6_copy.GetStringSelection()
        if self.combo_box_6_copy.GetStringSelection() == 'Trigger':
            pass
 
 
 
# end of class MyFrameEPOCH
 
 
class MyFrameTRIG(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameTRIG.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.frameTRIG_statusbar = self.CreateStatusBar(1, 0)
        self.label_15 = wx.StaticText(self, -1, "Select Trigger Type")
        self.combo_box_4 = wx.ComboBox(self, -1, choices=["", "TRIGGER", "RESPONSE"], style=wx.CB_DROPDOWN)
        self.combo_box_5 = wx.ComboBox(self, -1, choices=[], style=wx.CB_DROPDOWN)
        self.button_14 = wx.Button(self, -1, "Get Triggers")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_TEXT, self.gettrigtype, self.combo_box_4)
        self.Bind(wx.EVT_TEXT, self.getind, self.combo_box_5)
        self.Bind(wx.EVT_BUTTON, self.settrig, self.button_14)
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
 
    def __set_properties(self):
        # begin wxGlade: MyFrameTRIG.__set_properties
        self.SetTitle("Triggers")
        self.frameTRIG_statusbar.SetStatusWidths([-1])
        # statusbar fields
        frameTRIG_statusbar_fields = ["Number of Triggers: NA"]
        for i in range(len(frameTRIG_statusbar_fields)):
            self.frameTRIG_statusbar.SetStatusText(frameTRIG_statusbar_fields[i], i)
        self.combo_box_4.SetSelection(0)
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFrameTRIG.__do_layout
        sizer_14 = wx.BoxSizer(wx.VERTICAL)
        sizer_14.Add(self.label_15, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 12)
        sizer_14.Add(self.combo_box_4, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 10)
        sizer_14.Add(self.combo_box_5, 0, wx.BOTTOM|wx.ALIGN_CENTER_HORIZONTAL, 14)
        sizer_14.Add(self.button_14, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        self.SetSizer(sizer_14)
        sizer_14.Fit(self)
        self.Layout()
        # end wxGlade
 
    def OnClose(self, event):
        print 'closing win'
        self.Hide()
 
    def gettrigtype(self, event): # wxGlade: MyFrameTRIG.<event_handler>
        print "Event handler `gettrigtype'"
        if self.combo_box_4.GetCurrentSelection() == 1:
            self.uvals,self.nzind,self.nz  = trigger.vals(frame1.d.data_block[:,frame1.chantypeind == 'trig'])# = channel.index(frame1.datapdf, 'TRIGGER')
 
        print self.uvals
        for t in self.uvals:
            self.combo_box_5.AppendItems([str([t])])
    def getind(self, event): # wxGlade: MyFrameTRIG.<event_handler>
        print "Event handler `getind' "
        frame1.sel =  self.combo_box_5.GetStringSelection()
        ind = trigger.ind(frame1.sel, self.nzind,self.nz )
        self.SetStatusText("Number of Triggers: "+str(len(ind)))
 
 
 
    def settrig(self, event): # wxGlade: MyFrameTRIG.<event_handler>
        from pdf2py import readwrite
        print "Event handler `settrig' "
        frame1.ind = trigger.ind(frame1.sel, self.nzind,self.nz )
        frame1.TRIG = frame1.tree_ctrl_1.AppendItem(frame1.SESSION, 'Trigger')
        readwrite.writedata(frame1.ind, '/home/danc/trig')
        self.Hide()
 
# end of class MyFrameTRIG
 
 
class MyFrameCH(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameCH.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.combo_box_3 = wx.ComboBox(self, -1, choices=["MEG", "TRIGGER", "REFERENCE", "EEG", "UTIL", "DERIVED", "SHORTED", "EXTERNAL"], style=wx.CB_DROPDOWN|wx.CB_DROPDOWN)
        self.button_13 = wx.Button(self, -1, "Get Channels")
        self.list_box_1 = wx.ListBox(self, -1, choices=[])
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_TEXT, self.getchoice, self.combo_box_3)
        self.Bind(wx.EVT_BUTTON, self.getchtype, self.button_13)
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
 
    def __set_properties(self):
        # begin wxGlade: MyFrameCH.__set_properties
        self.SetTitle("Load Channels")
        self.combo_box_3.SetSelection(0)
        self.list_box_1.SetMinSize((139, 263))
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFrameCH.__do_layout
        sizer_15 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_16 = wx.BoxSizer(wx.VERTICAL)
        sizer_16.Add(self.combo_box_3, 0, wx.ALL, 8)
        sizer_16.Add(self.button_13, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 9)
        sizer_15.Add(sizer_16, 1, wx.EXPAND, 0)
        sizer_15.Add(self.list_box_1, 0, 0, 0)
        self.SetSizer(sizer_15)
        sizer_15.Fit(self)
        self.Layout()
        # end wxGlade
 
    def OnClose(self, event):
        print 'closing win'
        #del self.tbIcon
        self.Hide()
 
    def getchoice(self, event): # wxGlade: MyFrameCH.<event_handler>
        print "Event handler `getchoice' "
        event.Skip()
 
    def getchtype(self, event): # wxGlade: MyFrameCH.<event_handler>
        print "Event handler `getchtype' "
        if self.combo_box_3.GetCurrentSelection() == 0:
            frame1.ch = channel.index(frame1.datapdf, 'meg')
        if self.combo_box_3.GetCurrentSelection() == 1:
            frame1.ch = channel.index(frame1.datapdf, 'trig')
        if self.combo_box_3.GetCurrentSelection() == 2:
            frame1.ch = channel.index(frame1.datapdf, 'ref')
        if self.combo_box_3.GetCurrentSelection() == 3:
            frame1.ch = channel.index(frame1.datapdf, 'eeg')
        if self.combo_box_3.GetCurrentSelection() == 4:
            frame1.ch = channel.index(frame1.datapdf, 'util')
        if self.combo_box_3.GetCurrentSelection() == 5:
            frame1.ch = channel.index(frame1.datapdf, 'derived')
        if self.combo_box_3.GetCurrentSelection() == 6:
            frame1.ch = channel.index(frame1.datapdf, 'shorted')
        if self.combo_box_3.GetCurrentSelection() == 7:
            frame1.ch = channel.index(frame1.datapdf, 'ext')
 
        #READ THE DATA
        frame1.d.getdata(0, frame1.d.pnts_in_file, chindex=frame1.ch.channelindexhdr)
        frame1.SetPyData(event, 'd')
 
        try:
            frame1.tree_ctrl_1.Delete(frame1.CHANNEL)
        except AttributeError:
            print 'cant delete item'
        frame1.CHANNEL = frame1.tree_ctrl_1.AppendItem(frame1.MEGDATA, 'Channels')
        self.Hide()
 
# end of class MyFrameCH
 
 
class MyFrameAVG(wx.Frame):
    def __init__(self, *args, **kwds):
        # content of this block not found: did you rename this class?
        pass
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
    def __set_properties(self):
        # content of this block not found: did you rename this class?
        pass
 
    def __do_layout(self):
        # content of this block not found: did you rename this class?
        pass
 
    def averagedata(self, event): # wxGlade: MyFrameAVG.<event_handler>
        print "Event handler `averagedata' not implemented"
        event.Skip()
 
# end of class MyFrameAVG
 
 
class MyFrameSP(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameSP.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.frameSP_statusbar = self.CreateStatusBar(2, 0)
        self.label_10 = wx.StaticText(self, -1, "Source Projection Method", style=wx.ALIGN_CENTRE)
        self.label_12 = wx.StaticText(self, -1, "Manual:")
        self.label_11 = wx.StaticText(self, -1, "x,y,z")
        self.text_ctrl_3 = wx.TextCtrl(self, -1, "")
        self.label_13 = wx.StaticText(self, -1, "qx,qz,qz")
        self.text_ctrl_4 = wx.TextCtrl(self, -1, "")
        self.button_12 = wx.Button(self, -1, "Run Projection from Manual Specs")
        self.static_line_4 = wx.StaticLine(self, -1)
        self.label_14 = wx.StaticText(self, -1, "Custom Weight From Selection:")
        self.label_22 = wx.StaticText(self, -1, "make sure to select new data from \n the main window, if you wish to \n apply weights to it!")
        self.button_20 = wx.ToggleButton(self, -1, "Generate Weight from Plot")
        self.text_ctrl_9 = wx.TextCtrl(self, -1, "seconds")
        self.text_ctrl_10 = wx.TextCtrl(self, -1, "epochs")
        self.button_22 = wx.Button(self, -1, "Weights from Time")
        self.text_ctrl_8 = wx.TextCtrl(self, -1, "freq in hz")
        self.button_23 = wx.Button(self, -1, "Weights from Freq")
        self.combo_box_2 = wx.ComboBox(self, -1, choices=["", "Selection", "MEG data"], style=wx.CB_DROPDOWN)
        self.button_21 = wx.Button(self, -1, "Get Selected Data to Apply Weights")
        self.button_3 = wx.Button(self, -1, "Apply Weights to Posted")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_BUTTON, self.getmanualsp, self.button_12)
        self.Bind(wx.EVT_TOGGLEBUTTON, self.pickfromplot, self.button_20)
        self.Bind(wx.EVT_BUTTON, self.manualtime, self.button_22)
        self.Bind(wx.EVT_BUTTON, self.manualfreq, self.button_23)
        self.Bind(wx.EVT_TEXT, self.getchoice, self.combo_box_2)
        self.Bind(wx.EVT_COMBOBOX, self.getchoice, self.combo_box_2)
        self.Bind(wx.EVT_BUTTON, self.refreshstatus, self.button_21)
        self.Bind(wx.EVT_BUTTON, self.getweightchoice, self.button_3)
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: MyFrameSP.__set_properties
        self.SetTitle("Source Projection")
        self.SetBackgroundColour(wx.Colour(143, 143, 188))
        self.frameSP_statusbar.SetStatusWidths([-1, -1])
        # statusbar fields
        frameSP_statusbar_fields = ["No Weights:", "Data Posted:"]
        for i in range(len(frameSP_statusbar_fields)):
            self.frameSP_statusbar.SetStatusText(frameSP_statusbar_fields[i], i)
        self.label_10.SetFont(wx.Font(12, wx.MODERN, wx.ITALIC, wx.BOLD, 0, "Sans"))
        self.label_12.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 1, ""))
        self.label_14.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 1, ""))
        self.combo_box_2.SetBackgroundColour(wx.Colour(207, 194, 129))
        self.combo_box_2.Enable(False)
        self.combo_box_2.Hide()
        self.combo_box_2.SetSelection(-1)
        self.button_3.Enable(False)
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFrameSP.__do_layout
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_30 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_29 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_28 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_12 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_2.Add(self.label_10, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 7)
        sizer_2.Add(self.label_12, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_12.Add(self.label_11, 0, 0, 0)
        sizer_12.Add(self.text_ctrl_3, 0, 0, 0)
        sizer_12.Add(self.label_13, 0, 0, 0)
        sizer_12.Add(self.text_ctrl_4, 0, 0, 0)
        sizer_2.Add(sizer_12, 1, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 10)
        sizer_2.Add(self.button_12, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_2.Add(self.static_line_4, 0, wx.ALL|wx.EXPAND, 22)
        sizer_2.Add(self.label_14, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_28.Add(self.label_22, 0, wx.BOTTOM, 16)
        sizer_28.Add(self.button_20, 0, 0, 0)
        sizer_2.Add(sizer_28, 1, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_29.Add(self.text_ctrl_9, 0, 0, 0)
        sizer_29.Add(self.text_ctrl_10, 0, 0, 0)
        sizer_29.Add(self.button_22, 0, 0, 0)
        sizer_2.Add(sizer_29, 1, 0, 0)
        sizer_30.Add(self.text_ctrl_8, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_30.Add(self.button_23, 0, 0, 0)
        sizer_2.Add(sizer_30, 1, 0, 0)
        sizer_2.Add(self.combo_box_2, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_2.Add(self.button_21, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 16)
        sizer_2.Add(self.button_3, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 10)
        self.SetSizer(sizer_2)
        sizer_2.Fit(self)
        self.Layout()
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
    def OnClose(self, event):
        print 'closing win'
        #del self.tbIcon
        self.Hide()
 
    def getmanualsp(self, event): # wxGlade: MyFrameSP.<event_handler>
        print "Event handler `getmanualsp' not implemented"
        self.text_ctrl_4.GetLineText(0)
        self.text_ctrl_3.GetLineText(0)
 
    def getweightchoice(self, event): # wxGlade: MyFrameSP.<event_handler>
        print "Event handler `getweightchoice' not implemented"
        from pdf2py import readwrite
        weight=eval('frame1.'+frame1.selitem+'[frame1.x,frame1.chindex]')
        self.SetStatusText("weight size: %s" % shape(weight), 0)
        frame1.projection = sourcespaceprojection.calc(eval('frame1.'+frame1.selitem+'[:,frame1.chindex]'), weight=weight)
        readwrite.writedata(frame1.projection, '/home/danc/spdata')
        print shape(frame1.projection), type(frame1.projection)
        frame1.SetStatusText("Projection Done")
        frame1.PROJECTION = frame1.tree_ctrl_1.AppendItem(frame1.PROCESSES, 'projection')
        self.Hide()
 
    def getchoice(self, event): # wxGlade: MyFrameSP.<event_handler>
        print "Event handler `getchoice' not implemented"
        print self.combo_box_2.GetStringSelection() #== 'MEG data':
 
        if self.combo_box_2.GetStringSelection() == 'Selection':
            try:
                frame1.plot2ddata(eval('frame1.'+frame1.selitem)) #check if something selected
            except AttributeError:
                print 'nothing selected'
                dlg = wx.MessageDialog(self, 'Nothing workspace data selected from PyMEG left window. Do that first', 'Selection error', wx.OK|wx.ICON_INFORMATION)
                dlg.ShowModal()
                dlg.Destroy()
                self.combo_box_2.SetSelection(0)
 
        if self.combo_box_2.GetStringSelection() == 'MEG data':
            frame1.plotdata(event)
            print 'computing projection on weights'
        if self.combo_box_2.GetStringSelection() == 'MEG average':
            #frame1.data2plot
            frame1.plotdata(event, data=frame1.avg[:,frame1.chantypeind == 'meg'])
            print 'computing projection on weights from average'
        if self.combo_box_2.GetStringSelection() == 'MEG epoch':
            #frame1.data2plot
            frame1.plotdata(event, data=frame1.epoch[:,frame1.chantypeind == 'meg'])
            print 'computing projection on weights from epochs'
 
        if self.combo_box_2.GetStringSelection() == 'fftpow':
            pass
 
        if self.combo_box_2.GetSelection() > 0:
            self.button_3.Enable(True)
 
    def pickfromplot(self, event): # wxGlade: MyFrameSP.<event_handler>
        print "Event handler `pickfromplot' "
        try:
            frame1.plot2ddata(eval('frame1.'+frame1.selitem)) #check if something selected
            self.button_3.Enable(True)
 
        except AttributeError:
            print 'nothing selected'
            dlg = wx.MessageDialog(self, 'Nothing workspace data selected from PyMEG left window. Do that first', 'Selection error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            self.combo_box_2.SetSelection(0)
 
 
    def refreshstatus(self, event): # wxGlade: MyFrameSP.<event_handler>
        print "Event handler `refreshstatus' "
        self.SetStatusText("Data selected: %s" % frame1.selitem, 1)
 
 
    def manualtime(self, event): # wxGlade: MyFrameSP.<event_handler>
        print "Event handler `manualtime' not implemented"
        indtoval = fftmeg.nearest(frame1.timeaxis, float(self.text_ctrl_9.GetLineText(0))) * int(float(self.text_ctrl_10.GetLineText(0)))
        print 'indextovalue',indtoval
        frame1.x = indtoval
        self.button_3.Enable(True)
 
    def manualfreq(self, event): # wxGlade: MyFrameSP.<event_handler>
        print "Event handler `manualfreq' not implemented"
        indtoval = str(self.text_ctrl_8.GetLineText(0))
        indtoval = fftmeg.nearest(frame1.timeaxis, float(self.text_ctrl_8.GetLineText(0)))
        print 'indextovalue',indtoval
        frame1.x = indtoval
        self.button_3.Enable(True)
 
# end of class MyFrameSP
 
 
class MyFrameCOREG(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameCOREG.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.frameCOREG_statusbar = self.CreateStatusBar(1, 0)
        self.button_2_copy = wx.Button(self, -1, "Load Analyze MRI Volume")
        self.button_3_copy = wx.Button(self, -1, "coregister fiducials")
        self.checkbox_1_copy = wx.CheckBox(self, -1, "nas")
        self.checkbox_2_copy = wx.CheckBox(self, -1, "lpa")
        self.checkbox_3_copy = wx.CheckBox(self, -1, "rpa")
        self.save_index = wx.Button(self, -1, "save index points")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_BUTTON, self.loadmri, self.button_2_copy)
        self.Bind(wx.EVT_BUTTON, self.coregistermri, self.button_3_copy)
        self.Bind(wx.EVT_CHECKBOX, self.getnas, self.checkbox_1_copy)
        self.Bind(wx.EVT_CHECKBOX, self.getlpa, self.checkbox_2_copy)
        self.Bind(wx.EVT_CHECKBOX, self.getrpa, self.checkbox_3_copy)
        self.Bind(wx.EVT_BUTTON, self.saveindexpoints, self.save_index)
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: MyFrameCOREG.__set_properties
        self.SetTitle("coregister MRI")
        self.SetBackgroundColour(wx.Colour(143, 143, 188))
        self.frameCOREG_statusbar.SetStatusWidths([-1])
        # statusbar fields
        frameCOREG_statusbar_fields = ["frameCOREG_statusbar"]
        for i in range(len(frameCOREG_statusbar_fields)):
            self.frameCOREG_statusbar.SetStatusText(frameCOREG_statusbar_fields[i], i)
        self.button_3_copy.Enable(False)
        self.checkbox_1_copy.Enable(False)
        self.checkbox_2_copy.Enable(False)
        self.checkbox_3_copy.Enable(False)
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFrameCOREG.__do_layout
        sizer_11 = wx.BoxSizer(wx.VERTICAL)
        sizer_2_copy = wx.BoxSizer(wx.HORIZONTAL)
        sizer_11.Add(self.button_2_copy, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 9)
        sizer_11.Add(self.button_3_copy, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 9)
        sizer_2_copy.Add(self.checkbox_1_copy, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_2_copy.Add(self.checkbox_2_copy, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_2_copy.Add(self.checkbox_3_copy, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_11.Add(sizer_2_copy, 1, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 9)
        sizer_11.Add(self.save_index, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        self.SetSizer(sizer_11)
        sizer_11.Fit(self)
        self.Layout()
        self.Centre()
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
    def OnClose(self, event):
        print 'closing win'
        #del self.tbIcon
        self.Hide()
 
    def loadmri(self, event): # wxGlade: MyFrameCOREG.<event_handler>
        print "Event handler `loadmri' "
        try:
            self.SetStatusText("MRI Loaded: %s" % frame1.mrimypath,0)
            self.button_2_copy.Enable(False)
            self.button_3_copy.Enable(True)
 
        except AttributeError:
            frame1.openmri(event)
            self.button_2_copy.Enable(False)
 
 
 
    def coregistermri(self, event): # wxGlade: MyFrameCOREG.<event_handler>
        from mri import viewmri
        print "Event handler `coregistermri'"
        self.checkbox_1_copy.Enable(True)
        self.checkbox_2_copy.Enable(True)
        self.checkbox_3_copy.Enable(True)
        self.mrpnts = viewmri.display(frame1.nim, pixdim=frame1.nim.voxdim)
 
 
    def getnas(self, event): # wxGlade: MyFrameCOREG.<event_handler>
        print "Event handler `getnas' "
        frame1.nas = (array([self.mrpnts.ind3,self.mrpnts.ind2,self.mrpnts.ind1])*frame1.VoxDim).round()
        self.SetStatusText("nasion %s" % unicode(frame1.nas))
 
 
    def getlpa(self, event): # wxGlade: MyFrameCOREG.<event_handler>
        print "Event handler `getlpa'"
        frame1.lpa = (array([self.mrpnts.ind3,self.mrpnts.ind2,self.mrpnts.ind1])*frame1.VoxDim).round()
        self.SetStatusText("lpa %s" % unicode(frame1.lpa))
 
    def getrpa(self, event): # wxGlade: MyFrameCOREG.<event_handler>
        print "Event handler `getrpa'"
        frame1.rpa = (array([self.mrpnts.ind3,self.mrpnts.ind2,self.mrpnts.ind1])*frame1.VoxDim).round()
        self.SetStatusText("rpa %s" % unicode(frame1.rpa))
 
 
    def saveindexpoints(self, event): # wxGlade: MyFrameCOREG.<event_handler>
        print "Event handler `saveindexpoints' "
        ind = str([frame1.lpa,frame1.rpa,frame1.nas]).replace(' ','')
        print ind
        frame1.nim.setDescription(ind)
        print 'saving index points in mri', ind
        print frame1.mripath
        frame1.nim.save(str(frame1.mripath))
 
 
 
# end of class MyFrameCOREG
 
 
class MyFrameWEIGHTFIT(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameWEIGHTFIT.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.frame_4_statusbar = self.CreateStatusBar(1, 0)
        self.label_6 = wx.StaticText(self, -1, "Generate localization from which:", style=wx.ALIGN_CENTRE)
        self.label_7 = wx.StaticText(self, -1, "time point in data")
        self.button_8 = wx.Button(self, -1, "Plot Data")
        self.label_8 = wx.StaticText(self, -1, "ICA components")
        self.button_9 = wx.Button(self, -1, "Run ICA")
        self.label_9 = wx.StaticText(self, -1, "Already computed weight")
        self.button_10 = wx.Button(self, -1, "Retrieve Selection")
        self.button_11 = wx.Button(self, -1, "Localize")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_BUTTON, self.pickfromplot, self.button_8)
        self.Bind(wx.EVT_BUTTON, self.weightfit, self.button_11)
        # end wxGlade
 
 
    def __set_properties(self):
        # begin wxGlade: MyFrameWEIGHTFIT.__set_properties
        self.SetTitle("frameWEIGHT")
        self.frame_4_statusbar.SetStatusWidths([-1])
        # statusbar fields
        frame_4_statusbar_fields = ["frame_4_statusbar"]
        for i in range(len(frame_4_statusbar_fields)):
            self.frame_4_statusbar.SetStatusText(frame_4_statusbar_fields[i], i)
        self.button_11.SetBackgroundColour(wx.Colour(143, 143, 188))
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
 
    def __do_layout(self):
        # begin wxGlade: MyFrameWEIGHTFIT.__do_layout
        sizer_10 = wx.BoxSizer(wx.VERTICAL)
        grid_sizer_2 = wx.GridSizer(3, 2, 2, 2)
        sizer_10.Add(self.label_6, 0, wx.EXPAND, 0)
        grid_sizer_2.Add(self.label_7, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_2.Add(self.button_8, 0, 0, 0)
        grid_sizer_2.Add(self.label_8, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_2.Add(self.button_9, 0, 0, 0)
        grid_sizer_2.Add(self.label_9, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_2.Add(self.button_10, 0, 0, 0)
        sizer_10.Add(grid_sizer_2, 1, wx.EXPAND, 0)
        sizer_10.Add(self.button_11, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 15)
        self.SetSizer(sizer_10)
        sizer_10.Fit(self)
        self.Layout()
        # end wxGlade
 
    def OnClose(self, event):
        print 'closing win'
        self.Hide()
 
    def pickfromplot(self, event): # wxGlade: MyFrameWEIGHTFIT.<event_handler>
        print "Event handler `pickfromplot'"
        frame1.openfilecheck(event)
        frame1.plotdata(event)
 
 
    def weightfit(self, event): # wxGlade: MyFrameWEIGHTFIT.<event_handler>
        print "Event handler `weightfit' "
        frame1.openfilecheck(event)
        try:
            frame1.lf
        except AttributeError:
            dlg = wx.MessageDialog(self, 'No leadfields detected. Do that first', 'Leadfield detection error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            frame1.leadfieldgen(event)
        data2plot = eval('frame1.'+frame1.selitem)
        print 'calculating weights from', str(frame1.selitem), 'at index value', str(frame1.x)
 
        wmat = data2plot[frame1.x,:]
 
        print 'weight shape',shape(wmat)
        print 'fitting weights'
        w = weightfit.calc(frame1.datapdf, frame1.lf.leadfield, wmat)
        print 'Done. Fit result size is', shape(w.corr_mat)
        self.SetStatusText("Fit Completed %s" % unicode(shape(w.corr_mat)))
        frame1.SetStatusText("Fit Completed %s" % unicode(shape(w.corr_mat)))
        frame1.FIT = frame1.tree_ctrl_1.AppendItem(frame1.PROCESSES, 'fit')
        frame1.fit = w;
        try:
            frame1.fitimage = sourcesolution2img.build(w.corr_mat, frame1.dec)
            viewmri.display(frame1.fitimage[0], colormap=cm.hot)
            frame1.FITIMAGE = frame1.tree_ctrl_1.AppendItem(frame1.PROCESSES, 'fitimage')
 
        except NameError:
            print 'no mri to make image from'
 
 
 
# end of class MyFrameWEIGHTFIT
 
class MyFrameICA(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameICA.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.label_5 = wx.StaticText(self, -1, "independent components: ", style=wx.ALIGN_CENTRE)
        self.text_ctrl_5 = wx.TextCtrl(self, -1, "10", style=wx.TE_CENTRE)
        self.button_7 = wx.Button(self, -1, "Run ICA", style=wx.BU_EXACTFIT)
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_BUTTON, self.runica, self.button_7)
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: MyFrameICA.__set_properties
        self.SetTitle("Independent Component Analysis")
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFrameICA.__do_layout
        sizer_8 = wx.BoxSizer(wx.VERTICAL)
        sizer_9 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_9.Add(self.label_5, 0, 0, 0)
        sizer_9.Add(self.text_ctrl_5, 0, 0, 0)
        sizer_8.Add(sizer_9, 1, 0, 0)
        sizer_8.Add(self.button_7, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        self.SetSizer(sizer_8)
        sizer_8.Fit(self)
        self.Layout()
        self.Centre()
        # end wxGlade
 
    def runica(self, event): # wxGlade: MyFrameICA.<event_handler>
        print "Event handler `runica'"
        frame1.openfilecheck(event)
        print 'running ICA'
        r.library('fastICA')
        ts = time.time()
        frame1.ica = r.fastICA(frame1.d.data_block.T, int(self.text_ctrl_5.GetLineText(0)), verbose='TRUE')
        self.Hide()
        telapsed = time.time()-ts
        print 'done. elapsed time', telapsed, 'seconds'
        frame1.ICA = frame1.tree_ctrl_1.AppendItem(frame1.MEGDATA, 'ICA')
        frame1.SetStatusText("ICA components %s" % unicode(shape(frame1.ica)))
 
 
# end of class MyFrameICA
 
 
class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.label_1 = wx.StaticText(self, -1, "Time Freq Values")
        self.label_4 = wx.StaticText(self, -1, "data")
        self.combo_box_1 = wx.ComboBox(self, -1, choices=["raw data", "projection"], style=wx.CB_DROPDOWN)
        self.label_4_copy = wx.StaticText(self, -1, "channel label")
        self.text_ctrl_chl = wx.TextCtrl(self, -1, "'A1'")
        self.label_4_copy_1 = wx.StaticText(self, -1, "cycles")
        self.text_ctrl_cyc = wx.TextCtrl(self, -1, "[3.0, 0.5]")
        self.label_4_copy_2 = wx.StaticText(self, -1, "frequency range")
        self.text_ctrl_freqr = wx.TextCtrl(self, -1, "[5.0, 100]")
        self.label_4_copy_3 = wx.StaticText(self, -1, "padratio")
        self.text_ctrl_padr = wx.TextCtrl(self, -1, "4")
        self.label_4_copy_4 = wx.StaticText(self, -1, "timesout")
        self.text_ctrl_timout = wx.TextCtrl(self, -1, "200")
        self.label_4_copy_5 = wx.StaticText(self, -1, "frames")
        self.text_ctrl_4_copy_3 = wx.TextCtrl(self, -1, "[3.0, 0.5]")
        self.label_4_copy_6 = wx.StaticText(self, -1, "trials")
        self.text_ctrl_4_copy_4 = wx.TextCtrl(self, -1, "None")
        self.label_4_copy_7 = wx.StaticText(self, -1, "sample rate")
        self.text_ctrl_4_copy_5 = wx.TextCtrl(self, -1, "None")
        self.timef_run = wx.Button(self, -1, "Run Timef")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_TEXT, self.getchoice, self.combo_box_1)
        self.Bind(wx.EVT_BUTTON, self.timefhandle, self.timef_run)
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
 
    def __set_properties(self):
        # begin wxGlade: MyFrame.__set_properties
        self.SetTitle("TimeFreq Parameters")
        self.SetBackgroundColour(wx.Colour(143, 143, 188))
        self.label_1.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "Sans"))
        self.combo_box_1.SetBackgroundColour(wx.Colour(195, 203, 113))
        self.combo_box_1.SetSelection(-1)
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFrame.__do_layout
        sizer_7 = wx.BoxSizer(wx.VERTICAL)
        grid_sizer_1 = wx.GridSizer(11, 2, 0, 0)
        sizer_7.Add(self.label_1, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_1.Add(self.label_4, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_1.Add(self.combo_box_1, 0, 0, 0)
        grid_sizer_1.Add(self.label_4_copy, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_1.Add(self.text_ctrl_chl, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_1.Add(self.label_4_copy_1, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_1.Add(self.text_ctrl_cyc, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_1.Add(self.label_4_copy_2, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_1.Add(self.text_ctrl_freqr, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_1.Add(self.label_4_copy_3, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_1.Add(self.text_ctrl_padr, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_1.Add(self.label_4_copy_4, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_1.Add(self.text_ctrl_timout, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_1.Add(self.label_4_copy_5, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_1.Add(self.text_ctrl_4_copy_3, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_1.Add(self.label_4_copy_6, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_1.Add(self.text_ctrl_4_copy_4, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        grid_sizer_1.Add(self.label_4_copy_7, 0, wx.ALIGN_RIGHT, 0)
        grid_sizer_1.Add(self.text_ctrl_4_copy_5, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer_7.Add(grid_sizer_1, 1, 0, 0)
        sizer_7.Add(self.timef_run, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        self.SetSizer(sizer_7)
        sizer_7.Fit(self)
        self.Layout()
        # end wxGlade
 
 
    def OnClose(self, event):
        print 'closing win'
        self.Hide()
 
    def timefhandle(self, event): # wxGlade: MyFrame.<event_handler>
        print "Event handler `timefhandle' "
        frame1.openfilecheck(event)
 
        if self.combo_box_1.GetCurrentSelection() == 0:
            data = frame1.datapdf
            chl = str(eval(self.text_ctrl_chl.GetLineText(0)))
        if self.combo_box_1.GetCurrentSelection() == 1:
            print 'sp shape',shape(frame1.projection)
            data = frame1.projection
            chl=None
 
        srate=1/frame1.p.hdr.header_data.sample_period
        frames=int(frame1.p.hdr.epoch_data[0].epoch_duration/frame1.p.hdr.header_data.sample_period)-1
        trials=size(frame1.p.hdr.epoch_data)
        cyc = array(eval(self.text_ctrl_cyc.GetLineText(0)))
        freqr = array(eval(self.text_ctrl_freqr.GetLineText(0)))
        padr = int(eval(self.text_ctrl_padr.GetLineText(0)))
        timout = int(eval(self.text_ctrl_timout.GetLineText(0)))
        frame1.t = timef.initialize()
 
        print type(data),shape(data)
        frame1.t.calc(data=data, chlabel=chl, cycles=cyc, freqrange=freqr, padratio=padr, timesout=timout,frames=frames, trials=trials, srate=srate)
        frame1.TIMEF = frame1.tree_ctrl_1.AppendItem(frame1.PROCESSES, 'timef')
        frame1.TIMEFpow = frame1.tree_ctrl_1.AppendItem(frame1.TIMEF, 'induced_power')
        frame1.TIMEFpow = frame1.tree_ctrl_1.AppendItem(frame1.TIMEF, 'induced_powerlog')
        frame1.TIMEFplf = frame1.tree_ctrl_1.AppendItem(frame1.TIMEF, 'phaselocking_factor')
        frame1.TIMEFplf = frame1.tree_ctrl_1.AppendItem(frame1.TIMEF, 'power_of_continious_data')
        self.Hide()
    def getchoice(self, event): # wxGlade: MyFrame.<event_handler>
        print "Event handler `getchoice' not implemented"
        print self.combo_box_1.GetCurrentSelection()
        if self.combo_box_1.GetCurrentSelection() == 0:
            pass
        if self.combo_box_1.GetCurrentSelection() == 1:
            print 'sp shape',shape(frame1.projection)
            self.text_ctrl_chl.Enable(False)
 
# end of class MyFrame
 
 
class MyFrameGrid(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrameGrid.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.sizer_6_staticbox = wx.StaticBox(self, -1, "Decimation Factor for Brain Space")
        self.frame_2_statusbar = self.CreateStatusBar(1, 0)
        self.label_2 = wx.StaticText(self, -1, "Manual Specification of Grid Points:\nEnter X,Y,Z coordinates (mm)\nex. [[55,-65,82.3],[52.2,63.4,84]]", style=wx.ALIGN_CENTRE)
        self.text_ctrl_2 = wx.TextCtrl(self, -1, "[]", style=wx.TE_CENTRE)
        self.button_1 = wx.Button(self, -1, "Manual Add of Grid Points", style=wx.BU_BOTTOM)
        self.label_3 = wx.StaticText(self, -1, "Source Space Volume Method", style=wx.ALIGN_CENTRE)
        self.button_2 = wx.Button(self, -1, "Load Head MRI Volume")
        self.button_4 = wx.Button(self, -1, "Load Extracted Brain Volume")
        self.text_ctrl_1 = wx.TextCtrl(self, -1, "10")
        self.button_5 = wx.Button(self, -1, "Generate Source Space Grid")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_BUTTON, self.gridgetxyz, self.button_1)
        self.Bind(wx.EVT_BUTTON, self.gridloadmri, self.button_2)
        self.Bind(wx.EVT_BUTTON, self.loadbrain, self.button_4)
        self.Bind(wx.EVT_BUTTON, self.gridcalc, self.button_5)
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: MyFrameGrid.__set_properties
        self.SetTitle("Grid Selection")
        self.SetBackgroundColour(wx.Colour(143, 143, 188))
        self.frame_2_statusbar.SetStatusWidths([-1])
        # statusbar fields
        frame_2_statusbar_fields = ["frame_2_statusbar"]
        for i in range(len(frame_2_statusbar_fields)):
            self.frame_2_statusbar.SetStatusText(frame_2_statusbar_fields[i], i)
        self.text_ctrl_2.SetMinSize((180, 37))
        self.button_1.SetBackgroundColour(wx.Colour(128, 128, 128))
        self.button_4.Enable(False)
        self.text_ctrl_1.Enable(False)
        self.button_5.SetBackgroundColour(wx.Colour(128, 128, 128))
        # end wxGlade
        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
 
    def __do_layout(self):
        # begin wxGlade: MyFrameGrid.__do_layout
        sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_5 = wx.BoxSizer(wx.VERTICAL)
        sizer_6 = wx.StaticBoxSizer(self.sizer_6_staticbox, wx.HORIZONTAL)
        sizer_4 = wx.BoxSizer(wx.VERTICAL)
        sizer_4.Add(self.label_2, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_4.Add(self.text_ctrl_2, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_4.Add(self.button_1, 0, wx.ALIGN_BOTTOM|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_3.Add(sizer_4, 1, wx.ALIGN_BOTTOM|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL|wx.SHAPED, 0)
        sizer_3.Add((20, 20), 0, wx.ALL|wx.SHAPED, 2)
        sizer_5.Add(self.label_3, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 19)
        sizer_5.Add(self.button_2, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 11)
        sizer_5.Add(self.button_4, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 8)
        sizer_6.Add(self.text_ctrl_1, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_5.Add(sizer_6, 1, wx.BOTTOM|wx.EXPAND, 5)
        sizer_5.Add(self.button_5, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_3.Add(sizer_5, 1, wx.EXPAND, 6)
        self.SetSizer(sizer_3)
        sizer_3.Fit(self)
        self.Layout()
        self.Centre()
        # end wxGlade
 
    def OnClose(self, event):
        print 'closing win'
        self.Hide()
 
    def gridgetxyz(self, event): # wxGlade: MyFrameGrid.<event_handler>
 
        print "Event handler `gridgetxyz'"
        pnts = array(eval(self.text_ctrl_2.GetLineText(0)))
        print pnts
 
        if len(pnts.shape) == 1:
            pnts = array([pnts])
        if shape(pnts)[1] != 3:
            print 'need pairs of 3 points ([x,y,z])'
        numgridpnts = pnts.shape
        frame1.grid = pnts.T
        frame2.SetStatusText("number of pnts %s" % unicode(numgridpnts))
        frame1.GRID = frame1.tree_ctrl_1.AppendItem(frame1.PROCESSES, 'grid')
        self.Hide()
 
    def gridloadmri(self, event): # wxGlade: MyFrameGrid.<event_handler>
        print "Event handler `gridloadmri'"
        try:
            frameCOREG.mrpnts
        except AttributeError:
            frameCOREG.loadmri(event)
            time.sleep(1)
            frameCOREG.Show()
            frameCOREG.button_3_copy.Enable(True)
            self.button_4.Enable(True)
            self.text_ctrl_1.Enable(True)
        frame2.SetStatusText("MRI Loaded: %s" % frame1.mrimypath,0)
 
    def loadbrain(self, event): # wxGlade: MyFrameGrid.<event_handler>
        print "Event handler `loadbrain' not implemented"
        frame1.openbrain(event)
 
    def gridcalc(self, event): # wxGlade: MyFrameGrid.<event_handler>
        print "Event handler `gridcalc'"
        frame1.dec = img.decimate(frame1.brain, eval(self.text_ctrl_1.GetLineText(0)))
        [t,r] = transform.meg2mri(frame1.lpa,frame1.rpa,frame1.nas)
        megxyz = transform.mri2meg(t,r,frame1.dec.mrixyz)
        try:
            datapdf = frame1.megpath
        except AttributeError:
            frame1.openfile(event)
            datapdf = frame1.megpath
        print frame1.megpath
        self.scaledmegxyz = transform.scalesourcespace(datapdf, megxyz)
        frame2.SetStatusText("rpa %s" % unicode(shape(self.scaledmegxyz)))
        print shape(self.scaledmegxyz)
        frame1.grid = self.scaledmegxyz.T
        frame1.GRID = frame1.tree_ctrl_1.AppendItem(frame1.PROCESSES, 'grid')
        self.Hide()
 
# end of class MyFrameGrid
 
 
class MyFrame1(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrame1.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.window_1 = wx.SplitterWindow(self, -1, style=wx.SP_NOBORDER)
 
        # Menu Bar
        self.framewithnotebook_menubar = wx.MenuBar()
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(1, "New Session", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(2, "Load MEG", "Load 4D MEG File", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(3, "Load MRI", "load mri file", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(4, "Load Stripped MRI", "Load Brain Extracted Volume", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(7, "Load Dipole File(s)", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(8, "load hs_file", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(9, "Project Info", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(10, "Macro", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(11, "Save Workspace", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendSeparator()
        self.Exit = wx.MenuItem(wxglade_tmp_menu, wx.NewId(), "Exit PyMEG", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendItem(self.Exit)
        self.framewithnotebook_menubar.Append(wxglade_tmp_menu, "File")
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(12, "Channels", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(13, "Events", "", wx.ITEM_NORMAL)
        self.framewithnotebook_menubar.Append(wxglade_tmp_menu, "Edit")
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu_sub = wx.Menu()
        wxglade_tmp_menu_sub.Append(150, "Data-Tap", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendMenu(wx.NewId(), "Acquisition", wxglade_tmp_menu_sub, "")
        wxglade_tmp_menu.Append(30, "Epoch and or Average Data", "resize data", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(31, "Epoch Data", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(32, "Remove DC offset", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(33, "Coregister MRI", "coregister mri fiducials", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(34, "LeadField", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(35, "Source Space Grid", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(36, "Source Projection", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(37, "Source Simulation", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(38, "ICA", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(39, "Time Frequency Transform", "compute time freq transform using Morlet Wavelets", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(40, "Fast Fourier Transform", "fft", wx.ITEM_NORMAL)
        wxglade_tmp_menu_sub = wx.Menu()
        wxglade_tmp_menu_sub.Append(41, "Weight Matrix", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendMenu(wx.NewId(), "Localize", wxglade_tmp_menu_sub, "")
        wxglade_tmp_menu.Append(42, "Bad Channel Detection", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(43, "Dipole Density", "", wx.ITEM_NORMAL)
        self.framewithnotebook_menubar.Append(wxglade_tmp_menu, "Tools")
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu_sub = wx.Menu()
        wxglade_tmp_menu_sub.Append(50, "Channel Data", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu_sub.Append(51, "ERP", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu_sub.Append(52, "headshape", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu_sub.Append(53, "sensors", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu_sub.Append(54, "fiducials", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu_sub.Append(55, "headshape,sensors,fiducials", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu_sub.Append(56, "headshape,fids,dipoles", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendMenu(wx.NewId(), "MEG", wxglade_tmp_menu_sub, "")
        wxglade_tmp_menu_sub = wx.Menu()
        wxglade_tmp_menu_sub.Append(57, "2D", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu_sub.Append(58, "3D", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.AppendMenu(wx.NewId(), "MRI", wxglade_tmp_menu_sub, "")
        self.framewithnotebook_menubar.Append(wxglade_tmp_menu, "Plot")
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(200, "psel", "", wx.ITEM_NORMAL)
        wxglade_tmp_menu.Append(201, "acquisition menu", "", wx.ITEM_NORMAL)
        self.framewithnotebook_menubar.Append(wxglade_tmp_menu, "MSI-tools")
        self.exportitems = wx.Menu()
        self.itemtovtk = wx.MenuItem(self.exportitems, wx.NewId(), "Item to VTK", "", wx.ITEM_NORMAL)
        self.exportitems.AppendItem(self.itemtovtk)
        self.framewithnotebook_menubar.Append(self.exportitems, "Export")
        wxglade_tmp_menu = wx.Menu()
        self.framewithnotebook_menubar.Append(wxglade_tmp_menu, "Help")
        self.SetMenuBar(self.framewithnotebook_menubar)
        # Menu Bar end
        self.framewithnotebook_statusbar = self.CreateStatusBar(3, 0)
 
        # Tool Bar
        self.frame1_toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL|wx.TB_DOCKABLE|wx.TB_3DBUTTONS|wx.TB_TEXT|wx.TB_NODIVIDER|wx.TB_NOALIGN)
        self.SetToolBar(self.frame1_toolbar)
        self.frame1_toolbar.AddLabelTool(101, "MEG load", wx.Bitmap("filelight.png", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Load Data File", "")
        self.frame1_toolbar.AddLabelTool(102, "PlotMEG", wx.Bitmap("plotdata2.png", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "2D Plot", "")
        self.frame1_toolbar.AddLabelTool(103, "megcontour", wx.Bitmap("contour3.png", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "Contour Plot Of Data Point", "")
        self.frame1_toolbar.AddLabelTool(105, "Plot Selected", wx.Bitmap("fityk.png", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "", "")
        self.frame1_toolbar.AddSeparator()
        self.frame1_toolbar.AddLabelTool(104, "MRI load", wx.Bitmap("brain1.png", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "LoadMR", "")
        self.frame1_toolbar.AddLabelTool(106, "MACRO", wx.Bitmap("brain2.png", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "", "")
        # Tool Bar end
        self.tree_ctrl_1 = wx.TreeCtrl(self.window_1, -1, style=wx.TR_HAS_BUTTONS|wx.TR_NO_LINES|wx.TR_EDIT_LABELS|wx.TR_MULTIPLE|wx.TR_MULTIPLE|wx.TR_EXTENDED|wx.TR_DEFAULT_STYLE)
        self.list_ctrl_1 = wx.ListCtrl(self.window_1, -1, style=wx.LC_REPORT|wx.LC_AUTOARRANGE|wx.LC_EDIT_LABELS|wx.SUNKEN_BORDER)
        self.button_6 = wx.Button(self, -1, "Delete Item")
        self.static_line_2 = wx.StaticLine(self, -1)
        self.static_line_1 = wx.StaticLine(self, -1)
        self.text = wx.StaticText(self, -1, "argument")
 
        self.__set_properties()
        self.__do_layout()
 
        self.Bind(wx.EVT_MENU, self.newsession, id=1)
        self.Bind(wx.EVT_MENU, self.openfile, id=2)
        self.Bind(wx.EVT_MENU, self.openmri, id=3)
        self.Bind(wx.EVT_MENU, self.openbrain, id=4)
        self.Bind(wx.EVT_MENU, self.loaddipoles, id=7)
        self.Bind(wx.EVT_MENU, self.loadhs, id=8)
        self.Bind(wx.EVT_MENU, self.projectutils, id=9)
        self.Bind(wx.EVT_MENU, self.batch, id=10)
        self.Bind(wx.EVT_MENU, self.saveworkspace, id=11)
        self.Bind(wx.EVT_MENU, self.quitapp, self.Exit)
        self.Bind(wx.EVT_MENU, self.loadchan, id=12)
        self.Bind(wx.EVT_MENU, self.getevents, id=13)
        self.Bind(wx.EVT_MENU, self.tapwin, id=150)
        self.Bind(wx.EVT_MENU, self.cutdata, id=30)
        self.Bind(wx.EVT_MENU, self.epochdata, id=31)
        self.Bind(wx.EVT_MENU, self.offsetcorrect, id=32)
        self.Bind(wx.EVT_MENU, self.coregistermri, id=33)
        self.Bind(wx.EVT_MENU, self.leadfieldgen, id=34)
        self.Bind(wx.EVT_MENU, self.sourcespacegrid, id=35)
        self.Bind(wx.EVT_MENU, self.sourceprojection, id=36)
        self.Bind(wx.EVT_MENU, self.ica, id=38)
        self.Bind(wx.EVT_MENU, self.timef, id=39)
        self.Bind(wx.EVT_MENU, self.fft, id=40)
        self.Bind(wx.EVT_MENU, self.weightfit, id=41)
        self.Bind(wx.EVT_MENU, self.badch, id=42)
        self.Bind(wx.EVT_MENU, self.dipoledensity, id=43)
        self.Bind(wx.EVT_MENU, self.plot2ddata, id=50)
        self.Bind(wx.EVT_MENU, self.plotheadshape, id=52)
        self.Bind(wx.EVT_MENU, self.plotsensors, id=53)
        self.Bind(wx.EVT_MENU, self.plotindex, id=54)
        self.Bind(wx.EVT_MENU, self.plothssensind, id=55)
        self.Bind(wx.EVT_MENU, self.plothsinddips, id=56)
        self.Bind(wx.EVT_MENU, self.mri2D, id=57)
        self.Bind(wx.EVT_MENU, self.mri3D, id=58)
        self.Bind(wx.EVT_MENU, self.psel, id=200)
        self.Bind(wx.EVT_MENU, self.ape, id=201)
        self.Bind(wx.EVT_TOOL, self.openfile, id=101)
        self.Bind(wx.EVT_TOOL, self.plotdata, id=102)
        self.Bind(wx.EVT_TOOL, self.megcontour, id=103)
        self.Bind(wx.EVT_TOOL, self.plotselected, id=105)
        self.Bind(wx.EVT_TOOL, self.openmri, id=104)
        self.Bind(wx.EVT_TOOL, self.batch, id=106)
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.treeitemact, self.tree_ctrl_1)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.listitemselected, self.list_ctrl_1)
        self.Bind(wx.EVT_BUTTON, self.treedelitem, self.button_6)
        # end wxGlade
 
    def __set_properties(self):
        # begin wxGlade: MyFrame1.__set_properties
        self.SetTitle("PyMEG GUI")
        self.SetSize((645, 668))
        self.SetToolTipString("pymegGUI")
        self.framewithnotebook_statusbar.SetStatusWidths([-1, -1, -1])
        # statusbar fields
        framewithnotebook_statusbar_fields = ["Status:", "No value:", "No element:"]
        for i in range(len(framewithnotebook_statusbar_fields)):
            self.framewithnotebook_statusbar.SetStatusText(framewithnotebook_statusbar_fields[i], i)
        self.frame1_toolbar.SetToolBitmapSize((10, 10))
        self.frame1_toolbar.Realize()
        self.tree_ctrl_1.SetBackgroundColour(wx.Colour(143, 143, 188))
        self.list_ctrl_1.SetBackgroundColour(wx.Colour(137, 137, 180))
        self.list_ctrl_1.SetToolTipString("data properties")
        self.window_1.SetMinSize((645, 237))
        self.button_6.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 1, ""))
        # end wxGlade
 
    def __do_layout(self):
        # begin wxGlade: MyFrame1.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        self.window_1.SplitVertically(self.tree_ctrl_1, self.list_ctrl_1)
        sizer_1.Add(self.window_1, 1, wx.EXPAND, 0)
        sizer_1.Add(self.button_6, 0, 0, 0)
        sizer_1.Add(self.static_line_2, 0, wx.EXPAND, 0)
        sizer_1.Add(self.static_line_1, 0, wx.EXPAND, 0)
        sizer_1.Add(self.text, 0, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        sizer_1.SetSizeHints(self)
        self.Layout()
        # end wxGlade
 
    def replaceitem(self, event, parent, item, text):
        try:
            self.tree_ctrl_1.Delete(item)
        except AttributeError:
            print 'nothing 2 replace'
            item = self.tree_ctrl_1.AppendItem(parent, text)
 
    def createworkspace(self):
        try:
            self.WORKSPACE
        except AttributeError:
            self.WORKSPACE = self.tree_ctrl_1.AddRoot('Workspace')
 
    def openfile(self, event, batch='none'): # wxGlade: MyFrame1.<event_handler>
        print 'opening file'
        try:
            self.WORKSPACE
        except AttributeError:
            self.WORKSPACE = self.tree_ctrl_1.AddRoot('Workspace')
            self.SESSION = self.tree_ctrl_1.AppendItem(self.WORKSPACE, 'Session')
            self.DATA = self.tree_ctrl_1.AppendItem(self.SESSION, 'DataChannels')
 
        try:
            self.MEG# = self.tree_ctrl_1.AppendItem(self.SESSION, 'MEG')
        except AttributeError:
            self.MEG = self.tree_ctrl_1.AppendItem(self.SESSION, 'MEG')
 
        if batch != 'none':
            self.megpath = path = batch
        else:
            dlg = wx.FileDialog(self, "Select a 4D MEG file", os.getcwd(), "", "*", wx.OPEN)
            if dlg.ShowModal() == wx.ID_OK:
                self.megpath = path = dlg.GetPath()
                dlg.Destroy()
 
        self.megmypath = mypath = os.path.basename(self.megpath)
        self.filename = self.megmypath
        self.SetStatusText("Data Loaded: %s" % self.megmypath,0)
 
        try:
            self.tree_ctrl_1.Delete(self.MEGDATA)
        except AttributeError:
            print 'cant delete item'
        self.MEGDATA = self.tree_ctrl_1.AppendItem(self.MEG, 'data_block')#mypath)
        self.PROCESSES = frame1.tree_ctrl_1.AppendItem(frame1.MEG, 'PROCESSES')
 
        self.list_ctrl_1.InsertColumn(0, 'Val')
        self.list_ctrl_1.InsertColumn(0, 'Val')
        self.list_ctrl_1.InsertColumn(0, 'Data')
        self.list_ctrl_1.SetColumnWidth(0, 140)
        self.list_ctrl_1.SetColumnWidth(1, 193)
        self.list_ctrl_1.SetColumnWidth(2, 140)
        self.datapdf = self.megpath
        self.d = data.read(self.megpath)
 
        try:
            self.ch
        except AttributeError:
            print 'select channels first'
            frameCHAN.Show()
 
        self.p = pdf.read(self.datapdf)
        try:
            self.p.hs
            self.HS = self.tree_ctrl_1.AppendItem(self.MEGDATA, 'headshape')
        except AttributeError:
            print 'no headshape to load'
        try:
            self.p.cfg
            self.CFG = self.tree_ctrl_1.AppendItem(self.MEGDATA, 'config')
        except AttributeError:
            print 'no config file to load'
 
        dataprefix = 'd'
        self.HDR = self.tree_ctrl_1.AppendItem(self.MEGDATA, 'header')
        self.tree_ctrl_1.AppendItem(self.HDR, 'epoch_data')
        self.tree_ctrl_1.AppendItem(self.HDR, 'event_data')
        self.tree_ctrl_1.AppendItem(self.HDR, 'header_data')
        self.tree_ctrl_1.AppendItem(self.HDR, 'header_offset')
        self.CR = self.tree_ctrl_1.AppendItem(self.HDR, 'channel_ref_data')
        self.tree_ctrl_1.AppendItem(self.CR, 'attributes')
        self.tree_ctrl_1.AppendItem(self.CR, 'chan_no')
        self.tree_ctrl_1.AppendItem(self.CR, 'checksum')
        self.tree_ctrl_1.AppendItem(self.CR, 'index')
        self.tree_ctrl_1.AppendItem(self.CR, 'scale')
        self.tree_ctrl_1.AppendItem(self.CR, 'valid_min_max')
        self.tree_ctrl_1.AppendItem(self.CR, 'whatisit')
        self.tree_ctrl_1.AppendItem(self.CR, 'yaxis_label')
        self.tree_ctrl_1.AppendItem(self.CR, 'ymax')
        self.tree_ctrl_1.AppendItem(self.CR, 'ymin')
 
 
    def sessionhandler(self, event):
        pdb = []; cdb = []
        print self.tree_ctrl_1.GetChildrenCount(self.SESSION)
        cookie = -1
        if self.tree_ctrl_1.ItemHasChildren(self.SESSION) == True:
                parent, cookie = self.tree_ctrl_1.GetFirstChild( self.SESSION )
        for i in arange(self.tree_ctrl_1.GetChildrenCount(self.SESSION)):
            if self.tree_ctrl_1.ItemHasChildren(parent) == False:
 
                child, cookie = self.tree_ctrl_1.GetNextChild( parent, cookie )
                print self.tree_ctrl_1.GetItemText(parent),'no child',self.tree_ctrl_1.GetItemText(child)
 
            else:
 
                child, cookie = self.tree_ctrl_1.GetFirstChild( parent )
                print self.tree_ctrl_1.GetItemText(parent),'has child',self.tree_ctrl_1.GetItemText(child)
                if self.tree_ctrl_1.ItemHasChildren(child) == True:
                    parent = child
                else:
                    parent = child
 
        print pdb
        print cdb
 
    def openfilecheck(self, event):
        try:
            self.datapdf# = self.megpath
        except AttributeError:
            dlg = wx.MessageDialog(self, 'First you need to load MEG data file', 'MEG file error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            self.openfile(event)
            datapdf = self.megpath
 
    def closeapp(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Closing Pymeg"
        self.Close(True)
 
    def testevent(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `press' not implemented!"
        self.button_1.SetLabel("Ouch!")
        self.label_1.SetLabel("Ouch!")
        event.Skip()
 
    def quitapp(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Closing Application"
        self.Close(True)
 
    def plotdata(self, event, data=None): # wxGlade: MyFrame1.<event_handler>
        print "plotting data", self.megmypath
        def event_response(event):
            print event.name
            print event.xdata
            self.SetStatusText("You selected time point: %s" % event.xdata)
            if data == None:
                self.SetPyData(int(event.xdata))
            else:
                self.SetPyData(int(event.xdata), data=data)
            #self.treebeginlabel('plotdata')
 
        if data == None:
            print 'no item selected'
            #data = self.d.data_block
        figure();plot(data);
        cid = connect('button_press_event', event_response)
        show()
 
    def toolbartest(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `toolbartest' not implemented"
        event.Skip()
 
    def SetPyData(self, event, data=None): # wxGlade: MyFrame1.<event_handler>
        self.x = event
        try:
            self.dataitems
        except AttributeError:
            self.dataitems = []
            self.dataitems.append(data)
        else:
            self.dataitems.append(data)
 
        #print 'dataitems',self.dataitems
 
    def megcontour(self, event, data=None): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `megcontour'"
        figure()
        data2plot = eval('frame1.'+frame1.selitem)
        print 'plotting', str(frame1.selitem)
        try:
            megcontour.display(data2plot[self.x,frame1.chantypeind == 'meg'], frame1.ch.chanlocs, subplot='on')
        except AttributeError:
            dlg = wx.MessageDialog(self, 'No Signal Channels Loaded', 'signal ch error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
 
    def GetPyData(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `GetPyData' not implemented"
        event.Skip()
 
    def treedelitem(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `treedelitem' "
        sel = self.tree_ctrl_1.GetSelection()
        self.tree_ctrl_1.Delete(sel)
        event.Skip()
 
    def treeitemact(self, event): # wxGlade: MyFrame1.<event_handler>
        self.list_ctrl_1.DeleteAllItems()
        self.itemID = self.tree_ctrl_1.GetSelection()
 
        self.selitem = selitem = self.tree_ctrl_1.GetItemText(self.itemID)
        self.rootitemID = self.tree_ctrl_1.GetRootItem()
        self.rootitem = rootitem = self.tree_ctrl_1.GetItemText(self.rootitemID)
        self.parentitemID = self.tree_ctrl_1.GetItemParent(self.itemID)
        self.parentitem = parentitem = self.tree_ctrl_1.GetItemText(self.parentitemID)
        self.SetStatusText("You selected data: %s" % selitem)
 
        self.tree_ctrl_1.ExpandAllChildren(self.itemID)
 
        print selitem, rootitem, parentitem
 
        print 'extracting', selitem
        from pdf2py import listparse
        if parentitem == 'MEG':
            data2pass = self.d
            items = listparse.megdata(parentitem, selitem, data2pass)
        if selitem == 'header':
            data2pass = self.d.hdr
            items = listparse.header(parentitem, selitem, data2pass)
        if parentitem == 'channel_ref_data':
            data2pass = self.d.hdr
            items = listparse.channel_ref_data(parentitem, selitem, data2pass)
        if selitem == 'epoch_data':
            data2pass = self.d.hdr.epoch_data[0]
            items = listparse.epoch_data(parentitem, selitem, data2pass)
        if selitem == 'event_data':
            data2pass = self.d.hdr.event_data
            items = listparse.event_data(parentitem, selitem, data2pass)
        if selitem == 'header_data':
            data2pass = self.d.hdr.header_data
            items = listparse.header_data(parentitem, selitem, data2pass)
        if selitem == 'headshape':
            data2pass = self.p.hs
            items = listparse.headshape(parentitem, selitem, data2pass)
        if selitem == 'config':
            data2pass = self.p.cfg
            items = listparse.config(parentitem, selitem, data2pass)
        if selitem == 'mr_header':
            data2pass = self.mr.header
            items = listparse.mr_header(parentitem, selitem, data2pass)
        if selitem == 'leadfields':
            data2pass = self.lf.leadfield
            items = listparse.leadfields(parentitem, selitem, data2pass)
        if selitem == 'grid':
            data2pass = self.grid
            items = listparse.grid(parentitem, selitem, data2pass)
        if selitem == 'timef':
            data2pass = frametimef.t
            items = listparse.timef(parentitem, selitem, data2pass)
        if selitem == 'ICA':
            data2pass = self.ica
            items = listparse.ica(parentitem, selitem, data2pass)
            self.tree_ctrl_1.AppendItem(self.ICA, 'Activation Matrix')
            self.tree_ctrl_1.AppendItem(self.ICA, 'Weight Matrix')
        if selitem == 'Gradiometer Channels':
            data2pass = frameCHAN.meg
            items = listparse.channels(parentitem, selitem, data2pass)
        if selitem == 'Trigger Channels':
            data2pass = frameCHAN.trig
            items = listparse.channels(parentitem, selitem, data2pass)
        if selitem == 'fftpow':
            data2pass = frame1.fftpow
            items = listparse.fftpow(parentitem, selitem, frame1.fftfreqs, frame1.fftpow)
        if selitem == 'fit':
            data2pass = frame1.fit
            items = listparse.fit(parentitem, selitem, data2pass)
        if selitem == 'Project_Utils':
            frame1.projectstats()
 
        if selitem == 'dipoles':
            from pylab import figure,subplot,scatter,show, plot, legend
            print 'test'
            figure()
            subplot(2,2,1);scatter(self.points[:,0], self.points[:,1])
            subplot(2,2,2);scatter(self.points[:,0], self.points[:,2])
            subplot(2,2,3);scatter(self.points[:,1], self.points[:,2])
            subplot(2,2,4);plot(self.dips['params']);legend(self.dips['labels'])
            show()
 
        if selitem == 'DiskUsage_by_PID':
            # make a square figure and axes
            figure(1, figsize=(6,6))
            ax = axes([0.1, 0.1, 0.8, 0.8])
            labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
            fracs = [15,30,45, 10]
            explode=(0, 0.05, 0, 0)
            pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
            title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
            show()
        try:
 
            for i in items:
                index = self.list_ctrl_1.InsertStringItem(sys.maxint, i[0]) #num_items, selitem)
                self.list_ctrl_1.SetStringItem(index, 1, i[1])
            num_items = self.list_ctrl_1.GetItemCount()
        except UnboundLocalError:
            print 'no matching item'
 
 
    def textentry(self, event): # wxGlade: MyFrame1.<event_handler>
        dlg = wx.TextEntryDialog(self, 'Enter some text','Text Entry')
        dlg.SetValue("Default")
        if dlg.ShowModal() == wx.ID_OK:
            self.SetStatusText('You entered: %s\n' % dlg.GetValue())
        dlg.Destroy()
 
    def buttonhand(self, event): # wxGlade: MyFrame1.<event_handler>
        print self.tx.GetValue()
 
    def loadchan(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `loadchan' "
        try:
            self.datapdf
        except AttributeError:
            print 'no data loaded yet'
            dlg = wx.MessageDialog(self, 'I dont think you meant to do that... No Data Loade Yet', 'data error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            frame1.openfile(event)
        frameCHAN.Show()
 
    def loadchan2(self, event):
        print "Event handler `loadchan' "
 
        def loadfunction(event):
            print 'loading channels', chchoice.GetStringSelection()
            pnl2.DestroyChildren()
            try:
                self.megpath
            except AttributeError:
                st3 = wx.StaticText(pnl2, 1, 'No Path to Data File')
                self.openfile('null')
 
            self.ch = channel.index(self.megpath, chchoice.GetStringSelection())
            frm.SetStatusText('Number of Ch Loaded: '+str(self.ch.channelsortedlabels.shape[0]))
            st3 = wx.TextCtrl(pnl2, -1, str(self.ch.channelsortedlabels),style=wx.TE_MULTILINE, size=(205,195))
            self.tree_ctrl_1.AppendItem(self.MEGPROC,'Channels: '+str(chchoice.GetStringSelection()))
 
        frm = wx.Frame(None, title="Load Channels")
        hbox = wx.BoxSizer(wx.VERTICAL)
        pnl1 = wx.Panel(frm, -1)
        st = wx.StaticText(pnl1, -1, 'Select Channels:')
        hbox.Add(st, 1)
        chchoice = wx.Choice(pnl1, -1, choices=["meg", "ref", "trig"])
        hbox.Add(chchoice,1)
        loadbutton = wx.Button(pnl1, -1, 'Load')
        hbox.Add(loadbutton, 1)
        hbox2 = wx.BoxSizer(wx.VERTICAL)
        hbox.Add(hbox2, 0, wx.LEFT | wx.TOP, 10)
        pnl1.SetSizer(hbox)
        pnl1.Fit()
        pnl2 = wx.Panel(frm, -1, (150, 20), (210, 210), style=wx.SUNKEN_BORDER)
        st3 = wx.StaticText(pnl2, -1, 'No Channels Loaded Yet')
        frm.Show()
        frm.Centre()
        loadbutton.Bind(wx.EVT_BUTTON, loadfunction)
        frm.CreateStatusBar()
 
 
 
    def openmri(self, event): # wxGlade: MyFrame1.<event_handler>
        from mri import mr2nifti, img
        from numpy import ndarray
        print "Event handler `openmri'"
        try:
            self.WORKSPACE #= self.tree_ctrl_1.AddRoot('Workspace')
        except AttributeError:
            self.WORKSPACE = self.tree_ctrl_1.AddRoot('Workspace')
        try:
            self.MRI #= self.tree_ctrl_1.AddRoot('Workspace')
        except AttributeError:
            self.MRI = self.tree_ctrl_1.AppendItem(self.WORKSPACE, 'MRI')
        dlg = wx.FileDialog(self, "Select an MRI file", os.getcwd(), "", "*", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.mripath = path = dlg.GetPath()
            dlg.Destroy()
            print path
            self.mrimypath = mypath = os.path.basename(path)
            self.SetStatusText("MRI Loaded: %s" % mypath,0)
 
            self.MRDATA = self.tree_ctrl_1.AppendItem(self.MRI, mypath)
 
            self.list_ctrl_1.InsertColumn(0, 'Data')
            self.list_ctrl_1.InsertColumn(0, 'Value')
            self.list_ctrl_1.SetColumnWidth(0, 140)
            self.list_ctrl_1.SetColumnWidth(1, 193)
        else:
            dlg.Destroy()
            return
 
        if str(self.mripath).find('img') != -1: #img
            self.mr = self.nim = img.read(str(self.mripath))
            print 'reading analyze'
        elif str(self.mripath).find('nii.gz') != -1: #nii.gz
            print 'reading compressed nifti'
            self.mr = self.nim = img.read(str(self.mripath))
            print self.mr.pixdim, self.mr.getQForm()
        elif str(self.mripath).find('nii') != -1: #nii
            print 'reading nifti'
            self.mr = self.nim = img.read(str(self.mripath))
        else:  #try dicom
            from mri import pydicom
            pathtodicom = os.path.dirname(str(self.mripath))
            pre = os.path.basename(self.mripath)[0:2]
            self.mr = pydicom.read(pathtodicom, prefix=pre)
 
            text = "Select a save file name"
            suffix='.nii.gz'; filter='*.nii.gz'
            for i in self.mr.seqdict.keys():
                dialog = wx.FileDialog(None, text, os.getcwd(), suffix, filter, wx.SAVE)
                if dialog.ShowModal() == wx.ID_OK:
                    fn = (dialog.GetPaths())
                    print fn
 
                    mr2nifti.start(self.mr, str(fn[0]))
                else:
                    print 'Nothing was choosen'
                dialog.Destroy()
 
            return
 
        dataprefix = 'm'
        self.HDR = self.tree_ctrl_1.AppendItem(self.MRDATA, 'mr_header')
        try:
 
            if type(eval(self.nim.description)[0]) == ndarray: #index points saved here. major hack
                self.lpa = eval(self.nim.description)[0]
                self.rpa = eval(self.nim.description)[1]
                self.nas = eval(self.nim.description)[2]
                dlg = wx.MessageDialog(self, 'Your file is already Coregistered', 'MRI file Info', wx.OK|wx.ICON_INFORMATION)
                dlg.ShowModal()
                dlg.Destroy()
        except SyntaxError:
            dlg = wx.MessageDialog(self, 'Your file is not Coregistered', 'MRI file error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
 
        #self.VoxDim = abs(sum(self.mr.getQForm()[0:3],axis=1)) #get vox dims from QForm matrix
        self.VoxDim = self.mr.voxdim[::-1] #get vox dims from reversed voxdim
 
 
 
    def openbrain(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `openbrain'"
        try:
            self.WORKSPACE #= self.tree_ctrl_1.AddRoot('Workspace')
        except AttributeError:
            self.WORKSPACE = self.tree_ctrl_1.AddRoot('Workspace')
        try:
            self.MRI #= self.tree_ctrl_1.AddRoot('Workspace')
        except AttributeError:
            self.MRI = self.tree_ctrl_1.AppendItem(self.WORKSPACE, 'MRI')
 
        dlg = wx.FileDialog(self, "Select a Analyze Brain Extracted MRI file", os.getcwd(), "", "*.img", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.brainpath = path = dlg.GetPath()
            self.brainmypath = mypath = os.path.basename(path)
            self.SetStatusText("MRI Brain Loaded: %s" % mypath,0)
            self.MRIBrain = self.tree_ctrl_1.AppendItem(frame1.WORKSPACE, 'MRI_Brain')
            self.MRDATA = self.tree_ctrl_1.AppendItem(self.MRIBrain, mypath)
            #self.MRIPROC = self.tree_ctrl_1.AppendItem(self.MRI, 'Processes')
 
            self.list_ctrl_1.InsertColumn(0, 'Data')
            self.list_ctrl_1.InsertColumn(0, 'Value')
            self.list_ctrl_1.SetColumnWidth(0, 140)
            self.list_ctrl_1.SetColumnWidth(1, 153)
 
        dlg.Destroy()
 
        self.mr = self.brain = img.read(str(self.brainpath))
        self.HDR = self.tree_ctrl_1.AppendItem(self.MRDATA, 'mr_header')
 
 
    def coregistermri(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `coregistermri'"
        print self.mripath
        try:
            self.mripath
        except AttributeError:
            dlg = wx.MessageDialog(self, 'First you need to load MRI data file', 'MRI file error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            self.openmri(event)
            #viewmri.display(self.nim)
        frameCOREG.Show()
        frameCOREG.loadmri(event)
 
    def leadfieldgen(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `leadfieldgen'"
        try:
            self.datapdf# = self.megpath
        except AttributeError:
            dlg = wx.MessageDialog(self, 'First you need to load MEG data file', 'MEG file error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            self.openfile(event)
            datapdf = self.megpath
        try:
            self.grid
        except AttributeError:
            dlg = wx.MessageDialog(self, 'No grid points detected. Do that first.', 'Grid error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
 
            frame2.Show()
            #frame2.gridcalc(event)
        self.lf = leadfield.calc(self.datapdf, self.ch, self.grid)
        #frame1.LF = frame1.tree_ctrl_1.AppendItem(frame1.MEGDATA, 'grid')
        self.LF = self.tree_ctrl_1.AppendItem(self.PROCESSES, 'leadfields')
        numlf = shape(self.lf.leadfield)
        self.leadfields = self.lf.leadfield
        print numlf
        self.SetStatusText("LeadFields Calculated: %s" % unicode(numlf))
 
 
    def sourcespacegrid(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `sourcespacegrid' "
        frame2.Show()
 
    def timef(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `timef'"
        frametimef.Show()
 
 
    def plotselected(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `plotselected'"
        selitem = self.tree_ctrl_1.GetItemText(self.itemID)
        data2plot = eval('frame1.'+selitem)
        if selitem == 'data_block':
            frame1.numplots = frame1.d.numofepochs
            frame1.timeaxis = frame1.d.wintime
            self.plot2ddata(event)
 
        if selitem == 'induced_power':
            t = self.t
            figure();imshow(real(t.P), \
            extent=(int(t.timevals[0]), int(t.timevals[-1]), int(t.freqrange[1]), \
            int(t.freqrange[0])) \
            ,aspect='auto')
            colorbar()
            show()
        if selitem == 'induced_powerlog':
            t = self.t
            figure();imshow(real(t.Plog), \
            extent=(int(t.timevals[0]), int(t.timevals[-1]), int(t.freqrange[1]), \
            int(t.freqrange[0])) \
            ,aspect='auto')
            colorbar()
            show()
        if selitem == 'phaselocking_factor':
            t = self.t
            figure();imshow(abs(t.itcvals), \
            extent=(int(t.timevals[0]), int(t.timevals[-1]), int(t.freqrange[1]), \
            int(t.freqrange[0])) \
            ,aspect='auto')
            colorbar()
            show()
        if selitem == 'power_of_continious_data':
            t = self.t
            figure();imshow(abs(t.tmpallallepochs), \
            extent=(int(t.timevals[0]), int(t.timevals[-1]), int(t.freqrange[1]), \
            int(t.freqrange[0])) \
            ,aspect='auto')
            colorbar()
            show()
 
        if selitem == 'ICA':
            figure();plot(self.ica['A'].T);show();
        if selitem == 'headshape':
            self.plotheadshape(event)
        if selitem == 'grid':
            plotvtk.display(self.grid)
        if selitem == 'Activation Matrix':
            figure()
            for i in arange(shape(self.ica['A'])[0]):
                plot(self.ica['A'][i], label=str(i))
            legend()
            show()
        if selitem == 'Weight Matrix':
            megcontour.display(self.ica['S'].T, self.ch.chanlocs, subplot='on')
        if selitem == 'projection':
            #self.plot2ddata(event)
            figure();plot(self.projection);show()
        if selitem == 'avg':
            #self.plotdata(event, frame1.avg)
            self.data2plot = frame1.avg
            self.plot2ddata(event)
        if selitem == 'epoch':
            self.data2plot = frame1.data_blockepoch
            frame1.numplots = frameCUT.numofepochs
            frame1.timeaxis = frameCUT.timeaxis
            self.plot2ddata(frame1.epoch)
        if selitem == 'Gradiometer Channels':
            self.plotsensors(event)
 
        if selitem == 'Gradiometer Data':
            self.plotdata(event, self.d.data_block[:,self.chantypeind == 'meg'])
        if selitem == 'Trigger Data':
            self.plotdata(event, self.d.data_block[:,self.chantypeind == 'trig'])
 
        if selitem == 'fftpow':
            frame1.timeaxis = frame1.fftfreqs
            self.plot2ddata(event)
            frame1.numplots = 1
            frame2DPLOT.checkbox_10.Enable(True)
 
 
            #figure();plot(frame1.fftfreqs, frame1.fftpow);show()
 
            #figure();plot(self.ica['A'].T);show();
 
        if selitem == 'offset':
            frame1.numplots = frame1.d.numofepochs
            frame1.timeaxis = frame1.d.wintime
            self.plot2ddata(event)
 
        if selitem == 'leadfields':
            print 'how the hell do you expect me to plot this?'
 
        if selitem == 'fit':
            plotvtk.display(self.fit)
        if selitem == 'fitimage':
            viewmri.display(frame1.fitimage[0], colormap=cm.hot)
 
 
    def ica(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `ica' "
        frameICA.Show()
    def weightfit(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `weightfit' "
        frameWEIGHT.Show()
 
    def plotheadshape(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `plotheadshape' "
        plotvtk.display(self.p.hs.hs_point)
 
    def plotsensors(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `plotsensors' "
        s=sensors.locations(self.datapdf)
        plotvtk.display(s.megchlpos)
 
    def plotindex(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `plotindex' "
        ind=hstack([self.p.hs.index_lpa,self.p.hs.index_rpa,self.p.hs.index_nasion]).reshape(3,3)
        plotvtk.display(ind)
 
    def plothssensind(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `plothssensind' "
        ind=hstack([self.p.hs.index_lpa,self.p.hs.index_rpa,self.p.hs.index_nasion]).reshape(3,3)
        s=sensors.locations(self.datapdf)
        plotvtk.display(self.p.hs.hs_point, s.megchlpos, ind)
 
    def plothsinddips(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `plothsinddips'"
        try:
            ind=hstack([self.p.hs.index_lpa,self.p.hs.index_rpa,self.p.hs.index_nasion]).reshape(3,3)
        except AttributeError:
            print 'prerequisite headshape file not found. first load'
            dlg = wx.MessageDialog(self, 'First you need to load headshape data file', 'hs file error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            self.loadhs(event)
            ind=hstack([self.p.hs.index_lpa,self.p.hs.index_rpa,self.p.hs.index_nasion]).reshape(3,3)
        s = self.points/1000
        plotvtk.display(self.p.hs.hs_point, s, ind)
 
    def mri2D(self, event): # wxGlade: MyFrame1.<event_handler>
        from mri import viewmri
        print "Event handler `mri2D' "
        try:
            viewmri.display(self.nim)
        except AttributeError:
            dlg = wx.MessageDialog(self, 'First you need to load MRI data file', 'MRI file error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            self.openmri(event)
            viewmri.display(self.nim)
 
    def mri3D(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `mri3D'"
        try:
            viewmri.display(self.nim)
        except AttributeError:
            dlg = wx.MessageDialog(self, 'First you need to load MRI data file', 'MRI file error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
            self.openmri(event)
        mr2vtk.convert(self.nim.data, path='~/', filename='tmpmrvtk')
        vtkview.vtkrender(d1=os.getenv('HOME')+'/tmpmrvtk.vtk')
 
    def newsession(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `newsession'"
        try:
            self.WORKSPACE
        except AttributeError:
            self.WORKSPACE = self.tree_ctrl_1.AddRoot('Workspace')
        try:
            self.SESSION
            self.id = 1
        except AttributeError:
            self.id = 1
            self.SESSION = self.tree_ctrl_1.AppendItem(self.WORKSPACE, 'Session'+str(self.id))
        else:
            self.id = self.id+1
            self.SESSION = self.tree_ctrl_1.AppendItem(self.WORKSPACE, 'Session'+str(self.id))
 
    def saveworkspace(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `saveworkspace' "
        self.sessionhandler(event)
 
    def sourceprojection(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `sourceprojection' not implemented"
        frameSP.Show()
 
    def cutdata(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `averagedata' not implemented"
        frameCUT.Show()
 
    def getevents(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `getevents' "
        pass
        frameTRIG.Show()
 
    def offsetcorrect(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `offsetcorrect'"
        try:
            eval('self.'+frame1.selitem)
        except AttributeError:
            print 'item doesnt exist'
            return
        frame1.OFFSET = frame1.tree_ctrl_1.AppendItem(frame1.PROCESSES, 'offset')
        frame1.offset = offset.correct(eval('self.'+frame1.selitem))
        frame1.offsetepochs = frame1.data_blockepochs
 
    def epochdata(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `epochdata' "
        frameEPOCH.Show()
 
    def plot2ddata(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `plot2ddata' not implemented"
        frame2DPLOT.Show()
    def recordmacro(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `recordmacro' not implemented"
        event.Skip()
 
    def playbackmacro(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `playbackmacro' not implemented"
        #/home/danc/vault/decrypted/programming/python/pymeg/gui/e,rfhp1.0Hz,COH
 
 
    def listitemselected(self, event): # wxGlade: MyFrame1.<event_handler>
        self.listind = self.list_ctrl_1.GetFocusedItem()
        self.listitem = self.list_ctrl_1.GetItem(self.listind,1).GetText()
        self.listdata = self.list_ctrl_1.GetItem(self.listind,0).GetText()
        self.SetStatusText("You selected value: %s" % self.listitem, 1)
        self.SetStatusText("You selected value: %s" % self.listdata, 2)
        self.listitem = str(self.listitem)
        self.listdata = str(self.listdata)
 
    def fft(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `fft' "
        frameFFT.Show()
 
#sourcesolution2img.build
 
    def badch(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `badch' "
        frameBADCH.Show()
 
    def batch(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `batch' "
        #self.openfile(event, batch='/home/danc/vault/decrypted/programming/python/pymeg/gui/data/0868ball/ballbounc3/10%01%08@11:08/1/e,rfDC')
        #self.openfile(event, batch='/home/danc/vault/decrypted/programming/python/pymeg/gui/e,rfhp1.0Hz,COH')
        #self.openfile(event, batch='/home/danc/python/data/1001/e,rfhp1.0Hz,COH')
        #self.openfile(event, batch='/home/danc/python/data/0868sef/e,rfhp1.0Hz,COH')
        self.openfile(event, batch='/home/danc/vault/decrypted/programming/python/pymeg/gui/data/0888nback/c,rfhp0.1Hz')
        frameCHAN.signalbutton.SetValue(True)
        frameCHAN.getchind(event)
        frameCHAN.loadchannels(event)
 
        frame1.selitem = 'data_block'
        frameFFT.Show()
        frameFFT.radio_box_1.SetSelection(1)
        frameFFT.getselected(event)
        frameFFT.text_ctrl_11.SetValue('400')
        frameFFT.runfft(event)
 
        frameBADCH.calcbadch(event)
        frameBADCH.Show()
        frameBADCH.removechsel(event)
 
 
    def psel(self, event): # wxGlade: MyFrame1.<event_handler>
        subprocess.call('psel')
 
    def ape(self, event): # wxGlade: MyFrame1.<event_handler>
        subprocess.call('ape')
 
    def tapwin(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `tapwin' "
        frameTAPWIN.Show()
 
    def projectutils(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `projectutils' not implemented"
        try:
            self.WORKSPACE
        except AttributeError:
            self.WORKSPACE = self.tree_ctrl_1.AddRoot('Workspace')
            self.PROJECT = self.tree_ctrl_1.AppendItem(self.WORKSPACE, 'Project_Utils')
            self.DUPID = self.tree_ctrl_1.AppendItem(self.PROJECT, 'DiskUsage_by_PID')
 
        self.list_ctrl_1.InsertColumn(0, 'Val')
        self.list_ctrl_1.InsertColumn(0, 'Val')
        self.list_ctrl_1.InsertColumn(0, 'Data')
        self.list_ctrl_1.SetColumnWidth(0, 140)
        self.list_ctrl_1.SetColumnWidth(1, 193)
        self.list_ctrl_1.SetColumnWidth(2, 140)
 
    def projectstats(self):
        statdict = {}
        statdict['project'] = 'test'
        stage = os.environ['STAGE']
        p = subprocess.Popen('du -s '+stage, shell=True, stdout=subprocess.PIPE)
        out = p.stdout.readlines()
 
        statdict['Disk Usage'] = str(int(out[0].split('\t')[0])/1000.0)+'MB'
        statdict['Disk Allocated'] = '10GB'
        statdict['Free Space'] = str(1-(int(out[0].split('\t')[0])/1000.0)/10000)+'%'
 
        projectdu()
 
        try:
 
            for i in statdict:
                index = self.list_ctrl_1.InsertStringItem(sys.maxint, i) #num_items, selitem)
                self.list_ctrl_1.SetStringItem(index, 1, statdict[i])
            num_items = self.list_ctrl_1.GetItemCount()
        except UnboundLocalError:
            print 'no matching item'
 
    def loaddipolereport(self, event): # wxGlade: MyFrame1.<event_handler>
        print "use load Dipole instead`loaddipolereport' "
        #~ self.createworkspace()
        #~ dlg = wx.FileDialog(self, "Select a Dipole Report file(s)", os.getcwd(), "", "*", wx.MULTIPLE)
        #~ datafile = []
        #~ if dlg.ShowModal() == wx.ID_OK:
            #~ dlg.Destroy()
            #~ for i in range(0, len(dlg.GetPaths())):
                #~ datafile.append(str(dlg.GetPaths()[i]))
            #~ print 'Selected:', datafile
        #~ else:
           #~ print 'Nothing was selected.'
        #~ dlg.Destroy()
 
 
 
    def loaddipoles(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `loaddipoles'"
        from pdf2py import readwrite,lA2array
        self.createworkspace()
        from meg import dipole
        #datafile = file.open()
        dlg = wx.FileDialog(self, "Select a Dipole file(s)", os.getcwd(), "",wildcard = "Dipole File (*lA)|*lA|Dipole Report(*.drf)|*.drf")
        #dlg = wx.FileDialog(self, "Select a Dipole file(s)", os.getcwd(), "", "*lA|*txt", wx.MULTIPLE)
        datafile = []
        if dlg.ShowModal() == wx.ID_OK:
            dlg.Destroy()
            for i in range(0, len(dlg.GetPaths())):
                datafile.append(str(dlg.GetPaths()[i]))
            print 'Selected:', datafile
        else:
           print 'Nothing was selected.'
        dlg.Destroy()
 
        self.points = array([])
        self.dips = {}
        self.dips['params'] = array([])
        self.gof = array([])
 
 
        for i in datafile:
            if datafile[0].split(',')[-1] == 'lA': #pdf
                lA = lA2array.calc(i)
                self.points = append(self.points, lA.dips[:,1:4]*1000) #xyz from meters to mm
            else:
                lA = dipole.parsereport(i)
                self.points = append(self.points, lA.dips[:,1:4]*10) #xyz from cm to mm
 
            self.dips['params'] = append(self.dips['params'], lA.dips[:,:]) #xyz in 
            sz = size(lA.dips[:,:],1) 
            print shape(self.points)
            gof_ind = lA.labels.index('GoF')
            self.gof = append(self.gof, lA.dips[:,gof_ind])
 
        self.points = self.points.reshape(len(self.points)/3,3)
        self.dips['params'] = self.dips['params'].reshape(len(self.dips['params'])/sz,sz)
        self.dips['labels'] = lA.labels
        readwrite.writedata(self.dips, os.path.dirname(i)+'/'+'ALLDIPS')
 
        #~ if datafile[0].split(',')[-1] == 'lA': #pdf
            #~ 
        #~ 
#~ 
            #~ self.points = array([])
            #~ self.dips = {}
            #~ self.dips['params'] = array([])
            #~ self.gof = array([])
            #~ for i in datafile:
                #~ lA = lA2array.calc(i)
                #~ #readwrite.writedata(lA, os.path.dirname(i)+'/'+os.path.basename(i))
                #~ self.points = append(self.points, lA.dips[:,1:4]*1000) #xyz in mm
                #~ self.dips['params'] = append(self.dips['params'], lA.dips[:,:]) #xyz in 
                #~ sz = size(lA.dips[:,:],1) 
                #~ print shape(self.points)
                #~ gof_ind = lA.labels.index('GoF')
                #~ self.gof = append(self.gof, lA.dips[:,gof_ind])
            #~ #self.dips = array(self.points)
            #~ self.points = self.points.reshape(len(self.points)/3,3)
            #~ self.dips['params'] = self.dips['params'].reshape(len(self.dips['params'])/sz,sz)
            #~ self.dips['labels'] = lA.labels
            #~ readwrite.writedata(self.dips, os.path.dirname(i)+'/'+'ALLDIPS')
            #~ 
            #~ #figure();plot(self.points);show()
                #~ 
        #~ else:#OR dipole report
            #~ for i in datafile:
                #~ lA = dipole.parsereport(i)
                #~ self.points = append(self.points, lA.dips[:,1:4]*1000) #xyz in mm
 
        self.DIPOLES = self.tree_ctrl_1.AppendItem(self.WORKSPACE, 'dipoles')
 
    def dipoledensity(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `dipoledensity'"
        try: self.points
        except AttributeError:
            print 'prerequisite dipole file not found'
            self.loaddipoles(event)
        try: self.mr
        except AttributeError:
            print 'prerequisite mri file not found'
            self.openmri(event)
 
        try:
            self.lpa
        except AttributeError:
            dlg = wx.MessageDialog(self, 'Your file is not Coregistered', 'MRI file error', wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            #dlg.Destroy()
            frameCOREG.Show()
            frameCOREG.loadmri(event)
        frameDENSITY.lpa_loc.SetLabel(str(frame1.lpa))
        frameDENSITY.rpa_loc.SetLabel(str(frame1.rpa))
        frameDENSITY.nas_loc.SetLabel(str(frame1.nas))
        frameDENSITY.numdipolesval.SetLabel(str(size(frame1.points,0)))
        frameDENSITY.Show()
 
    def loadhs(self, event): # wxGlade: MyFrame1.<event_handler>
        print "Event handler `loadhs'"
        dlg = wx.FileDialog(self, "Select a HS file", os.getcwd(), "", "*", wx.OPEN)
        print dlg.GetPath()
        if dlg.ShowModal() == wx.ID_OK:
            hsfile = dlg.GetPath()
            self.p = headshape.read(str(hsfile))
            self.p.hs = self.p
        dlg.Destroy
 
# end of class MyFrame1
 
 
if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    frame1 = MyFrame1(None, -1, "")
    app.SetTopWindow(frame1)
    frame1.Show()
 
    frameGUAGE = Guage(None, -1, "")
    #frameGUAGE.Show()
    frame2 = MyFrameGrid(None, -1, "")
    frametimef = MyFrame(None, -1, "")
    frameICA = MyFrameICA(None, -1, "")
    frameWEIGHT = MyFrameWEIGHTFIT(None, -1, "")
    frameCOREG = MyFrameCOREG(None, -1, "")
    frameSP = MyFrameSP(None, -1, "")
    frameCH = MyFrameCH(None, -1, "")
    frameTRIG = MyFrameTRIG(None, -1, "")
    frameCUT = MyFrameCUT(None, -1, "")
    frameEPOCH = MyFrameEPOCH(None, -1, "")
    frameCHAN = MyFrameCHAN(None, -1, "")
    frame2DPLOT = MyFrame2DPLOT(None, -1, "")
    frameFFT = MyFrameFFT(None, -1, "")
    frameBADCH = MyFrameBADCH(None, -1, "")
    frameTAPWIN = TAPWIN(None, -1, "")
    frameDENSITY = MyFrameDENSITY(None, -1, "")
    #frameDENSITY.Show()
    app.MainLoop()