Laurent@814: #!/usr/bin/env python Laurent@814: # -*- coding: utf-8 -*- Laurent@814: Laurent@814: #This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor Laurent@814: #based on the plcopen standard. Laurent@814: # Laurent@814: #Copyright (C) 2012: Edouard TISSERANT and Laurent BESSARD Laurent@814: # Laurent@814: #See COPYING file for copyrights details. Laurent@814: # Laurent@814: #This library is free software; you can redistribute it and/or Laurent@814: #modify it under the terms of the GNU General Public Laurent@814: #License as published by the Free Software Foundation; either Laurent@814: #version 2.1 of the License, or (at your option) any later version. Laurent@814: # Laurent@814: #This library is distributed in the hope that it will be useful, Laurent@814: #but WITHOUT ANY WARRANTY; without even the implied warranty of Laurent@814: #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Laurent@814: #General Public License for more details. Laurent@814: # Laurent@814: #You should have received a copy of the GNU General Public Laurent@814: #License along with this library; if not, write to the Free Software Laurent@814: #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Laurent@814: Laurent@887: from types import TupleType, FloatType Laurent@887: from time import time as gettime Laurent@902: import math Laurent@887: import numpy Laurent@814: Laurent@814: import wx Laurent@814: import wx.lib.buttons Laurent@888: Laurent@888: try: Laurent@888: import matplotlib Laurent@888: matplotlib.use('WX') Laurent@888: import matplotlib.pyplot Laurent@902: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas Laurent@902: #from matplotlib.backends.backend_wx import FigureCanvasWx as FigureCanvas Laurent@888: from mpl_toolkits.mplot3d import Axes3D Laurent@888: USE_MPL = True Laurent@888: except: Laurent@888: USE_MPL = False Laurent@887: Laurent@887: from graphics import DebugDataConsumer, DebugViewer, REFRESH_PERIOD Laurent@814: from controls import CustomGrid, CustomTable Laurent@814: from dialogs.ForceVariableDialog import ForceVariableDialog Laurent@814: from util.BitmapLibrary import GetBitmap Laurent@814: Laurent@902: SECOND = 1000000000 Laurent@902: MINUTE = 60 * SECOND Laurent@902: HOUR = 60 * MINUTE Laurent@902: Laurent@902: ZOOM_VALUES = map(lambda x:("x %.1f" % x, x), [math.sqrt(2) ** i for i in xrange(8)]) Laurent@902: RANGE_VALUES = map(lambda x: (str(x), x), [25 * 2 ** i for i in xrange(6)]) Laurent@902: TIME_RANGE_VALUES = [("%ds" % i, i * SECOND) for i in (1, 2, 5, 10, 20, 30)] + \ Laurent@902: [("%dm" % i, i * MINUTE) for i in (1, 2, 5, 10, 20, 30)] + \ Laurent@902: [("%dh" % i, i * HOUR) for i in (1, 2, 3, 6, 12, 24)] Laurent@902: Laurent@909: GRAPH_PARALLEL, GRAPH_ORTHOGONAL = range(2) Laurent@909: Laurent@814: def AppendMenu(parent, help, id, kind, text): Laurent@814: parent.Append(help=help, id=id, kind=kind, text=text) Laurent@814: Laurent@814: def GetDebugVariablesTableColnames(): Laurent@814: _ = lambda x : x Laurent@909: return [_("Variable"), _("Value")] Laurent@909: Laurent@814: class VariableTableItem(DebugDataConsumer): Laurent@814: Laurent@887: def __init__(self, parent, variable): Laurent@814: DebugDataConsumer.__init__(self) Laurent@814: self.Parent = parent Laurent@814: self.Variable = variable Laurent@887: self.RefreshVariableType() Laurent@887: self.Value = "" Laurent@909: Laurent@814: def __del__(self): Laurent@814: self.Parent = None Laurent@814: Laurent@814: def SetVariable(self, variable): Laurent@814: if self.Parent and self.Variable != variable: Laurent@814: self.Variable = variable Laurent@887: self.RefreshVariableType() Laurent@814: self.Parent.RefreshGrid() Laurent@814: Laurent@814: def GetVariable(self): Laurent@814: return self.Variable Laurent@814: Laurent@887: def RefreshVariableType(self): Laurent@887: self.VariableType = self.Parent.GetDataType(self.Variable) Laurent@887: self.ResetData() Laurent@887: Laurent@887: def GetVariableType(self): Laurent@887: return self.VariableType Laurent@887: Laurent@902: def GetData(self, start_tick=None, end_tick=None): Laurent@902: if self.IsNumVariable(): Laurent@902: if len(self.Data) == 0: Laurent@902: return self.Data Laurent@902: Laurent@902: start_idx = end_idx = None Laurent@902: if start_tick is not None: Laurent@902: start_idx = self.GetNearestData(start_tick, -1) Laurent@902: if end_tick is not None: Laurent@902: end_idx = self.GetNearestData(end_tick, 1) Laurent@902: if start_idx is None: Laurent@902: start_idx = 0 Laurent@902: if end_idx is not None: Laurent@902: return self.Data[start_idx:end_idx + 1] Laurent@902: else: Laurent@902: return self.Data[start_idx:] Laurent@902: Laurent@902: return None Laurent@902: Laurent@902: def GetRange(self): Laurent@902: return self.MinValue, self.MaxValue Laurent@887: Laurent@887: def ResetData(self): Laurent@887: if self.IsNumVariable(): Laurent@887: self.Data = numpy.array([]).reshape(0, 2) Laurent@902: self.MinValue = None Laurent@902: self.MaxValue = None Laurent@887: else: Laurent@887: self.Data = None Laurent@887: Laurent@887: def IsNumVariable(self): Laurent@887: return self.Parent.IsNumType(self.VariableType) Laurent@887: Laurent@887: def NewValue(self, tick, value, forced=False): Laurent@887: if self.IsNumVariable(): Laurent@895: num_value = {True:1., False:0.}.get(value, float(value)) Laurent@902: if self.MinValue is None: Laurent@902: self.MinValue = num_value Laurent@902: else: Laurent@902: self.MinValue = min(self.MinValue, num_value) Laurent@902: if self.MaxValue is None: Laurent@902: self.MaxValue = num_value Laurent@902: else: Laurent@902: self.MaxValue = max(self.MaxValue, num_value) Laurent@895: self.Data = numpy.append(self.Data, [[float(tick), num_value]], axis=0) Laurent@887: self.Parent.HasNewData = True Laurent@887: DebugDataConsumer.NewValue(self, tick, value, forced) Laurent@887: Laurent@814: def SetForced(self, forced): Laurent@814: if self.Forced != forced: Laurent@814: self.Forced = forced Laurent@814: self.Parent.HasNewData = True Laurent@814: Laurent@814: def SetValue(self, value): Laurent@892: if (self.VariableType == "STRING" and value.startswith("'") and value.endswith("'") or Laurent@892: self.VariableType == "WSTRING" and value.startswith('"') and value.endswith('"')): Laurent@892: value = value[1:-1] Laurent@814: if self.Value != value: Laurent@814: self.Value = value Laurent@814: self.Parent.HasNewData = True Laurent@814: Laurent@814: def GetValue(self): Laurent@887: if self.VariableType == "STRING": Laurent@878: return "'%s'" % self.Value Laurent@887: elif self.VariableType == "WSTRING": Laurent@878: return "\"%s\"" % self.Value Laurent@887: elif isinstance(self.Value, FloatType): Laurent@887: return "%.6g" % self.Value Laurent@814: return self.Value Laurent@814: Laurent@902: def GetNearestData(self, tick, adjust): Laurent@902: if self.IsNumVariable(): Laurent@902: ticks = self.Data[:, 0] Laurent@902: new_cursor = numpy.argmin(abs(ticks - tick)) Laurent@902: if adjust == -1 and ticks[new_cursor] > tick and new_cursor > 0: Laurent@902: new_cursor -= 1 Laurent@902: elif adjust == 1 and ticks[new_cursor] < tick and new_cursor < len(ticks): Laurent@902: new_cursor += 1 Laurent@902: return new_cursor Laurent@902: return None Laurent@902: Laurent@814: class DebugVariableTable(CustomTable): Laurent@814: Laurent@814: def GetValue(self, row, col): Laurent@814: if row < self.GetNumberRows(): Laurent@814: return self.GetValueByName(row, self.GetColLabelValue(col, False)) Laurent@814: return "" Laurent@814: Laurent@814: def SetValue(self, row, col, value): Laurent@814: if col < len(self.colnames): Laurent@814: self.SetValueByName(row, self.GetColLabelValue(col, False), value) Laurent@814: Laurent@814: def GetValueByName(self, row, colname): Laurent@814: if row < self.GetNumberRows(): Laurent@814: if colname == "Variable": Laurent@814: return self.data[row].GetVariable() Laurent@814: elif colname == "Value": Laurent@814: return self.data[row].GetValue() Laurent@814: return "" Laurent@814: Laurent@814: def SetValueByName(self, row, colname, value): Laurent@814: if row < self.GetNumberRows(): Laurent@814: if colname == "Variable": Laurent@814: self.data[row].SetVariable(value) Laurent@814: elif colname == "Value": Laurent@814: self.data[row].SetValue(value) Laurent@814: Laurent@814: def IsForced(self, row): Laurent@814: if row < self.GetNumberRows(): Laurent@814: return self.data[row].IsForced() Laurent@814: return False Laurent@814: Laurent@887: def IsNumVariable(self, row): Laurent@887: if row < self.GetNumberRows(): Laurent@887: return self.data[row].IsNumVariable() Laurent@887: return False Laurent@887: Laurent@814: def _updateColAttrs(self, grid): Laurent@814: """ Laurent@814: wx.grid.Grid -> update the column attributes to add the Laurent@814: appropriate renderer given the column name. Laurent@814: Laurent@814: Otherwise default to the default renderer. Laurent@814: """ Laurent@814: Laurent@814: for row in range(self.GetNumberRows()): Laurent@814: for col in range(self.GetNumberCols()): Laurent@887: colname = self.GetColLabelValue(col, False) Laurent@909: if colname == "Value": Laurent@909: if self.IsForced(row): Laurent@909: grid.SetCellTextColour(row, col, wx.BLUE) Laurent@814: else: Laurent@909: grid.SetCellTextColour(row, col, wx.BLACK) Laurent@909: grid.SetReadOnly(row, col, True) Laurent@814: self.ResizeRow(grid, row) Laurent@814: Laurent@814: def AppendItem(self, data): Laurent@814: self.data.append(data) Laurent@814: Laurent@814: def InsertItem(self, idx, data): Laurent@814: self.data.insert(idx, data) Laurent@814: Laurent@814: def RemoveItem(self, idx): Laurent@814: self.data.pop(idx) Laurent@814: Laurent@814: def MoveItem(self, idx, new_idx): Laurent@814: self.data.insert(new_idx, self.data.pop(idx)) Laurent@814: Laurent@814: def GetItem(self, idx): Laurent@814: return self.data[idx] Laurent@814: Laurent@814: class DebugVariableDropTarget(wx.TextDropTarget): Laurent@814: Laurent@909: def __init__(self, parent, control): Laurent@814: wx.TextDropTarget.__init__(self) Laurent@814: self.ParentWindow = parent Laurent@909: self.ParentControl = control Laurent@814: Laurent@814: def OnDropText(self, x, y, data): Laurent@814: message = None Laurent@814: try: Laurent@814: values = eval(data) Laurent@814: except: Laurent@814: message = _("Invalid value \"%s\" for debug variable")%data Laurent@814: values = None Laurent@814: if not isinstance(values, TupleType): Laurent@814: message = _("Invalid value \"%s\" for debug variable")%data Laurent@814: values = None Laurent@909: Laurent@814: if message is not None: Laurent@814: wx.CallAfter(self.ShowMessage, message) Laurent@909: elif values is not None and values[1] == "debug": Laurent@909: if self.ParentControl == self.ParentWindow.VariablesGrid: Laurent@909: x, y = self.ParentWindow.VariablesGrid.CalcUnscrolledPosition(x, y) Laurent@909: row = self.ParentWindow.VariablesGrid.YToRow(y - self.ParentWindow.VariablesGrid.GetColLabelSize()) Laurent@909: if row == wx.NOT_FOUND: Laurent@909: row = self.ParentWindow.Table.GetNumberRows() Laurent@909: self.ParentWindow.InsertValue(values[0], row, force=True) Laurent@909: else: Laurent@909: x, y = self.ParentWindow.GraphicsCanvasWindow.CalcUnscrolledPosition(x, y) Laurent@909: width, height = self.ParentWindow.GraphicsCanvas.GetSize() Laurent@909: target = None Laurent@909: merge_type = GRAPH_PARALLEL Laurent@909: for infos in self.ParentWindow.GraphicsAxes: Laurent@909: ax, ay, aw, ah = infos["axes"].get_position().bounds Laurent@909: rect = wx.Rect(ax * width, height - (ay + ah) * height, Laurent@909: aw * width, ah * height) Laurent@909: if rect.InsideXY(x, y): Laurent@909: target = infos Laurent@909: merge_rect = wx.Rect(ax * width, height - (ay + ah) * height, Laurent@909: aw * width / 2., ah * height) Laurent@909: if merge_rect.InsideXY(x, y): Laurent@909: merge_type = GRAPH_ORTHOGONAL Laurent@909: break Laurent@909: self.ParentWindow.MergeGraphs(values[0], target, merge_type, force=True) Laurent@814: Laurent@814: def ShowMessage(self, message): Laurent@814: dialog = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK|wx.ICON_ERROR) Laurent@814: dialog.ShowModal() Laurent@814: dialog.Destroy() Laurent@814: Laurent@887: SCROLLBAR_UNIT = 10 Laurent@887: Laurent@902: def NextTick(variables): Laurent@902: next_tick = None Laurent@902: for var_name, data in variables: Laurent@902: if len(data) > 0: Laurent@902: if next_tick is None: Laurent@902: next_tick = data[0][0] Laurent@902: else: Laurent@902: next_tick = min(next_tick, data[0][0]) Laurent@902: return next_tick Laurent@902: Laurent@909: def OrthogonalData(item, start_tick, end_tick): Laurent@909: data = item.GetData(start_tick, end_tick) Laurent@909: min_value, max_value = item.GetRange() Laurent@909: if min_value is not None and max_value is not None: Laurent@909: center = (min_value + max_value) / 2. Laurent@909: range = max(1.0, max_value - min_value) Laurent@909: else: Laurent@909: center = 0.5 Laurent@909: range = 1.0 Laurent@909: return data, center - range * 0.55, center + range * 0.55 Laurent@909: Laurent@887: class DebugVariablePanel(wx.SplitterWindow, DebugViewer): Laurent@814: Laurent@902: def __init__(self, parent, producer, window): Laurent@887: wx.SplitterWindow.__init__(self, parent, style=wx.SP_3D) Laurent@902: Laurent@902: self.ParentWindow = window Laurent@902: Laurent@814: DebugViewer.__init__(self, producer, True) Laurent@814: Laurent@887: self.SetSashGravity(0.5) Laurent@887: self.SetNeedUpdating(True) Laurent@887: self.SetMinimumPaneSize(1) Laurent@887: Laurent@887: self.MainPanel = wx.Panel(self, style=wx.TAB_TRAVERSAL) Laurent@887: Laurent@887: main_panel_sizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=0) Laurent@887: main_panel_sizer.AddGrowableCol(0) Laurent@887: main_panel_sizer.AddGrowableRow(1) Laurent@814: Laurent@814: button_sizer = wx.BoxSizer(wx.HORIZONTAL) Laurent@887: main_panel_sizer.AddSizer(button_sizer, border=5, Laurent@814: flag=wx.ALIGN_RIGHT|wx.ALL) Laurent@814: Laurent@814: for name, bitmap, help in [ Laurent@814: ("DeleteButton", "remove_element", _("Remove debug variable")), Laurent@814: ("UpButton", "up", _("Move debug variable up")), Laurent@814: ("DownButton", "down", _("Move debug variable down"))]: Laurent@887: button = wx.lib.buttons.GenBitmapButton(self.MainPanel, bitmap=GetBitmap(bitmap), Laurent@814: size=wx.Size(28, 28), style=wx.NO_BORDER) Laurent@814: button.SetToolTipString(help) Laurent@814: setattr(self, name, button) Laurent@814: button_sizer.AddWindow(button, border=5, flag=wx.LEFT) Laurent@814: Laurent@887: self.VariablesGrid = CustomGrid(self.MainPanel, size=wx.Size(-1, 150), style=wx.VSCROLL) Laurent@909: self.VariablesGrid.SetDropTarget(DebugVariableDropTarget(self, self.VariablesGrid)) Laurent@814: self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK, Laurent@814: self.OnVariablesGridCellRightClick) Laurent@892: self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, Laurent@892: self.OnVariablesGridCellLeftClick) Laurent@887: main_panel_sizer.AddWindow(self.VariablesGrid, flag=wx.GROW) Laurent@887: Laurent@887: self.MainPanel.SetSizer(main_panel_sizer) Laurent@814: Laurent@814: self.HasNewData = False Laurent@902: self.Ticks = numpy.array([]) Laurent@902: self.RangeValues = None Laurent@902: self.StartTick = 0 Laurent@902: self.Fixed = False Laurent@902: self.Force = False Laurent@814: Laurent@814: self.Table = DebugVariableTable(self, [], GetDebugVariablesTableColnames()) Laurent@814: self.VariablesGrid.SetTable(self.Table) Laurent@814: self.VariablesGrid.SetButtons({"Delete": self.DeleteButton, Laurent@814: "Up": self.UpButton, Laurent@814: "Down": self.DownButton}) Laurent@814: Laurent@814: def _AddVariable(new_row): Laurent@814: return self.VariablesGrid.GetGridCursorRow() Laurent@814: setattr(self.VariablesGrid, "_AddRow", _AddVariable) Laurent@814: Laurent@814: def _DeleteVariable(row): Laurent@814: item = self.Table.GetItem(row) Laurent@814: self.RemoveDataConsumer(item) Laurent@907: for infos in self.GraphicsAxes: Laurent@907: if item in infos["items"]: Laurent@907: if len(infos["items"]) == 1: Laurent@907: self.GraphicsAxes.remove(infos) Laurent@907: else: Laurent@907: infos["items"].remove(item) Laurent@907: break Laurent@814: self.Table.RemoveItem(row) Laurent@887: self.ResetGraphics() Laurent@814: self.RefreshGrid() Laurent@814: setattr(self.VariablesGrid, "_DeleteRow", _DeleteVariable) Laurent@814: Laurent@814: def _MoveVariable(row, move): Laurent@814: new_row = max(0, min(row + move, self.Table.GetNumberRows() - 1)) Laurent@814: if new_row != row: Laurent@814: self.Table.MoveItem(row, new_row) Laurent@887: self.ResetGraphics() Laurent@814: self.RefreshGrid() Laurent@814: return new_row Laurent@814: setattr(self.VariablesGrid, "_MoveRow", _MoveVariable) Laurent@814: Laurent@814: self.VariablesGrid.SetRowLabelSize(0) Laurent@814: Laurent@909: self.GridColSizes = [200, 100] Laurent@909: Laurent@814: for col in range(self.Table.GetNumberCols()): Laurent@814: attr = wx.grid.GridCellAttr() Laurent@909: attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER) Laurent@814: self.VariablesGrid.SetColAttr(col, attr) Laurent@909: self.VariablesGrid.SetColSize(col, self.GridColSizes[col]) Laurent@814: Laurent@814: self.Table.ResetView(self.VariablesGrid) Laurent@814: self.VariablesGrid.RefreshButtons() Laurent@887: Laurent@888: if USE_MPL: Laurent@888: self.GraphicsPanel = wx.Panel(self, style=wx.TAB_TRAVERSAL) Laurent@888: Laurent@907: self.GraphicsPanelSizer = wx.BoxSizer(wx.VERTICAL) Laurent@888: Laurent@902: graphics_button_sizer = wx.BoxSizer(wx.HORIZONTAL) Laurent@907: self.GraphicsPanelSizer.AddSizer(graphics_button_sizer, border=5, flag=wx.GROW|wx.ALL) Laurent@902: Laurent@902: range_label = wx.StaticText(self.GraphicsPanel, label=_('Range:')) Laurent@902: graphics_button_sizer.AddWindow(range_label, flag=wx.ALIGN_CENTER_VERTICAL) Laurent@902: Laurent@905: self.CanvasRange = wx.ComboBox(self.GraphicsPanel, style=wx.CB_READONLY) Laurent@902: self.Bind(wx.EVT_COMBOBOX, self.OnRangeChanged, self.CanvasRange) Laurent@905: graphics_button_sizer.AddWindow(self.CanvasRange, 1, Laurent@905: border=5, flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL) Laurent@902: Laurent@902: for name, bitmap, help in [ Laurent@902: ("ResetButton", "reset", _("Clear the graph values")), Laurent@902: ("CurrentButton", "current", _("Go to current value")), Laurent@902: ("ExportGraphButton", "export_graph", _("Export graph values to clipboard"))]: Laurent@902: button = wx.lib.buttons.GenBitmapButton(self.GraphicsPanel, Laurent@902: bitmap=GetBitmap(bitmap), Laurent@902: size=wx.Size(28, 28), style=wx.NO_BORDER) Laurent@902: button.SetToolTipString(help) Laurent@902: setattr(self, name, button) Laurent@902: self.Bind(wx.EVT_BUTTON, getattr(self, "On" + name), button) Laurent@902: graphics_button_sizer.AddWindow(button, border=5, flag=wx.LEFT) Laurent@902: Laurent@902: self.CanvasPosition = wx.ScrollBar(self.GraphicsPanel, Laurent@902: size=wx.Size(0, 16), style=wx.SB_HORIZONTAL) Laurent@902: self.CanvasPosition.Bind(wx.EVT_SCROLL_THUMBTRACK, Laurent@902: self.OnPositionChanging, self.CanvasPosition) Laurent@902: self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEUP, Laurent@902: self.OnPositionChanging, self.CanvasPosition) Laurent@902: self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEDOWN, Laurent@902: self.OnPositionChanging, self.CanvasPosition) Laurent@902: self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEUP, Laurent@902: self.OnPositionChanging, self.CanvasPosition) Laurent@902: self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEDOWN, Laurent@902: self.OnPositionChanging, self.CanvasPosition) Laurent@907: self.GraphicsPanelSizer.AddWindow(self.CanvasPosition, border=5, flag=wx.GROW|wx.LEFT|wx.RIGHT|wx.BOTTOM) Laurent@902: Laurent@888: self.GraphicsCanvasWindow = wx.ScrolledWindow(self.GraphicsPanel, style=wx.HSCROLL|wx.VSCROLL) Laurent@888: self.GraphicsCanvasWindow.Bind(wx.EVT_SIZE, self.OnGraphicsCanvasWindowResize) Laurent@907: self.GraphicsPanelSizer.AddWindow(self.GraphicsCanvasWindow, 1, flag=wx.GROW) Laurent@888: Laurent@888: graphics_canvas_window_sizer = wx.BoxSizer(wx.VERTICAL) Laurent@888: Laurent@888: self.GraphicsFigure = matplotlib.figure.Figure() Laurent@888: self.GraphicsAxes = [] Laurent@888: Laurent@888: self.GraphicsCanvas = FigureCanvas(self.GraphicsCanvasWindow, -1, self.GraphicsFigure) Laurent@909: self.GraphicsCanvas.mpl_connect("button_press_event", self.OnGraphicsCanvasClick) Laurent@909: self.GraphicsCanvas.SetDropTarget(DebugVariableDropTarget(self, self.GraphicsCanvas)) Laurent@888: graphics_canvas_window_sizer.AddWindow(self.GraphicsCanvas, 1, flag=wx.GROW) Laurent@888: Laurent@888: self.GraphicsCanvasWindow.SetSizer(graphics_canvas_window_sizer) Laurent@888: Laurent@888: self.Graphics3DFigure = matplotlib.figure.Figure() Laurent@888: self.Graphics3DFigure.subplotpars.update(left=0.0, right=1.0, bottom=0.0, top=1.0) Laurent@888: Laurent@888: self.LastMotionTime = gettime() Laurent@888: self.Graphics3DAxes = self.Graphics3DFigure.gca(projection='3d') Laurent@888: self.Graphics3DAxes.set_color_cycle(['b']) Laurent@888: setattr(self.Graphics3DAxes, "_on_move", self.OnGraphics3DMotion) Laurent@888: Laurent@888: self.Graphics3DCanvas = FigureCanvas(self.GraphicsPanel, -1, self.Graphics3DFigure) Laurent@892: self.Graphics3DCanvas.SetMinSize(wx.Size(1, 1)) Laurent@907: self.GraphicsPanelSizer.AddWindow(self.Graphics3DCanvas, 1, flag=wx.GROW) Laurent@888: Laurent@888: self.Graphics3DAxes.mouse_init() Laurent@888: Laurent@907: self.GraphicsPanel.SetSizer(self.GraphicsPanelSizer) Laurent@888: Laurent@888: self.SplitHorizontally(self.MainPanel, self.GraphicsPanel, -200) Laurent@888: Laurent@888: else: Laurent@888: self.Initialize(self.MainPanel) Laurent@887: Laurent@887: self.ResetGraphics() Laurent@902: self.RefreshCanvasRange() Laurent@902: self.RefreshScrollBar() Laurent@902: Laurent@902: def SetDataProducer(self, producer): Laurent@902: DebugViewer.SetDataProducer(self, producer) Laurent@902: Laurent@902: if self.DataProducer is not None: Laurent@902: self.Ticktime = self.DataProducer.GetTicktime() Laurent@902: self.RefreshCanvasRange() Laurent@902: else: Laurent@902: self.Ticktime = 0 Laurent@902: Laurent@902: def RefreshNewData(self, *args, **kwargs): Laurent@902: if self.HasNewData or self.Force: Laurent@814: self.HasNewData = False Laurent@887: self.RefreshGrid(only_values=True) Laurent@902: DebugViewer.RefreshNewData(self, *args, **kwargs) Laurent@902: Laurent@902: def NewDataAvailable(self, tick, *args, **kwargs): Laurent@902: if tick is not None: Laurent@902: self.Ticks = numpy.append(self.Ticks, [tick]) Laurent@902: if not self.Fixed or tick < self.StartTick + self.CurrentRange: Laurent@902: self.StartTick = max(self.StartTick, tick - self.CurrentRange) Laurent@902: DebugViewer.NewDataAvailable(self, tick, *args, **kwargs) Laurent@814: Laurent@887: def RefreshGrid(self, only_values=False): Laurent@814: self.Freeze() Laurent@887: if only_values: Laurent@887: for col in xrange(self.Table.GetNumberCols()): Laurent@887: if self.Table.GetColLabelValue(col, False) == "Value": Laurent@887: for row in xrange(self.Table.GetNumberRows()): Laurent@887: self.VariablesGrid.SetCellValue(row, col, str(self.Table.GetValueByName(row, "Value"))) Laurent@887: else: Laurent@887: self.Table.ResetView(self.VariablesGrid) Laurent@814: self.VariablesGrid.RefreshButtons() Laurent@887: Laurent@902: self.RefreshScrollBar() Laurent@902: Laurent@902: self.Thaw() Laurent@902: Laurent@909: if USE_MPL: Laurent@909: Laurent@909: if not self.Fixed or self.Force: Laurent@909: self.Force = False Laurent@909: Laurent@909: # Refresh graphics Laurent@909: start_tick, end_tick = self.StartTick, self.StartTick + self.CurrentRange Laurent@909: for infos in self.GraphicsAxes: Laurent@909: Laurent@909: if infos["type"] == GRAPH_PARALLEL: Laurent@909: min_value = max_value = None Laurent@909: Laurent@909: for idx, item in enumerate(infos["items"]): Laurent@909: data = item.GetData(start_tick, end_tick) Laurent@909: if data is not None: Laurent@909: item_min_value, item_max_value = item.GetRange() Laurent@909: if min_value is None: Laurent@909: min_value = item_min_value Laurent@909: elif item_min_value is not None: Laurent@909: min_value = min(min_value, item_min_value) Laurent@909: if max_value is None: Laurent@909: max_value = item_max_value Laurent@909: elif item_max_value is not None: Laurent@909: max_value = max(max_value, item_max_value) Laurent@909: Laurent@909: if len(infos["plots"]) <= idx: Laurent@909: infos["plots"].append( Laurent@909: infos["axes"].plot(data[:, 0], data[:, 1])[0]) Laurent@909: else: Laurent@909: infos["plots"][idx].set_data(data[:, 0], data[:, 1]) Laurent@909: Laurent@909: if min_value is not None and max_value is not None: Laurent@909: y_center = (min_value + max_value) / 2. Laurent@909: y_range = max(1.0, max_value - min_value) Laurent@909: else: Laurent@909: y_center = 0.5 Laurent@909: y_range = 1.0 Laurent@909: x_min, x_max = start_tick, end_tick Laurent@909: y_min, y_max = y_center - y_range * 0.55, y_center + y_range * 0.55 Laurent@909: Laurent@909: else: Laurent@909: min_start_tick = reduce(max, [item.GetData()[0, 0] Laurent@909: for item in infos["items"] Laurent@909: if len(item.GetData()) > 0], 0) Laurent@909: start_tick = max(self.StartTick, min_start_tick) Laurent@909: end_tick = max(self.StartTick + self.CurrentRange, min_start_tick) Laurent@909: x_data, x_min, x_max = OrthogonalData(infos["items"][0], start_tick, end_tick) Laurent@909: y_data, y_min, y_max = OrthogonalData(infos["items"][1], start_tick, end_tick) Laurent@909: length = 0 Laurent@909: if x_data is not None and y_data is not None: Laurent@909: length = min(len(x_data), len(y_data)) Laurent@909: if len(infos["items"]) < 3: Laurent@909: if x_data is not None and y_data is not None: Laurent@909: if len(infos["plots"]) == 0: Laurent@909: infos["plots"].append( Laurent@909: infos["axes"].plot(x_data[:, 1][:length], Laurent@909: y_data[:, 1][:length])[0]) Laurent@909: else: Laurent@909: infos["plots"][0].set_data( Laurent@909: x_data[:, 1][:length], Laurent@909: y_data[:, 1][:length]) Laurent@909: else: Laurent@909: while len(infos["axes"].lines) > 0: Laurent@909: infos["axes"].lines.pop() Laurent@909: z_data, z_min, z_max = OrthogonalData(infos["items"][2], start_tick, end_tick) Laurent@909: if x_data is not None and y_data is not None and z_data is not None: Laurent@909: length = min(length, len(z_data)) Laurent@909: infos["axes"].plot(x_data[:, 1][:length], Laurent@909: y_data[:, 1][:length], Laurent@909: zs = z_data[:, 1][:length]) Laurent@909: infos["axes"].set_zlim(z_min, z_max) Laurent@909: Laurent@909: infos["axes"].set_xlim(x_min, x_max) Laurent@909: infos["axes"].set_ylim(y_min, y_max) Laurent@909: Laurent@909: plot2d = plot3d = 0 Laurent@907: for infos in self.GraphicsAxes: Laurent@909: labels = ["%s: %s" % (item.GetVariable(), item.GetValue()) Laurent@909: for item in infos["items"]] Laurent@909: if infos["type"] == GRAPH_PARALLEL: Laurent@909: infos["axes"].legend(infos["plots"], labels, Laurent@909: loc="upper left", frameon=False, Laurent@909: prop={'size':'small'}) Laurent@909: plot2d += 1 Laurent@907: else: Laurent@909: infos["axes"].set_xlabel(labels[0], fontdict={'size':'small'}) Laurent@909: infos["axes"].set_ylabel(labels[1], fontdict={'size':'small'}) Laurent@909: if len(labels) > 2: Laurent@909: infos["axes"].set_zlabel(labels[2], fontdict={'size':'small'}) Laurent@909: plot3d += 1 Laurent@909: else: Laurent@909: plot2d += 1 Laurent@909: Laurent@909: if plot2d > 0: Laurent@902: self.GraphicsCanvas.draw() Laurent@909: if plot3d > 0: Laurent@902: self.Graphics3DCanvas.draw() Laurent@902: Laurent@814: def UnregisterObsoleteData(self): Laurent@814: items = [(idx, item) for idx, item in enumerate(self.Table.GetData())] Laurent@814: items.reverse() Laurent@814: for idx, item in items: Laurent@814: iec_path = item.GetVariable().upper() Laurent@814: if self.GetDataType(iec_path) is None: Laurent@814: self.RemoveDataConsumer(item) Laurent@814: self.Table.RemoveItem(idx) Laurent@814: else: Laurent@814: self.AddDataConsumer(iec_path, item) Laurent@887: item.RefreshVariableType() Laurent@814: self.Freeze() Laurent@814: self.Table.ResetView(self.VariablesGrid) Laurent@814: self.VariablesGrid.RefreshButtons() Laurent@814: self.Thaw() Laurent@902: if self.DataProducer is not None: Laurent@902: self.Ticktime = self.DataProducer.GetTicktime() Laurent@902: self.RefreshCanvasRange() Laurent@814: Laurent@814: def ResetGrid(self): Laurent@814: self.DeleteDataConsumers() Laurent@814: self.Table.Empty() Laurent@814: self.Freeze() Laurent@814: self.Table.ResetView(self.VariablesGrid) Laurent@814: self.VariablesGrid.RefreshButtons() Laurent@814: self.Thaw() Laurent@887: self.ResetGraphics() Laurent@814: Laurent@902: def RefreshCanvasRange(self): Laurent@902: if self.Ticktime == 0 and self.RangeValues != RANGE_VALUES: Laurent@902: self.RangeValues = RANGE_VALUES Laurent@902: self.CanvasRange.Clear() Laurent@902: for text, value in RANGE_VALUES: Laurent@902: self.CanvasRange.Append(text) Laurent@902: self.CanvasRange.SetStringSelection(RANGE_VALUES[0][0]) Laurent@902: self.CurrentRange = RANGE_VALUES[0][1] Laurent@902: self.RefreshGrid(True) Laurent@902: elif self.Ticktime != 0 and self.RangeValues != TIME_RANGE_VALUES: Laurent@902: self.RangeValues = TIME_RANGE_VALUES Laurent@902: self.CanvasRange.Clear() Laurent@902: for text, value in TIME_RANGE_VALUES: Laurent@902: self.CanvasRange.Append(text) Laurent@902: self.CanvasRange.SetStringSelection(TIME_RANGE_VALUES[0][0]) Laurent@902: self.CurrentRange = TIME_RANGE_VALUES[0][1] / self.Ticktime Laurent@902: self.RefreshGrid(True) Laurent@902: Laurent@902: def RefreshScrollBar(self): Laurent@902: if len(self.Ticks) > 0: Laurent@902: pos = int(self.StartTick - self.Ticks[0]) Laurent@902: range = int(self.Ticks[-1] - self.Ticks[0]) Laurent@902: else: Laurent@902: pos = 0 Laurent@902: range = 0 Laurent@902: self.CanvasPosition.SetScrollbar(pos, self.CurrentRange, range, self.CurrentRange) Laurent@902: Laurent@814: def GetForceVariableMenuFunction(self, iec_path, item): Laurent@814: iec_type = self.GetDataType(iec_path) Laurent@814: def ForceVariableFunction(event): Laurent@814: if iec_type is not None: Laurent@814: dialog = ForceVariableDialog(self, iec_type, str(item.GetValue())) Laurent@814: if dialog.ShowModal() == wx.ID_OK: Laurent@814: self.ForceDataValue(iec_path, dialog.GetValue()) Laurent@814: return ForceVariableFunction Laurent@814: Laurent@814: def GetReleaseVariableMenuFunction(self, iec_path): Laurent@814: def ReleaseVariableFunction(event): Laurent@814: self.ReleaseDataValue(iec_path) Laurent@814: return ReleaseVariableFunction Laurent@814: Laurent@892: def OnVariablesGridCellLeftClick(self, event): Laurent@892: if event.GetCol() == 0: Laurent@892: row = event.GetRow() Laurent@898: data = wx.TextDataObject(str((self.Table.GetValueByName(row, "Variable"), "debug"))) Laurent@892: dragSource = wx.DropSource(self.VariablesGrid) Laurent@892: dragSource.SetData(data) Laurent@892: dragSource.DoDragDrop() Laurent@892: event.Skip() Laurent@892: Laurent@814: def OnVariablesGridCellRightClick(self, event): Laurent@814: row, col = event.GetRow(), event.GetCol() Laurent@814: if self.Table.GetColLabelValue(col, False) == "Value": Laurent@814: iec_path = self.Table.GetValueByName(row, "Variable").upper() Laurent@814: Laurent@814: menu = wx.Menu(title='') Laurent@814: Laurent@814: new_id = wx.NewId() Laurent@814: AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Force value")) Laurent@814: self.Bind(wx.EVT_MENU, self.GetForceVariableMenuFunction(iec_path.upper(), self.Table.GetItem(row)), id=new_id) Laurent@814: Laurent@814: new_id = wx.NewId() Laurent@814: AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=_("Release value")) Laurent@814: self.Bind(wx.EVT_MENU, self.GetReleaseVariableMenuFunction(iec_path.upper()), id=new_id) Laurent@814: Laurent@814: if self.Table.IsForced(row): Laurent@814: menu.Enable(new_id, True) Laurent@814: else: Laurent@814: menu.Enable(new_id, False) Laurent@814: Laurent@814: self.PopupMenu(menu) Laurent@814: Laurent@814: menu.Destroy() Laurent@814: event.Skip() Laurent@814: Laurent@902: def RefreshRange(self): Laurent@902: if len(self.Ticks) > 0: Laurent@902: if self.Fixed and self.Ticks[-1] - self.Ticks[0] < self.CurrentRange: Laurent@902: self.Fixed = False Laurent@902: if self.Fixed: Laurent@902: self.StartTick = min(self.StartTick, self.Ticks[-1] - self.CurrentRange) Laurent@902: else: Laurent@902: self.StartTick = max(self.Ticks[0], self.Ticks[-1] - self.CurrentRange) Laurent@902: self.Force = True Laurent@902: self.RefreshGrid(True) Laurent@902: Laurent@902: def OnRangeChanged(self, event): Laurent@902: try: Laurent@902: if self.Ticktime == 0: Laurent@902: self.CurrentRange = self.RangeValues[self.CanvasRange.GetSelection()][1] Laurent@902: else: Laurent@902: self.CurrentRange = self.RangeValues[self.CanvasRange.GetSelection()][1] / self.Ticktime Laurent@902: except ValueError, e: Laurent@902: self.CanvasRange.SetValue(str(self.CurrentRange)) Laurent@902: wx.CallAfter(self.RefreshRange) Laurent@902: event.Skip() Laurent@902: Laurent@902: def OnResetButton(self, event): Laurent@902: self.StartTick = 0 Laurent@902: self.Fixed = False Laurent@902: for item in self.Table.GetData(): Laurent@902: item.ResetData() Laurent@902: self.RefreshGrid(True) Laurent@902: event.Skip() Laurent@902: Laurent@902: def OnCurrentButton(self, event): Laurent@902: if len(self.Ticks) > 0: Laurent@902: self.StartTick = max(self.Ticks[0], self.Ticks[-1] - self.CurrentRange) Laurent@902: self.Fixed = False Laurent@902: self.Force = True Laurent@902: self.RefreshGrid(True) Laurent@902: event.Skip() Laurent@902: Laurent@902: def CopyDataToClipboard(self, variables): Laurent@902: text = "tick;%s;\n" % ";".join([var_name for var_name, data in variables]) Laurent@902: next_tick = NextTick(variables) Laurent@902: while next_tick is not None: Laurent@902: values = [] Laurent@902: for var_name, data in variables: Laurent@902: if len(data) > 0: Laurent@902: if next_tick == data[0][0]: Laurent@902: values.append("%.3f" % data.pop(0)[1]) Laurent@902: else: Laurent@902: values.append("") Laurent@902: else: Laurent@902: values.append("") Laurent@902: text += "%d;%s;\n" % (next_tick, ";".join(values)) Laurent@902: next_tick = NextTick(variables) Laurent@902: self.ParentWindow.SetCopyBuffer(text) Laurent@902: Laurent@902: def OnExportGraphButton(self, event): Laurent@902: variables = [] Laurent@902: for item in self.Table.GetData(): Laurent@902: if item.IsNumVariable(): Laurent@902: variables.append((item.GetVariable(), [entry for entry in item.GetData()])) Laurent@902: wx.CallAfter(self.CopyDataToClipboard, variables) Laurent@902: event.Skip() Laurent@902: Laurent@902: def OnPositionChanging(self, event): Laurent@902: if len(self.Ticks) > 0: Laurent@902: self.StartTick = self.Ticks[0] + event.GetPosition() Laurent@902: self.Fixed = True Laurent@902: self.Force = True Laurent@902: wx.CallAfter(self.NewDataAvailable, None, True) Laurent@902: event.Skip() Laurent@902: Laurent@909: def InsertValue(self, iec_path, idx = None, force=False): Laurent@814: if idx is None: Laurent@814: idx = self.Table.GetNumberRows() Laurent@814: for item in self.Table.GetData(): Laurent@814: if iec_path == item.GetVariable(): Laurent@814: return Laurent@887: item = VariableTableItem(self, iec_path) Laurent@814: result = self.AddDataConsumer(iec_path.upper(), item) Laurent@814: if result is not None or force: Laurent@814: self.Table.InsertItem(idx, item) Laurent@907: if item.IsNumVariable(): Laurent@907: self.GraphicsAxes.append({ Laurent@907: "items": [item], Laurent@907: "axes": None, Laurent@909: "type": GRAPH_PARALLEL, Laurent@907: "plots": []}) Laurent@887: self.ResetGraphics() Laurent@814: self.RefreshGrid() Laurent@909: Laurent@909: def MergeGraphs(self, source, target_infos, merge_type, force=False): Laurent@909: source_item = None Laurent@909: for item in self.Table.GetData(): Laurent@909: if item.GetVariable() == source: Laurent@909: source_item = item Laurent@909: if source_item is None: Laurent@909: item = VariableTableItem(self, source) Laurent@909: if item.IsNumVariable(): Laurent@909: result = self.AddDataConsumer(source.upper(), item) Laurent@909: if result is not None or force: Laurent@909: self.Table.InsertItem(self.Table.GetNumberRows(), item) Laurent@909: source_item = item Laurent@909: if source_item is not None: Laurent@909: source_infos = None Laurent@909: for infos in self.GraphicsAxes: Laurent@909: if source_item in infos["items"]: Laurent@909: source_infos = infos Laurent@909: break Laurent@909: if target_infos is None and source_infos is None: Laurent@909: self.GraphicsAxes.append({ Laurent@909: "items": [source_item], Laurent@909: "axes": None, Laurent@909: "type": GRAPH_PARALLEL, Laurent@909: "plots": []}) Laurent@909: Laurent@909: self.ResetGraphics() Laurent@909: self.RefreshGrid() Laurent@909: Laurent@909: elif target_infos is not None: Laurent@909: if (merge_type == GRAPH_PARALLEL and target_infos["type"] != merge_type or Laurent@909: merge_type == GRAPH_ORTHOGONAL and Laurent@909: (target_infos["type"] == GRAPH_PARALLEL and len(target_infos["items"]) > 1 or Laurent@909: target_infos["type"] == GRAPH_ORTHOGONAL and len(target_infos["items"]) >= 3)): Laurent@909: return Laurent@909: Laurent@909: if source_infos is not None: Laurent@909: source_infos["items"].remove(source_item) Laurent@909: if len(source_infos["items"]) == 0: Laurent@909: self.GraphicsAxes.remove(source_infos) Laurent@909: Laurent@909: target_infos["items"].append(source_item) Laurent@909: target_infos["type"] = merge_type Laurent@909: Laurent@909: self.ResetGraphics() Laurent@909: self.RefreshGrid() Laurent@887: Laurent@814: def GetDebugVariables(self): Laurent@814: return [item.GetVariable() for item in self.Table.GetData()] Laurent@887: Laurent@909: def OnGraphicsCanvasClick(self, event): Laurent@909: for infos in self.GraphicsAxes: Laurent@909: if infos["axes"] == event.inaxes: Laurent@909: if len(infos["items"]) == 1: Laurent@909: data = wx.TextDataObject(str((infos["items"][0].GetVariable(), "debug"))) Laurent@909: dragSource = wx.DropSource(self.GraphicsCanvas) Laurent@909: dragSource.SetData(data) Laurent@909: dragSource.DoDragDrop() Laurent@909: if self.GraphicsCanvas.HasCapture(): Laurent@909: self.GraphicsCanvas.ReleaseMouse() Laurent@909: break Laurent@887: Laurent@887: def ResetGraphicsValues(self): Laurent@903: self.Ticks = numpy.array([]) Laurent@903: self.StartTick = 0 Laurent@887: for item in self.Table.GetData(): Laurent@887: item.ResetData() Laurent@887: Laurent@887: def ResetGraphics(self): Laurent@888: if USE_MPL: Laurent@888: self.GraphicsFigure.clear() Laurent@907: Laurent@909: axes_num = 0 Laurent@909: for infos in self.GraphicsAxes: Laurent@909: if infos["type"] != GRAPH_ORTHOGONAL or len(infos["items"]) < 3: Laurent@909: axes_num += 1 Laurent@909: if axes_num == len(self.GraphicsAxes): Laurent@909: self.Graphics3DCanvas.Hide() Laurent@909: else: Laurent@909: self.Graphics3DCanvas.Show() Laurent@909: self.GraphicsPanelSizer.Layout() Laurent@909: idx = 1 Laurent@909: for infos in self.GraphicsAxes: Laurent@909: if infos["type"] != GRAPH_ORTHOGONAL or len(infos["items"]) < 3: Laurent@909: axes = self.GraphicsFigure.add_subplot(axes_num, 1, idx) Laurent@909: infos["axes"] = axes Laurent@888: else: Laurent@909: infos["axes"] = self.Graphics3DAxes Laurent@909: infos["plots"] = [] Laurent@909: idx += 1 Laurent@888: self.RefreshGraphicsCanvasWindowScrollbars() Laurent@888: self.GraphicsCanvas.draw() Laurent@887: Laurent@887: def OnGraphics3DMotion(self, event): Laurent@887: current_time = gettime() Laurent@887: if current_time - self.LastMotionTime > REFRESH_PERIOD: Laurent@887: self.LastMotionTime = current_time Laurent@887: Axes3D._on_move(self.Graphics3DAxes, event) Laurent@902: Laurent@887: def RefreshGraphicsCanvasWindowScrollbars(self): Laurent@887: xstart, ystart = self.GraphicsCanvasWindow.GetViewStart() Laurent@887: window_size = self.GraphicsCanvasWindow.GetClientSize() Laurent@909: vwidth, vheight = (window_size[0], (len(self.GraphicsAxes) + 1) * 100) Laurent@887: self.GraphicsCanvas.SetMinSize(wx.Size(vwidth, vheight)) Laurent@887: posx = max(0, min(xstart, (vwidth - window_size[0]) / SCROLLBAR_UNIT)) Laurent@887: posy = max(0, min(ystart, (vheight - window_size[1]) / SCROLLBAR_UNIT)) Laurent@887: self.GraphicsCanvasWindow.Scroll(posx, posy) Laurent@887: self.GraphicsCanvasWindow.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT, Laurent@887: vwidth / SCROLLBAR_UNIT, vheight / SCROLLBAR_UNIT, posx, posy) Laurent@887: Laurent@887: def OnGraphicsCanvasWindowResize(self, event): Laurent@887: self.RefreshGraphicsCanvasWindowScrollbars() Laurent@887: event.Skip()