#!/usr/bin/env python
# -*- coding: CP1252 -*-
#
# generated by wxGlade 0.7.0 on Thu Nov 12 17:51:03 2015
#

import wx
from wx.lib.wordwrap import wordwrap
import os
import collections

# begin wxGlade: dependencies
import gettext
# end wxGlade

# begin wxGlade: extracode
# end wxGlade
import numpy as np
import pandas as pd
import csv
import sys
import pprint
from sklearn.ensemble import ExtraTreesClassifier
from sklearn import svm

import gen_train_data_w_gui as gen_train_data
import classify_peaks_w_gui as classific
import plot_peaks_w_gui as plot_peaks
import imp
imp.reload(gen_train_data)
imp.reload(classific)
imp.reload(plot_peaks)
###############

analysis_pars = collections.OrderedDict()
    
analysis_pars['data_folder'] = os.getcwd()  #data_folder
analysis_pars['fn_match'] = '*.csv' #fn_match
analysis_pars['fn_extension'] = '.csv' #fn_extension
analysis_pars['set_col_names'] = True #set_col_names
analysis_pars['DOWN_SAMPLE_FACTOR'] = 1 #DOWN_SAMPLE_FACTOR
analysis_pars['display_deriv2'] = True #display_deriv2
analysis_pars['PEAK_NPNTS_THRESH'] = 1 #PEAK_NPNTS_THRESH
analysis_pars['DERIV2_THRESH'] = 0.5 #DERIV2_THRESH
analysis_pars['PEAK_POLARITY'] = 1 #PEAK_POLARITY
analysis_pars['START'] = '' #START
analysis_pars['END'] = '' #END
analysis_pars['FILTER_WIN_SIZE'] = 5 #FILTER_WIN_SIZE
analysis_pars['FILTER_SIGMA'] = 3.0 #FILTER_SIGMA
analysis_pars['PEAK_PRE_CROP_WIN'] = '' #PEAK_PRE_CROP_WIN
analysis_pars['PEAK_POST_CROP_WIN'] = '' #PEAK_POST_CROP_WIN
analysis_pars['PEAK_DISPLAY_X_PRE'] = ''
analysis_pars['PEAK_DISPLAY_X_POST'] = ''
analysis_pars['PEAK_DISPLAY_Y_BELOW'] = ''
analysis_pars['PEAK_DISPLAY_Y_ABOVE'] = ''        
analysis_pars['DISPLAY_WIN'] = '' #DISPLAY_WIN
analysis_pars['yrange'] = '' #yrange
analysis_pars['detect_features_str'] = 'threshold' #detect_features
analysis_pars['detect_features'] = analysis_pars['detect_features_str'].split() 
analysis_pars['Peak_Classifier'] = ExtraTreesClassifier(n_estimators=100, 
                                        max_depth=None, min_samples_split=1, 
                                        random_state=0)
analysis_pars['Peak_FIT_PEAK_PRE_CROP_WIN'] = ''
analysis_pars['Peak_FIT_POST_PRE_CROP_WIN'] = ''


analysis_pars['Feature_Classifier'] = svm.SVR(gamma=0.001, C=100.)
analysis_pars['Feature_FIT_PEAK_PRE_CROP_WIN'] = ''
analysis_pars['Feature_FIT_POST_PRE_CROP_WIN'] = ''

analysis_pars['plot_full_traces'] = True

###############


class MyDialog(wx.Dialog):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyDialog.__init__
        wx.Dialog.__init__(self, *args, **kwds)
        self.notebook_1 = wx.Notebook(self, wx.ID_ANY)
        self.notebook_1_pane_1 = wx.Panel(self.notebook_1, wx.ID_ANY)
        self.label_1 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("Data Folder"))
        self.text_ctrl_1 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, os.getcwd()) 
        self.button_1 = wx.Button(self.notebook_1_pane_1, wx.ID_ANY, ("Browse"))
        self.label_2 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("File Type"))
        self.choice_1 = wx.Choice(self.notebook_1_pane_1, wx.ID_ANY, choices=[(".csv"), (".txt")])
        self.label_3 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("Peak"))
        self.choice_2 = wx.Choice(self.notebook_1_pane_1, wx.ID_ANY, choices=[("Maxima"), ("Minima")])
        self.checkbox_2 = wx.CheckBox(self.notebook_1_pane_1, wx.ID_ANY, ("Double Deriv."))
        self.checkbox_2.SetValue(True)
        self.label_4 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("Thresholds"))
        self.text_ctrl_2 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "50")
        self.text_ctrl_19 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "0.5")
        
        self.label_5 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("Crop"))
        self.text_ctrl_3 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "50")
        self.text_ctrl_4 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "30")
        self.label_6 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("Display X"))
        self.text_ctrl_5 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "300")
        self.text_ctrl_6 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "400")
        self.label_7 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("Display Y"))
        self.text_ctrl_7 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "-1e-3")
        
        self.text_ctrl_8 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "1e-3")
        self.label_8 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("Down Sample"))
        self.text_ctrl_9 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "5")
        self.label_9 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("Range"))
        self.text_ctrl_10 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "")
        self.text_ctrl_11 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "")
        self.label_10 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("Filter"))
        self.text_ctrl_12 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "21")
        self.text_ctrl_13 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "10")
        self.label_11 = wx.StaticText(self.notebook_1_pane_1, wx.ID_ANY, ("Feature List"))
        self.text_ctrl_14 = wx.TextCtrl(self.notebook_1_pane_1, wx.ID_ANY, "Threshold1 Threshold2")
        self.button_8 = wx.Button(self.notebook_1_pane_1, wx.ID_ANY, ("Browse peaks"))
        self.button_2 = wx.Button(self.notebook_1_pane_1, wx.ID_ANY, ("Start"))
        
        self.notebook_1_pane_2 = wx.Panel(self.notebook_1, wx.ID_ANY)
        self.label_12 = wx.StaticText(self.notebook_1_pane_2, wx.ID_ANY, ("Peak Classification"))
        self.label_13 = wx.StaticText(self.notebook_1_pane_2, wx.ID_ANY, ("Num Points"))
        self.text_ctrl_15 = wx.TextCtrl(self.notebook_1_pane_2, wx.ID_ANY, "50")
        self.text_ctrl_16 = wx.TextCtrl(self.notebook_1_pane_2, wx.ID_ANY, "30")
        self.label_15 = wx.StaticText(self.notebook_1_pane_2, wx.ID_ANY, ("Feature detection"))
        self.label_16 = wx.StaticText(self.notebook_1_pane_2, wx.ID_ANY, ("Num Points"))
        self.text_ctrl_17 = wx.TextCtrl(self.notebook_1_pane_2, wx.ID_ANY, "30")
        self.text_ctrl_18 = wx.TextCtrl(self.notebook_1_pane_2, wx.ID_ANY, "30")
        self.button_3 = wx.Button(self.notebook_1_pane_2, wx.ID_ANY, ("Start"))
        
        self.notebook_1_pane_3 = wx.Panel(self.notebook_1, wx.ID_ANY)
        self.label_17 = wx.StaticText(self.notebook_1_pane_3, wx.ID_ANY, ("Show all\n"))
        self.checkbox_1 = wx.CheckBox(self.notebook_1_pane_3, wx.ID_ANY, "")
        self.checkbox_1.SetValue(True)
        self.button_4 = wx.Button(self.notebook_1_pane_3, wx.ID_ANY, ("Start"))
        
        self.notebook_1_pane_4 = wx.Panel(self.notebook_1, wx.ID_ANY)
        self.label_14 = wx.StaticText(self.notebook_1_pane_4, wx.ID_ANY, ("Save parameters"))
        #self.text_ctrl_19 = wx.TextCtrl(self.notebook_1_pane_4, wx.ID_ANY, "parameters")
        self.button_5 = wx.Button(self.notebook_1_pane_4, wx.ID_ANY, ("Save"))
        self.label_18 = wx.StaticText(self.notebook_1_pane_4, wx.ID_ANY, ("Load parameters"))
        #self.text_ctrl_20 = wx.TextCtrl(self.notebook_1_pane_4, wx.ID_ANY, "parameters")
        self.button_6 = wx.Button(self.notebook_1_pane_4, wx.ID_ANY, ("Load"))
        
        self.notebook_1_pane_5 = wx.Panel(self.notebook_1, wx.ID_ANY)
        self.button_7 = wx.Button(self.notebook_1_pane_5, wx.ID_ANY, ("About"))
        self.OnAboutButton('') # show the terms of use in the begining.

        self.__set_properties()
        self.__do_layout()

        #self.Bind(wx.EVT_BUTTON, self.browse_func, self.button_1)
        self.Bind(wx.EVT_BUTTON, lambda evt, title_text =
                'Choose folder containing raw data files': 
                self.select_folder(evt, title_text), self.button_1)
        self.Bind(wx.EVT_BUTTON, self.gen_examples_start_func, self.button_2)
        self.Bind(wx.EVT_BUTTON, self.classific_start_func, self.button_3)
        self.Bind(wx.EVT_BUTTON, self.plot_start_func, self.button_4)
        self.Bind(wx.EVT_BUTTON, self.OnSaveAs, self.button_5)
        self.Bind(wx.EVT_BUTTON, self.OnOpen, self.button_6)
        self.Bind(wx.EVT_BUTTON, self.OnAboutButton, self.button_7)
        self.Bind(wx.EVT_BUTTON, self.browse_peaks_func, self.button_8)
        # end wxGlade
        # closing the window
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
    
    def OnCloseWindow(self, event):
        # http://stackoverflow.com/questions/26289275/how-do-i-stop-a-windows-
        #from-closing-after-i-raise-wx-evt-close-in-wxpython
        dialog = (wx.MessageDialog(self, message = "Are you sure you want to " 
                                "quit?", caption = "Caption", style = 
                                wx.YES_NO, pos = wx.DefaultPosition))
        response = dialog.ShowModal()
    
        if (response == wx.ID_YES):
            #Pairs = []
            #self.list_ctrl_1.DeleteAllItems()
            #self.index = 0
            self.Destroy()
        #elif (response == wx.ID_NO):
        #   wx.CloseEvent.Veto(True)
        #event.Skip()

    def __set_properties(self):
        # begin wxGlade: MyDialog.__set_properties
        self.SetTitle(("Peak_Detect"))
        self.label_1.SetToolTipString(("Folder containing raw data files"))
        self.text_ctrl_1.SetMinSize((150, -1))
        self.text_ctrl_1.SetToolTipString(("Folder containing raw data files"))
        self.button_1.SetToolTipString(("Choose folder containing raw data files"))
        self.label_2.SetToolTipString(("Raw data files to select"))
        self.choice_1.SetToolTipString(("Raw data files to select"))
        self.choice_1.SetSelection(0)
        self.label_3.SetToolTipString(("Choose whether events are peaks or dips"))
        self.choice_2.SetToolTipString(("Choose whether events are peaks or dips"))
        self.choice_2.SetSelection(0)
        self.checkbox_2.SetToolTip(wx.ToolTip(("Display double derivative")))
        self.label_4.SetToolTipString(("Adjust thresholds for preliminary peak detection"))
        self.text_ctrl_2.SetToolTipString(("About half the number of points in a typical peak (eg. 50)"))
        
        self.text_ctrl_19.SetToolTipString(("2nd derivative threshold (eg. 0.01 or -0.01)"))
        
        self.label_5.SetToolTipString(("Number of points to crop before and after the peak. Should be enough to include features in the 'Feature List' "))
        self.text_ctrl_3.SetToolTipString(("Before the peak (eg. 50)"))
        self.text_ctrl_4.SetToolTipString(("After the peak (eg. 30)"))
        self.label_6.SetToolTipString(("Number of points to display before and after peak while generating training examples"))
        self.text_ctrl_5.SetToolTipString(("Before the peak (Eg. 300)"))
        self.text_ctrl_6.SetToolTipString(("After the peak (Eg. 400)"))
        self.label_7.SetToolTipString(("Y range to display below and above the mean peak value while generating training examples"))
        self.text_ctrl_7.SetToolTipString(("Below the peak (Eg. -1e-3)"))
        self.text_ctrl_8.SetToolTipString(("Above the peak (Eg. 1e-3)"))
        self.label_8.SetToolTipString(("Down sampling factor if data is sampled at higher frequency than needed."))
        self.text_ctrl_9.SetToolTipString(("Eg. 5"))
        self.label_9.SetToolTipString(("Start and end point of data indices to analyze for each trace. Leave empty for full range."))
        self.text_ctrl_10.SetToolTipString(("Start point (Eg. 1000)"))
        self.text_ctrl_11.SetToolTipString(("End point (Eg. 10000)"))
        self.label_10.SetToolTipString(("Gaussian filter data if it is noisy (window size and sigma in points)."))
        self.text_ctrl_12.SetToolTipString(("Not used any more. Set automatically")) # Window size (Eg. 21) 03/04/16
        self.text_ctrl_13.SetToolTipString(("Window sigma (10)"))
        self.label_11.SetToolTipString(("List of additional features to mark per peak"))
        self.text_ctrl_14.SetToolTipString(("Eg. Threshold1 Threshold2"))
        self.button_8.SetToolTip(wx.ToolTip(("Browse peaks (including false positives)")))
        self.button_2.SetToolTipString(("Start generating training data. Delete/ Rename 'results' directory for new analysis"))
        
        #self.label_12.SetToolTip(wx.ToolTip(_("Choose algorithm for peak classification")))
        self.label_13.SetToolTip(wx.ToolTip(("Number of points to use  before and after the peak. Cannot be more than number of points cropped during training")))
        self.text_ctrl_15.SetToolTip(wx.ToolTip(("Before the peak (Eg. 50)")))
        self.text_ctrl_16.SetToolTip(wx.ToolTip(("After the peak (eg. 30)")))
        #self.label_15.SetToolTip(wx.ToolTip(_("Choose algorithm for feature detection")))
        self.label_16.SetToolTip(wx.ToolTip(("Number of points to use  before and after the peak. Cannot be more than number of points cropped during training")))
        self.text_ctrl_17.SetToolTip(wx.ToolTip(("Before the peak (Eg. 50)")))
        self.text_ctrl_18.SetToolTip(wx.ToolTip(("After the peak (eg. 30)")))
        self.button_3.SetToolTip(wx.ToolTip(("Start training and predicting")))
        self.label_17.SetToolTip(wx.ToolTip(("Show all peaks in the trace")))
        self.checkbox_1.SetToolTip(wx.ToolTip(("Show all peaks in the trace")))
        self.button_4.SetToolTip(wx.ToolTip(("Plot predictions")))
        
        self.label_14.SetToolTip(wx.ToolTip(("Save all parameters")))
        #self.text_ctrl_19.SetToolTip(wx.ToolTip(("File name")))
        self.button_5.SetToolTip(wx.ToolTip(("Choose file to save in")))
        self.label_18.SetToolTip(wx.ToolTip(("Load all parameters")))
        #self.text_ctrl_20.SetToolTip(wx.ToolTip(("Filename")))
        self.button_6.SetToolTip(wx.ToolTip(("Choose parameter file")))
        self.button_7.SetToolTip(wx.ToolTip(("About this software")))
        self.notebook_1.SetMinSize((500, 350))
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: MyDialog.__do_layout
        sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
        
        grid_sizer_5 = wx.FlexGridSizer(2, 3, 3, 3)
        grid_sizer_4 = wx.FlexGridSizer(4, 3, 3, 3)
        grid_sizer_3 = wx.FlexGridSizer(2, 3, 3, 3)
        grid_sizer_2 = wx.FlexGridSizer(6, 3, 3, 3)
        grid_sizer_1 = wx.FlexGridSizer(12, 3, 3, 3)
        
        grid_sizer_1.Add(self.label_1, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_1, 0, 0, 0)
        grid_sizer_1.Add(self.button_1, 0, 0, 0)
        grid_sizer_1.Add(self.label_2, 0, 0, 0)
        grid_sizer_1.Add(self.choice_1, 0, 0, 0)
        grid_sizer_1.Add((20, 20), 0, 0, 0)
        grid_sizer_1.Add(self.label_3, 0, 0, 0)
        grid_sizer_1.Add(self.choice_2, 0, 0, 0)
        #grid_sizer_1.Add((20, 20), 0, 0, 0)
        grid_sizer_1.Add(self.checkbox_2, 0, 0, 0)
        grid_sizer_1.Add(self.label_4, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_2, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_19, 0, 0, 0)
        
        #grid_sizer_1.Add((20, 20), 0, 0, 0)
        grid_sizer_1.Add(self.label_5, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_3, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_4, 0, 0, 0)
        grid_sizer_1.Add(self.label_6, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_5, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_6, 0, 0, 0)
        grid_sizer_1.Add(self.label_7, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_7, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_8, 0, 0, 0)
        grid_sizer_1.Add(self.label_8, 0, 0, 0)
        
        grid_sizer_1.Add(self.text_ctrl_9, 0, 0, 0)
        grid_sizer_1.Add((20, 20), 0, 0, 0)
        grid_sizer_1.Add(self.label_9, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_10, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_11, 0, 0, 0)
        grid_sizer_1.Add(self.label_10, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_12, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_13, 0, 0, 0)
        grid_sizer_1.Add(self.label_11, 0, 0, 0)
        grid_sizer_1.Add(self.text_ctrl_14, 0, 0, 0)
        grid_sizer_1.Add((20, 20), 0, 0, 0)
        grid_sizer_1.Add((20, 20), 0, 0, 0)
        #grid_sizer_1.Add((20, 20), 0, 0, 0)
        grid_sizer_1.Add(self.button_8, 0, 0, 0)
        grid_sizer_1.Add(self.button_2, 0, 0, 0)
        self.notebook_1_pane_1.SetSizer(grid_sizer_1)
        
        grid_sizer_2.Add(self.label_12, 0, 0, 0)
        grid_sizer_2.Add((20, 20), 0, 0, 0)
        grid_sizer_2.Add((20, 20), 0, 0, 0)
        grid_sizer_2.Add(self.label_13, 0, 0, 0)
        grid_sizer_2.Add(self.text_ctrl_15, 0, 0, 0)
        grid_sizer_2.Add(self.text_ctrl_16, 0, 0, 0)
        grid_sizer_2.Add((20, 20), 0, 0, 0)
        grid_sizer_2.Add((20, 20), 0, 0, 0)
        grid_sizer_2.Add((20, 20), 0, 0, 0)
        grid_sizer_2.Add(self.label_15, 0, 0, 0)
        grid_sizer_2.Add((20, 20), 0, 0, 0)
        grid_sizer_2.Add((20, 20), 0, 0, 0)
        grid_sizer_2.Add(self.label_16, 0, 0, 0)
        grid_sizer_2.Add(self.text_ctrl_17, 0, 0, 0)
        grid_sizer_2.Add(self.text_ctrl_18, 0, 0, 0)
        grid_sizer_2.Add((20, 20), 0, 0, 0)
        grid_sizer_2.Add((20, 20), 0, 0, 0)
        grid_sizer_2.Add(self.button_3, 0, 0, 0)
        self.notebook_1_pane_2.SetSizer(grid_sizer_2)
        grid_sizer_3.Add(self.label_17, 0, 0, 0)
        grid_sizer_3.Add((20, 20), 0, 0, 0)
        grid_sizer_3.Add(self.checkbox_1, 0, 0, 0)
        grid_sizer_3.Add((20, 20), 0, 0, 0)
        grid_sizer_3.Add((20, 20), 0, 0, 0)
        grid_sizer_3.Add(self.button_4, 0, 0, 0)
        self.notebook_1_pane_3.SetSizer(grid_sizer_3)
        
        grid_sizer_4.Add((20, 20), 0, 0, 0)
        grid_sizer_4.Add((20, 20), 0, 0, 0)
        grid_sizer_4.Add((20, 20), 0, 0, 0)
        grid_sizer_4.Add(self.label_14, 0, 0, 0)
        #grid_sizer_4.Add(self.text_ctrl_19, 0, 0, 0)
        grid_sizer_4.Add(self.button_5, 0, 0, 0)
        grid_sizer_4.Add((20, 20), 0, 0, 0)
        grid_sizer_4.Add((20, 20), 0, 0, 0)
        grid_sizer_4.Add((20, 20), 0, 0, 0)
        grid_sizer_4.Add((20, 20), 0, 0, 0)
        grid_sizer_4.Add(self.label_18, 0, 0, 0)
        #grid_sizer_4.Add(self.text_ctrl_20, 0, 0, 0)
        grid_sizer_4.Add(self.button_6, 0, 0, 0)
        grid_sizer_4.Add((20, 20), 0, 0, 0)
        self.notebook_1_pane_4.SetSizer(grid_sizer_4)
        
        grid_sizer_5.Add(self.button_7, 0, 0, 0)
        grid_sizer_5.Add((20, 20), 0, 0, 0)
        self.notebook_1_pane_5.SetSizer(grid_sizer_5)
        
        self.notebook_1.AddPage(self.notebook_1_pane_1, ("Training Data"))
        self.notebook_1.AddPage(self.notebook_1_pane_2, ("Train and Predict"))
        self.notebook_1.AddPage(self.notebook_1_pane_3, ("Visualize"))
        self.notebook_1.AddPage(self.notebook_1_pane_4, ("Load/ Save"))
        self.notebook_1.AddPage(self.notebook_1_pane_5, ("About"))
        
        sizer_1.Add(self.notebook_1, 1, 0, 0)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()
        # end wxGlade

    
    
    

    '''
    def Save_pars_func(self, event):  # wxGlade: MyDialog.<event_handler>
        #print "Event handler 'Save_pars_func' not implemented!"
        #event.Skip()
        self.__get_properties()
        print self.par_save_file_name
        self.select_file(event, title_text = 'Choose file to save')
        # 
    
    def Load_pars_func(self, event):  # wxGlade: MyDialog.<event_handler>
        #print "Event handler 'Save_pars_func' not implemented!"
        #event.Skip()
        self.__get_properties()
        print self.par_load_file_name
        self.select_file(event, title_text = 'Choose file to load')
    '''
    
    def OnAboutButton(self, evt):
        #print "Event handler 'About_func' not implemented!"
        #event.Skip()
        # First we create and fill the info object
        info = wx.AboutDialogInfo()
        info.Name = "Peak detect ML"
        info.Version = "0.2"
        info.Copyright = "(C) 2016 Praveen Taneja"
        info.Description = wordwrap(
            "Peak detect ML is a program to detect peaks and features (such as "
            "threshold, return to baseline) using machine learning. The use of " 
            "the program implies your acceptance of the license terms",
            350, wx.ClientDC(self))
        #info.WebSite = ("http://en.wikipedia.org/wiki/Hello_world", "Hello World home page")
        info.Developers = [ "Praveen Taneja"]#,
        #                    "Jane Coder",
        #                    "Vippy the Mascot" ]
        
        licenseText = ('THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF '
                        'ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED '
                        'TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A '
                        'PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT '
                        'SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR '
                        'ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN '
                        'ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, '
                        'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR '
                        'OTHER DEALINGS IN THE SOFTWARE.')
        info.License = wordwrap(licenseText, 400, wx.ClientDC(self))

        # Then we call wx.AboutBox giving it that info object
        wx.AboutBox(info)
        
        
    
    def select_folder(self, evt, title_text = ''):
        """
        http://www.blog.pythonlibrary.org/2010/06/26/the-dialogs-of-wxpython-part-1-of-2/
        Show the DirDialog and print the user's choice to stdout
        """
        #print title_text
        #app1 = wx.App()
        dlg = wx.DirDialog(None, title_text,
                        style=wx.DD_DEFAULT_STYLE
                        #| wx.DD_DIR_MUST_EXIST
                        #| wx.DD_CHANGE_DIR
                        )
        folder_path = ''
        if dlg.ShowModal() == wx.ID_OK:
            #print "You chose %s" % dlg.GetPath()
            #print dlg.GetPath()
            folder_path = dlg.GetPath()
            #data_folder = data_folder + '/'
        else:
            #sys.exit()
            evt.Skip()
        
        self.text_ctrl_1.SetValue(folder_path)
        dlg.Destroy()
        #return folder_path

    
    def __get_properties(self): 
        ''' get values from gui into variables
        '''
        analysis_pars['data_folder'] = self.text_ctrl_1.GetValue()# + '/'
        if self.choice_1.GetSelection() == 0:
            analysis_pars['fn_extension'] = '.csv'
        else:
            analysis_pars['fn_extension'] = '.txt'
        analysis_pars['fn_match'] = '*' + analysis_pars['fn_extension']
        analysis_pars['set_col_names'] = True
        
        if self.choice_2.GetSelection() == 0:
            analysis_pars['PEAK_POLARITY'] = 1 # maxima
        else:
            analysis_pars['PEAK_POLARITY'] = -1 # minima
        
        analysis_pars['display_deriv2'] = self.checkbox_2.GetValue()        
        analysis_pars['PEAK_NPNTS_THRESH'] = int(self.text_ctrl_2.GetValue())
        analysis_pars['DERIV2_THRESH'] = float(self.text_ctrl_19.GetValue())

        analysis_pars['PEAK_PRE_CROP_WIN'] = int(self.text_ctrl_3.GetValue())
        analysis_pars['PEAK_POST_CROP_WIN'] = int(self.text_ctrl_4.GetValue())
        
        analysis_pars['PEAK_DISPLAY_X_PRE'] = int(self.text_ctrl_5.GetValue())
        analysis_pars['PEAK_DISPLAY_X_POST'] = int(self.text_ctrl_6.GetValue())
        analysis_pars['DISPLAY_WIN'] =  (int(analysis_pars['PEAK_DISPLAY_X_PRE']) +
                                        int(analysis_pars['PEAK_DISPLAY_X_POST']))
                                        
        analysis_pars['PEAK_DISPLAY_Y_BELOW'] = float(self.text_ctrl_7.GetValue())
        analysis_pars['PEAK_DISPLAY_Y_ABOVE'] = float(self.text_ctrl_8.GetValue()) 
        
        
        analysis_pars['yrange'] = (float(analysis_pars['PEAK_DISPLAY_Y_BELOW']), 
                                    float(analysis_pars['PEAK_DISPLAY_Y_ABOVE']) )
        analysis_pars['DOWN_SAMPLE_FACTOR'] = int(self.text_ctrl_9.GetValue()) #DOWN_SAMPLE_FACTOR
        
        if  self.text_ctrl_10.GetValue() == '':# or self.text_ctrl_10.GetValue() == None:
            analysis_pars['START'] = '' # ie. start from 1st value
        else:
            analysis_pars['START'] = int(self.text_ctrl_10.GetValue())
            
        if  self.text_ctrl_11.GetValue() == '':# or self.text_ctrl_11.GetValue() == None:
            analysis_pars['END'] = '' # ie. end on last value
        else:
            analysis_pars['END'] = int(self.text_ctrl_11.GetValue())
        analysis_pars['FILTER_WIN_SIZE'] = int(self.text_ctrl_12.GetValue())
        analysis_pars['FILTER_SIGMA'] = int(self.text_ctrl_13.GetValue())
        analysis_pars['detect_features_str'] = self.text_ctrl_14.GetValue()#.split()
        analysis_pars['detect_features'] = (analysis_pars['detect_features_str']
                                                        .split())
        
        #self.par_save_file_name = self.text_ctrl_19.GetValue()
        #self.par_load_file_name = self.text_ctrl_20.GetValue()
        
        analysis_pars['Peak_FIT_PEAK_PRE_CROP_WIN'] = int(self.text_ctrl_15.GetValue())
        analysis_pars['Peak_FIT_POST_PRE_CROP_WIN'] = int(self.text_ctrl_16.GetValue())
        analysis_pars['Feature_FIT_PEAK_PRE_CROP_WIN'] = int(self.text_ctrl_17.GetValue())
        analysis_pars['Feature_FIT_POST_PRE_CROP_WIN'] = int(self.text_ctrl_18.GetValue())
        
        analysis_pars['plot_full_traces'] = self.checkbox_1.GetValue()

        
    def __set_variables(self): 
        ''' set values from variables into gui
        '''
        self.text_ctrl_1.SetValue(analysis_pars['data_folder'])
        #print 'analysis_pars[\'fn_extension\']', analysis_pars['fn_extension']
        
        if analysis_pars['fn_extension'] == '.csv':
            self.choice_1.SetSelection(0)
        else:
            self.choice_1.SetSelection(1)
        
        analysis_pars['fn_match'] = '*' + analysis_pars['fn_extension']
        analysis_pars['set_col_names'] = True
        #print 'analysis_pars[\'PEAK_POLARITY\']', analysis_pars['PEAK_POLARITY']
        if int(analysis_pars['PEAK_POLARITY']) == 1:
            self.choice_2.SetSelection(0)
        else:
            self.choice_2.SetSelection(1)
        
        self.checkbox_2.SetValue(bool(analysis_pars['display_deriv2']))         
        self.text_ctrl_2.SetValue(analysis_pars['PEAK_NPNTS_THRESH'])
        self.text_ctrl_19.SetValue(analysis_pars['DERIV2_THRESH'])
        
        self.text_ctrl_3.SetValue(analysis_pars['PEAK_PRE_CROP_WIN'])
        self.text_ctrl_4.SetValue(analysis_pars['PEAK_POST_CROP_WIN'])
        
        self.text_ctrl_5.SetValue(analysis_pars['PEAK_DISPLAY_X_PRE'])
        self.text_ctrl_6.SetValue(analysis_pars['PEAK_DISPLAY_X_POST'])
        analysis_pars['DISPLAY_WIN'] =  (int(analysis_pars['PEAK_DISPLAY_X_PRE']) +
                                        int(analysis_pars['PEAK_DISPLAY_X_POST']))
                                        
        self.text_ctrl_7.SetValue(analysis_pars['PEAK_DISPLAY_Y_BELOW'])
        self.text_ctrl_8.SetValue(analysis_pars['PEAK_DISPLAY_Y_ABOVE'])
        analysis_pars['yrange'] = (float(analysis_pars['PEAK_DISPLAY_Y_BELOW']), 
                                    float(analysis_pars['PEAK_DISPLAY_Y_ABOVE']))
        
        self.text_ctrl_9.SetValue(analysis_pars['DOWN_SAMPLE_FACTOR']) #DOWN_SAMPLE_FACTOR
        if analysis_pars['START'] == None:
            self.text_ctrl_10.SetValue = ''
        else:
            self.text_ctrl_10.SetValue(analysis_pars['START'])
        
        if analysis_pars['END'] == None:
            self.text_ctrl_11.SetValue = ''
        else:
            self.text_ctrl_11.SetValue(analysis_pars['END'])
        self.text_ctrl_12.SetValue(analysis_pars['FILTER_WIN_SIZE'])
        self.text_ctrl_13.SetValue(analysis_pars['FILTER_SIGMA'])
        
        #print 'analysis_pars[\'detect_features\']', analysis_pars['detect_features']
        #print type(analysis_pars['detect_features'])                                                        
        self.text_ctrl_14.SetValue(analysis_pars['detect_features_str'])#.split()
        analysis_pars['detect_features'] = (analysis_pars['detect_features_str']
                                                        .split())
        
        self.text_ctrl_15.SetValue(analysis_pars['Peak_FIT_PEAK_PRE_CROP_WIN'])
        self.text_ctrl_16.SetValue(analysis_pars['Peak_FIT_POST_PRE_CROP_WIN'])
        self.text_ctrl_17.SetValue(analysis_pars['Feature_FIT_PEAK_PRE_CROP_WIN'])
        self.text_ctrl_18.SetValue(analysis_pars['Feature_FIT_POST_PRE_CROP_WIN'])
        
        self.checkbox_1.SetValue(bool(analysis_pars['plot_full_traces'])) 
                
    def browse_peaks_func(self, event):  # wxGlade: MyDialog.<event_handler>
        print "Event handler 'browse_func' not implemented!"
        event.Skip()                            
    
    def gen_examples_start_func(self, event):  # wxGlade: MyDialog.<event_handler>
        #print "Event handler 'start_func' not implemented!"
        #event.Skip()
        self.__get_properties()
        print '----------------------------------------'
        print 'Starting generation of training examples'
        print '----------------------------------------'
        print 'Folder selected:', analysis_pars['data_folder']
        self.results_dir = self.create_results_dir(analysis_pars['data_folder'] + '/')
        #self.save_pars(analysis_pars['data_folder'] + 'results/')
        gen_train_data.generate_examples(analysis_pars['data_folder'] + '/', 
                self.results_dir, analysis_pars['fn_match'], 
                analysis_pars['fn_extension'], analysis_pars['START'], 
                analysis_pars['END'], analysis_pars['set_col_names'], 
                analysis_pars['DOWN_SAMPLE_FACTOR'], 
                analysis_pars['FILTER_WIN_SIZE'], analysis_pars['FILTER_SIGMA'],
                analysis_pars['PEAK_POLARITY'], 
                analysis_pars['PEAK_NPNTS_THRESH'], 
                analysis_pars['DERIV2_THRESH'], analysis_pars['display_deriv2'],
                analysis_pars['PEAK_PRE_CROP_WIN'], 
                analysis_pars['PEAK_POST_CROP_WIN'], analysis_pars['DISPLAY_WIN'], 
                analysis_pars['yrange'], analysis_pars['detect_features'])
                
    def classific_start_func(self, event):  # wxGlade: MyDialog.<event_handler>
        #print "Event handler 'classific_start_func' not implemented!"
        #event.Skip()
        self.__get_properties()
        print '----------------------------------------'
        print 'Starting training and prediction'
        print '----------------------------------------'
        self.results_dir = self.create_results_dir(analysis_pars['data_folder'] + '/')
        # merge cropped peak and peak_vars file into a single file
        cropped_peaks = pd.read_table(self.results_dir + 'cropped_peaks.csv',
                                delimiter = ',')
        peak_vars = pd.read_table(self.results_dir + 'peak_vars.csv',
                                delimiter = ',')
        train_data = pd.concat([cropped_peaks, peak_vars], axis = 1)
        train_data.to_csv(self.results_dir + 'train_data_all.csv', 
                        delimiter = ',', index = False)
        
        analysis_pars['Peak_Classifier'] = ExtraTreesClassifier(n_estimators=100, 
                                        max_depth=None, min_samples_split=1, 
                                        random_state=0)
        analysis_pars['Feature_Classifier'] = svm.SVR(gamma=0.001, C=100.)
                                                                                                    
        # classify peak or no peak
                                        
        FEATURE_START_COLNUM = (analysis_pars['PEAK_PRE_CROP_WIN'] - 
                                        analysis_pars['Peak_FIT_PEAK_PRE_CROP_WIN'])
        FEATURE_END_COLNUM = (FEATURE_START_COLNUM + 
                            analysis_pars['Peak_FIT_PEAK_PRE_CROP_WIN'] + 
                            analysis_pars['Peak_FIT_POST_PRE_CROP_WIN'])
        print 'Analysing peak selection/rejection.'
        ##print ('FEATURE_START_COLNUM, FEATURE_END_COLNUM', FEATURE_START_COLNUM,
        ##        FEATURE_END_COLNUM)
        
        #print 'analysis_pars[\'Peak_Classifier\']', analysis_pars['Peak_Classifier']
        #print type(analysis_pars['Peak_Classifier'])
        classific.classify_peaks(train_data, self.results_dir, 
                                analysis_pars['Peak_Classifier'], 'selected', 
                                analysis_pars['Peak_FIT_PEAK_PRE_CROP_WIN'], 
                                analysis_pars['Peak_FIT_POST_PRE_CROP_WIN'], 
                                FEATURE_START_COLNUM, FEATURE_END_COLNUM)
                                
        # classify peak for features
        
        FEATURE_START_COLNUM = (analysis_pars['PEAK_PRE_CROP_WIN'] - 
                                analysis_pars['Feature_FIT_PEAK_PRE_CROP_WIN'])
        FEATURE_END_COLNUM = (FEATURE_START_COLNUM + 
                            analysis_pars['Feature_FIT_PEAK_PRE_CROP_WIN'] + 
                            analysis_pars['Feature_FIT_POST_PRE_CROP_WIN'])
        
        
        
        for self.feature in analysis_pars['detect_features']:
            print 'Analysing', self.feature
            ##print ('FEATURE_START_COLNUM, FEATURE_END_COLNUM', FEATURE_START_COLNUM,
            ##    FEATURE_END_COLNUM)
            df_predicted = pd.read_table(self.results_dir + 'predicted.csv', 
                        delimiter = ',')
            classific.classify_peaks(df_predicted, self.results_dir, 
                                analysis_pars['Feature_Classifier'],
                                self.feature + '_rel_x', 
                                analysis_pars['Feature_FIT_PEAK_PRE_CROP_WIN'], 
                                analysis_pars['Feature_FIT_POST_PRE_CROP_WIN'], 
                                FEATURE_START_COLNUM, FEATURE_END_COLNUM)
            # also calculated abs x, y values of features
            df_predicted = pd.read_table(self.results_dir + 'predicted.csv', 
                        delimiter = ',')
            df_predicted[self.feature +'_rel_x'] = np.rint(
                                        df_predicted[self.feature + '_rel_x'])
            df_predicted[self.feature + '_x'] = (df_predicted[self.feature+ 
                                                '_rel_x'] + 
                                                df_predicted['peak_x'] - 
                                                analysis_pars['PEAK_PRE_CROP_WIN'])
            df_predicted[self.feature + '_y'] = df_predicted.apply(
                                                self.abs_thresh, axis = 1)
                                                
            df_predicted.to_csv(self.results_dir + 'predicted.csv', index = False)
    
    def plot_start_func(self, event):  # wxGlade: MyDialog.<event_handler>
        #print "Event handler 'classific_start_func' not implemented!"
        #event.Skip()
        self.__get_properties()
        print '----------------------------------------'
        print 'Starting plotting of all peaks'
        print '----------------------------------------'
        self.results_dir = self.create_results_dir(analysis_pars['data_folder'] + '/')
        df_predicted = pd.read_table(self.results_dir + 'predicted.csv', 
                                    delimiter = ',')
        peak_analysis_start_col = (analysis_pars['PEAK_PRE_CROP_WIN'] + 
                                    analysis_pars['PEAK_POST_CROP_WIN'])
        peak_analysis = df_predicted.iloc[:, peak_analysis_start_col:]
        plot_peaks.plot_peaks(analysis_pars['data_folder'] + '/', 
                peak_analysis, 
                analysis_pars['fn_extension'], analysis_pars['START'], 
                analysis_pars['END'], analysis_pars['set_col_names'], 
                analysis_pars['DOWN_SAMPLE_FACTOR'], 
                analysis_pars['FILTER_WIN_SIZE'], analysis_pars['FILTER_SIGMA'],
                analysis_pars['DISPLAY_WIN'], 
                analysis_pars['yrange'], analysis_pars['detect_features'], 
                analysis_pars['plot_full_traces'])
                                    

    def abs_thresh(self, x):
        if (int(x[self.feature + '_rel_x']) >= 0 and 
                                        (int(x[self.feature + '_rel_x']) <=
                                        (analysis_pars['PEAK_PRE_CROP_WIN']
                                        + analysis_pars['PEAK_POST_CROP_WIN']
                                        - 1))):
            return x[int(x[self.feature + '_rel_x'])]
        else:
            print ('Warning!', self.feature, 'lies outside cropped peaks.'  
                    'Increase range of cropped peaks to include all features')
            return np.nan
        
    def create_results_dir(self, data_folder):
        #data_folder = data_folder + '/'
        results_dir = data_folder + 'results/'
        if os.path.exists(results_dir) == False:
            os.makedirs(results_dir)
        return results_dir
        
    def save_pars(self, fn_w_path):
        # save analysis parameters to disk for future reference:
        #with open(results_dir+'analysis_pars.txt', 'w') as fh:
        with open(fn_w_path, 'w') as fh:
            fh .writelines('{}, {}\n'.format(k,v) for k, v in analysis_pars.items())
    
    def OnSaveAs(self, event):
        saveFileDialog = wx.FileDialog(self, "Save parameters", "", "peak_analysis_pars.txt",
                                   "Text files (*.txt)|*.txt", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
        if saveFileDialog.ShowModal() == wx.ID_CANCEL:
            return     # the user changed idea...

        # save the current contents in the file
        # this can be done with e.g. wxPython output streams:
        #output_stream = wx.FileOutputStream(saveFileDialog.GetPath())
        self.__get_properties()
        with open(saveFileDialog.GetPath(), 'w') as fh:
            fh .writelines('{}, {}\n'.format(k, v) for k, v in analysis_pars.items())
        
        #for k, v in analysis_pars.items():
        #    print k, v
        #    sys.stdout.flush()
        #if not output_stream.IsOk():
        #    wx.LogError("Cannot save current contents in file '%s'."%saveFileDialog.GetPath())
            return
    
    def OnOpen(self, event):

        ##if self.contentNotSaved:
    
        ##    if wx.MessageBox("Current content has not been saved! Proceed?", "Please confirm",
        ##                    wx.ICON_QUESTION | wx.YES_NO, self) == wx.NO:
        ##        return
    
            # else: proceed asking to the user the new file to open
    
        openFileDialog = wx.FileDialog(self, "Load parameters", "", "",
                                    "Text files (*.txt)|*.txt", 
                                    wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
    
        if openFileDialog.ShowModal() == wx.ID_CANCEL:
            return     # the user changed idea...
    
            # proceed loading the file chosen by the user
            # this can be done with e.g. wxPython input streams:
            #input_stream = wx.FileInputStream(openFileDialog.GetPath())
        with open(openFileDialog.GetPath(), 'r') as fh:
            csv_reader = csv.reader(fh)
            for row in csv_reader:
                analysis_pars[row[0]] = row[1].strip()
        self.__set_variables()
        ##pprint.pprint( list(analysis_pars.items()))
    
            #if not input_stream.IsOk():
    
            #    wx.LogError("Cannot open file '%s'."%openFileDialog.GetPath())
            #    return
        
# end of class MyDialog
class MyApp(wx.App):
    def OnInit(self):
        wx.InitAllImageHandlers()
        dialog_1 = MyDialog(None, wx.ID_ANY, "")
        self.SetTopWindow(dialog_1)
        dialog_1.Show()
        return 1

# end of class MyApp

if __name__ == "__main__":
    gettext.install("app") # replace with the appropriate catalog name

    app = MyApp(0)
    app.MainLoop()