<commit_before>#!/usr/bin/python
import datetime
from matplotlib.ticker import FormatStrFormatter

import wx
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import pandas as pd

import mpl_toolkits.axisartist as AA

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas
from mpl_toolkits.axes_grid1 import host_subplot


from matplotlib.lines import Line2D
from matplotlib.text import Text

from matplotlib.font_manager import FontProperties
from wx.lib.pubsub import pub as Publisher
from mnuPlotToolbar import MyCustomToolbar as NavigationToolbar

## Enable logging
import logging
from odmtools.common.logger import LoggerTool

tool = LoggerTool()
logger = tool.setupLogger(__name__, __name__ + '.log', 'w', logging.DEBUG)


class plotTimeSeries(wx.Panel):
    def __init__(self, parent, id, pos, size, style, name):
        self._init_ctrls(parent)


    def _init_coll_boxSizer1_Items(self, parent):
        # generated method, don't edit

        parent.AddWindow(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        parent.AddWindow(self.toolbar, 0, wx.EXPAND)

    def _init_ctrls(self, parent):
        wx.Panel.__init__(self, parent, -1)
        self.parent = parent

        #init Plot
        # matplotlib.figure.Figure
        self.figure = plt.figure()

        # matplotlib.axes.AxesSubplot
        self.timeSeries = host_subplot( 111, axes_class=AA.Axes)
        #self.timeSeries = self.figure.add_subplot(111)
        #self.timeSeries.plot([], [], picker=5)
        self.setTimeSeriesTitle("No Data to Plot")

        # matplotlib.backends.backend_wxagg.FigureCanvasWxAgg
        self.canvas = FigCanvas(self, -1, self.figure)

        self.canvas.SetFont(wx.Font(20, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Tahoma'))
        self.isShowLegendEnabled = False

        '''
        import pandas as pd
        import numpy as np

        self.data = pd.DataFrame(np.random.randn(14, 2),
                    index=np.arange('2005-02', '2005-02-15', dtype='datetime64[D]'),
                    columns=['first', 'sec'])

        #ax = self.data.plot(ax=self.timeSeries, title='sample')
        '''

        #self.hoverAction = self.canvas.mpl_connect('motion_notify_event', self._onMotion)
        #self.pointPick = self.canvas.mpl_connect('pick_event', self._onPick)
        self.canvas.mpl_connect('figure_leave_event', self._onFigureLeave)
        Publisher.subscribe(self.updateCursor, "updateCursor")

        # Create the navigation toolbar, tied to the canvas
        self.toolbar = NavigationToolbar(self.canvas, allowselect=True)
        self.toolbar.Realize()
        self.seriesPlotInfo = None

        #set properties
        self.fontP = FontProperties()
        self.fontP.set_size('x-small')

        self.format = '-o'
        self.alpha=1
        self._setColor("WHITE")

        left = 0.125  # the left side of the subplots of the figure
        #right = 0.9  # the right side of the subplots of the figure
        #bottom = 0.51  # the bottom of the subplots of the figure
        #top = 1.2  # the top of the subplots of the figure
        #wspace = .8  # the amount of width reserved for blank space between subplots
        #hspace = .8  # the amount of height reserved for white space between subplots
        plt.subplots_adjust(
            left=left#, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace
        )
        plt.tight_layout()

        #init hover tooltip

        # create a long tooltip with newline to get around wx bug (in v2.6.3.3)
        # where newlines aren't recognized on subsequent self.tooltip.SetTip() calls
        self.tooltip = wx.ToolTip(tip='tip with a long %s line and a newline\n')
        self.canvas.SetToolTip(self.tooltip)
        self.tooltip.Enable(False)
        self.tooltip.SetDelay(0)

        #init lists
        #self.lines = {}
        self.lines = []
        self.axislist = {}
        self.curveindex = -1
        self.editseriesID = -1
        self.editCurve = None
        self.editPoint =None
        self.hoverAction = None
        self.selplot= None

        self.cursors = []

        self.canvas.draw()
        self._init_sizers()

    def _init_sizers(self):
        # generated method, don't edit
        self.boxSizer1 = wx.BoxSizer(orient=wx.VERTICAL)
        self._init_coll_boxSizer1_Items(self.boxSizer1)
        self.SetSizer(self.boxSizer1)

    '''
    def changePlotSelection(self, datetime_list=[]):
        cc= ColorConverter()
        # k black,    # r red
        # needs to have graph first
        selected = cc.to_rgba('r', 1)
        unselected = cc.to_rgba('k', 0.1)
        allunselected = cc.to_rgba('k', 1)
        if self.editPoint:
            colorlist=[allunselected] *len(self.editCurve.dataTable)
            if len(datetime_list)>0:
                for i in xrange(len(self.editCurve.dataTable)):
                    if  self.editCurve.dataTable[i][1] in datetime_list:
                        colorlist[i]=selected
                    else:
                        colorlist[i]=unselected

            self.editPoint.set_color(colorlist)
            #self.editPoint.set_color(['k' if x == 0 else 'r' for x in tflist])
            self.canvas.draw()

    '''
    ## TODO 10/15/2014 Change function so that it will accept a list of datavalues. This will remove the need to loop through the values currently plotted and we would instead plot the list of datetimes and datavalues together.

    def changePlotSelection(self,  datetime_list=[], datavalues=[]):

        #for entire list of points if selected add to new lists
        #newx = []
        #newy = []
        if self.selplot:
            self.selplot.remove()
            del(self.selplot)
            self.selplot = None


        if len(datetime_list) > 0:
            df = self.editCurve.dataTable
            result = df[df['LocalDateTime'].isin(datetime_list)].astype(datetime.datetime)
            values = result['DataValue'].values
            dates = result.LocalDateTime.values
            self.selplot = self.axislist[self.editSeries.axisTitle].scatter(dates, values, s=35, c='red',
                                                                            edgecolors='none', zorder=12, marker='s', alpha=1)

            '''
            #DELETE
            for x, y, a, b, c in self.editCurve.dataTable:
                if y in datetime_list:
                    newx.append(x)
                    newy.append(y)

            self.selplot = self.axislist[self.editSeries.axisTitle].scatter(newy, newx,
                                              s=35, c='red', edgecolors='none',
                                              zorder=12, marker='s', alpha=1)
            '''

        self.canvas.draw()


    def changeSelection(self, datetime_list=[]):
        self.changePlotSelection( datetime_list)
<commit_msg>Resolved an issue with the filter on Windows, still need to fully test lasso on windows<commit_after>#!/usr/bin/python
import datetime
from matplotlib.ticker import FormatStrFormatter

import wx
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import pandas as pd

import mpl_toolkits.axisartist as AA

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas
from mpl_toolkits.axes_grid1 import host_subplot


from matplotlib.lines import Line2D
from matplotlib.text import Text

from matplotlib.font_manager import FontProperties
from wx.lib.pubsub import pub as Publisher
from mnuPlotToolbar import MyCustomToolbar as NavigationToolbar

## Enable logging
import logging
from odmtools.common.logger import LoggerTool

tool = LoggerTool()
logger = tool.setupLogger(__name__, __name__ + '.log', 'w', logging.DEBUG)


class plotTimeSeries(wx.Panel):
    def __init__(self, parent, id, pos, size, style, name):
        self._init_ctrls(parent)


    def _init_coll_boxSizer1_Items(self, parent):
        # generated method, don't edit

        parent.AddWindow(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        parent.AddWindow(self.toolbar, 0, wx.EXPAND)

    def _init_ctrls(self, parent):
        wx.Panel.__init__(self, parent, -1)
        self.parent = parent

        #init Plot
        # matplotlib.figure.Figure
        self.figure = plt.figure()

        # matplotlib.axes.AxesSubplot
        self.timeSeries = host_subplot( 111, axes_class=AA.Axes)
        #self.timeSeries = self.figure.add_subplot(111)
        #self.timeSeries.plot([], [], picker=5)
        self.setTimeSeriesTitle("No Data to Plot")

        # matplotlib.backends.backend_wxagg.FigureCanvasWxAgg
        self.canvas = FigCanvas(self, -1, self.figure)

        self.canvas.SetFont(wx.Font(20, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Tahoma'))
        self.isShowLegendEnabled = False

        '''
        import pandas as pd
        import numpy as np

        self.data = pd.DataFrame(np.random.randn(14, 2),
                    index=np.arange('2005-02', '2005-02-15', dtype='datetime64[D]'),
                    columns=['first', 'sec'])

        #ax = self.data.plot(ax=self.timeSeries, title='sample')
        '''

        #self.hoverAction = self.canvas.mpl_connect('motion_notify_event', self._onMotion)
        #self.pointPick = self.canvas.mpl_connect('pick_event', self._onPick)
        self.canvas.mpl_connect('figure_leave_event', self._onFigureLeave)
        Publisher.subscribe(self.updateCursor, "updateCursor")

        # Create the navigation toolbar, tied to the canvas
        self.toolbar = NavigationToolbar(self.canvas, allowselect=True)
        self.toolbar.Realize()
        self.seriesPlotInfo = None

        #set properties
        self.fontP = FontProperties()
        self.fontP.set_size('x-small')

        self.format = '-o'
        self.alpha=1
        self._setColor("WHITE")

        left = 0.125  # the left side of the subplots of the figure
        #right = 0.9  # the right side of the subplots of the figure
        #bottom = 0.51  # the bottom of the subplots of the figure
        #top = 1.2  # the top of the subplots of the figure
        #wspace = .8  # the amount of width reserved for blank space between subplots
        #hspace = .8  # the amount of height reserved for white space between subplots
        plt.subplots_adjust(
            left=left#, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace
        )
        plt.tight_layout()

        #init hover tooltip

        # create a long tooltip with newline to get around wx bug (in v2.6.3.3)
        # where newlines aren't recognized on subsequent self.tooltip.SetTip() calls
        self.tooltip = wx.ToolTip(tip='tip with a long %s line and a newline\n')
        self.canvas.SetToolTip(self.tooltip)
        self.tooltip.Enable(False)
        self.tooltip.SetDelay(0)

        #init lists
        #self.lines = {}
        self.lines = []
        self.axislist = {}
        self.curveindex = -1
        self.editseriesID = -1
        self.editCurve = None
        self.editPoint =None
        self.hoverAction = None
        self.selplot= None

        self.cursors = []

        self.canvas.draw()
        self._init_sizers()

    def _init_sizers(self):
        # generated method, don't edit
        self.boxSizer1 = wx.BoxSizer(orient=wx.VERTICAL)
        self._init_coll_boxSizer1_Items(self.boxSizer1)
        self.SetSizer(self.boxSizer1)

    '''
    def changePlotSelection(self, datetime_list=[]):
        cc= ColorConverter()
        # k black,    # r red
        # needs to have graph first
        selected = cc.to_rgba('r', 1)
        unselected = cc.to_rgba('k', 0.1)
        allunselected = cc.to_rgba('k', 1)
        if self.editPoint:
            colorlist=[allunselected] *len(self.editCurve.dataTable)
            if len(datetime_list)>0:
                for i in xrange(len(self.editCurve.dataTable)):
                    if  self.editCurve.dataTable[i][1] in datetime_list:
                        colorlist[i]=selected
                    else:
                        colorlist[i]=unselected

            self.editPoint.set_color(colorlist)
            #self.editPoint.set_color(['k' if x == 0 else 'r' for x in tflist])
            self.canvas.draw()

    '''
    ## TODO 10/15/2014 Change function so that it will accept a list of datavalues. This will remove the need to loop through the values currently plotted and we would instead plot the list of datetimes and datavalues together.

    def changePlotSelection(self,  datetime_list=[], datavalues=[]):

        #for entire list of points if selected add to new lists
        #newx = []
        #newy = []
        if self.selplot:
            self.selplot.remove()
            del(self.selplot)
            self.selplot = None


        if len(datetime_list) > 0:
            df = self.editCurve.dataTable
            result = df[df['LocalDateTime'].isin(datetime_list)].astype(datetime.datetime)
            values = result['DataValue'].values.tolist()
            dates = result.LocalDateTime.values.tolist()
            self.selplot = self.axislist[self.editSeries.axisTitle].scatter(dates, values, s=35, c='red',
                                                                            edgecolors='none', zorder=12, marker='s', alpha=1)

            '''
            #DELETE
            for x, y, a, b, c in self.editCurve.dataTable:
                if y in datetime_list:
                    newx.append(x)
                    newy.append(y)

            self.selplot = self.axislist[self.editSeries.axisTitle].scatter(newy, newx,
                                              s=35, c='red', edgecolors='none',
                                              zorder=12, marker='s', alpha=1)
            '''

        self.canvas.draw()


    def changeSelection(self, datetime_list=[]):
        self.changePlotSelection( datetime_list)

{'fraction_non_alphanumeric': 0.10061852704257768, 'fraction_numerical': 0.01237054085155351, 'mean_word_length': 2.2232267037552154, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1053679', 'n_tokens_mistral': 4263, 'n_tokens_neox': 4034, 'n_words': 1017}