Skip to content

Commit

Permalink
autopep8
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Lautman committed Oct 20, 2018
1 parent 3bb45cf commit 9665c96
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 80 deletions.
90 changes: 53 additions & 37 deletions src/rqt_plot/data_plot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,18 @@
# separate class for DataPlot exceptions, just so that users can differentiate
# errors from the DataPlot widget from exceptions generated by the underlying
# libraries


class DataPlotException(Exception):
pass


class DataPlot(QWidget):

"""A widget for displaying a plot of data
The DataPlot widget displays a plot, on one of several plotting backends,
depending on which backend(s) are available at runtime. It currently
depending on which backend(s) are available at runtime. It currently
supports PyQtGraph, MatPlot and QwtPlot backends.
The DataPlot widget manages the plot backend internally, and can save
Expand All @@ -80,33 +84,39 @@ class DataPlot(QWidget):
{
'title': 'PyQtGraph',
'widget_class': PyQtGraphDataPlot,
'description': 'Based on PyQtGraph\n- installer: http://luke.campagnola.me/code/pyqtgraph\n',
'description':
'Based on PyQtGraph\n- installer: http://luke.campagnola.me/code/pyqtgraph\n',
'enabled': PyQtGraphDataPlot is not None,
},
{
'title': 'MatPlot',
'widget_class': MatDataPlot,
'description': 'Based on MatPlotLib\n- needs most CPU\n- needs matplotlib >= 1.1.0\n- if using PySide: PySide > 1.1.0\n',
'description':
'Based on MatPlotLib\n- needs most CPU\n- needs matplotlib >= 1.1.0\n- if using '
'PySide: PySide > 1.1.0\n',
'enabled': MatDataPlot is not None,
},
{
'title': 'QwtPlot',
'widget_class': QwtDataPlot,
'description': 'Based on QwtPlot\n- does not use timestamps\n- uses least CPU\n- needs Python Qwt bindings\n',
'description':
'Based on QwtPlot\n- does not use timestamps\n- uses least CPU\n- needs Python '
'Qwt bindings\n',
'enabled': QwtDataPlot is not None,
},
]

# pre-defined colors:
RED=(255, 0, 0)
GREEN=(0, 255, 0)
BLUE=(0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

SCALE_ALL=1
SCALE_VISIBLE=2
SCALE_EXTEND=4
SCALE_ALL = 1
SCALE_VISIBLE = 2
SCALE_EXTEND = 4

_colors = [Qt.blue, Qt.red, Qt.cyan, Qt.magenta, Qt.green, Qt.darkYellow, Qt.black, Qt.darkCyan, Qt.darkRed, Qt.gray]
_colors = [Qt.blue, Qt.red, Qt.cyan, Qt.magenta, Qt.green,
Qt.darkYellow, Qt.black, Qt.darkCyan, Qt.darkRed, Qt.gray]

limits_changed = Signal()
_redraw = Signal()
Expand Down Expand Up @@ -146,7 +156,9 @@ def __init__(self, parent=None):
if QT_BINDING == 'pyside':
version_info += ' and PySide %s' % \
('> 1.1.0' if qVersion().startswith('4.') else '>= 2.0.0')
raise RuntimeError('No usable plot type found. Install at least one of: PyQtGraph, MatPlotLib (at least %s) or Python-Qwt5.' % version_info)
raise RuntimeError(
'No usable plot type found. Install at least one of: PyQtGraph, MatPlotLib '
'(at least %s) or Python-Qwt5.' % version_info)

self._switch_data_plot_widget(self._plot_index)

Expand Down Expand Up @@ -205,7 +217,7 @@ def _switch_plot_markers(self, markers_on):

self.redraw()

# interface out to the managing GUI component: get title, save, restore,
# interface out to the managing GUI component: get title, save, restore,
# etc
def getTitle(self):
"""get the title of the current plotting backend"""
Expand Down Expand Up @@ -248,19 +260,20 @@ def restore_settings(self, plugin_settings, instance_settings):
except:
qWarning("Failed to restore Y limits")


def doSettingsDialog(self):
"""Present the user with a dialog for choosing the plot backend
This displays a SimpleSettingsDialog asking the user to choose a
plot type, gets the result, and updates the plot type as necessary
This method is blocking"""

marker_settings = [
{
'title': 'Show Plot Markers',
'description': 'Warning: Displaying markers in rqt_plot may cause\n \t high cpu load, especially using PyQtGraph\n',
'description':
'Warning: Displaying markers in rqt_plot may cause\n \t high cpu load, '
'especially using PyQtGraph\n',
'enabled': True,
}]
if self._markers_on:
Expand All @@ -269,11 +282,16 @@ def doSettingsDialog(self):
selected_checkboxes = []

dialog = SimpleSettingsDialog(title='Plot Options')
dialog.add_exclusive_option_group(title='Plot Type', options=self.plot_types, selected_index=self._plot_index)
dialog.add_checkbox_group(title='Plot Markers', options=marker_settings, selected_indexes=selected_checkboxes)
dialog.add_exclusive_option_group(
title='Plot Type', options=self.plot_types, selected_index=self._plot_index)
dialog.add_checkbox_group(
title='Plot Markers', options=marker_settings, selected_indexes=selected_checkboxes)
[plot_type, checkboxes] = dialog.get_settings()
if plot_type is not None and plot_type['selected_index'] is not None and self._plot_index != plot_type['selected_index']:
self._switch_data_plot_widget(plot_type['selected_index'], 0 in checkboxes['selected_indexes'])
if plot_type is not None and \
plot_type['selected_index'] is not None and \
self._plot_index != plot_type['selected_index']:
self._switch_data_plot_widget(
plot_type['selected_index'], 0 in checkboxes['selected_indexes'])
else:
if checkboxes is not None and self._markers_on != (0 in checkboxes['selected_indexes']):
self._switch_plot_markers(0 in checkboxes['selected_indexes'])
Expand Down Expand Up @@ -304,14 +322,14 @@ def _get_curve(self, curve_id):
return self._curves[curve_id]
else:
raise DataPlotException("No curve named %s in this DataPlot" %
( curve_id) )
(curve_id))

def add_curve(self, curve_id, curve_name, data_x, data_y):
"""Add a new, named curve to this plot
Add a curve named `curve_name` to the plot, with initial data series
`data_x` and `data_y`.
Future references to this curve should use the provided `curve_id`
Note that the plot is not redraw automatically; call `redraw()` to make
Expand All @@ -320,10 +338,10 @@ def add_curve(self, curve_id, curve_name, data_x, data_y):
curve_color = QColor(self._colors[self._color_index % len(self._colors)])
self._color_index += 1

self._curves[curve_id] = { 'x': numpy.array(data_x),
'y': numpy.array(data_y),
'name': curve_name,
'color': curve_color}
self._curves[curve_id] = {'x': numpy.array(data_x),
'y': numpy.array(data_y),
'name': curve_name,
'color': curve_color}
if self._data_plot_widget:
self._add_curve.emit(curve_id, curve_name, curve_color, self._markers_on)

Expand All @@ -337,7 +355,7 @@ def remove_curve(self, curve_id):

def update_values(self, curve_id, values_x, values_y, sort_data=True):
"""Append new data to an existing curve
`values_x` and `values_y` will be appended to the existing data for
`curve_id`
Expand Down Expand Up @@ -376,12 +394,11 @@ def clear_values(self, curve_id=None):
self._curves[curve_id]['x'] = numpy.array([])
self._curves[curve_id]['y'] = numpy.array([])


def vline(self, x, color=RED):
"""Draw a vertical line on the plot
Draw a line a position X, with the given color
@param x: position of the vertical line to draw
@param color: optional parameter specifying the color, as tuple of
RGB values from 0 to 255
Expand Down Expand Up @@ -436,7 +453,7 @@ def _merged_autoscale(self):

# reset the upper x_limit so that we ignore the previous position
x_limit[1] = -numpy.inf

# get largest X value
for curve_id in self._curves:
curve = self._curves[curve_id]
Expand All @@ -455,7 +472,6 @@ def _merged_autoscale(self):
if numpy.isinf(x_limit[1]):
x_limit[1] = 1.0


y_limit = [numpy.inf, -numpy.inf]
if self._autoscale_y:
# if we're extending the y limits, initialize them with the
Expand Down Expand Up @@ -486,14 +502,14 @@ def _merged_autoscale(self):
# ONLY consider data for new values; not
# existing limits, or we'll add padding on top of old
# padding in SCALE_EXTEND mode
#
#
# pad the min/max
# TODO: invert this padding in get_ylim
#ymin = limits[0]
#ymax = limits[1]
#delta = ymax - ymin if ymax != ymin else 0.1
#ymin -= .05 * delta
#ymax += .05 * delta
# ymin = limits[0]
# ymax = limits[1]
# delta = ymax - ymin if ymax != ymin else 0.1
# ymin -= .05 * delta
# ymax += .05 * delta
else:
y_limit = self.get_ylim()

Expand Down
10 changes: 7 additions & 3 deletions src/rqt_plot/data_plot/mat_data_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,11 @@ def parse_version(s):


class MatDataPlot(QWidget):

class Canvas(FigureCanvas):

"""Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""

def __init__(self, parent=None):
super(MatDataPlot.Canvas, self).__init__(Figure())
self.axes = self.figure.add_subplot(111)
Expand Down Expand Up @@ -133,7 +136,8 @@ def add_curve(self, curve_id, curve_name, curve_color=QColor(Qt.blue), markers_o
marker_size = 3
else:
marker_size = 0
line = self._canvas.axes.plot([], [], 'o-', markersize=marker_size, label=curve_name, linewidth=1, picker=5, color=curve_color.name())[0]
line = self._canvas.axes.plot([], [], 'o-', markersize=marker_size, label=curve_name,
linewidth=1, picker=5, color=curve_color.name())[0]
self._curves[curve_id] = line
self._update_legend()
self.set_xlim(x_limits)
Expand Down Expand Up @@ -162,8 +166,8 @@ def redraw(self):
self._canvas.draw()

def vline(self, x, color):
# convert color range from (0,255) to (0,1.0)
matcolor=(color[0]/255.0, color[1]/255.0, color[2]/255.0)
# convert color range from (0,255) to (0,1.0)
matcolor = (color[0] / 255.0, color[1] / 255.0, color[2] / 255.0)
if self._current_vline:
self._current_vline.remove()
self._current_vline = self._canvas.axes.axvline(x=x, color=matcolor)
Expand Down
10 changes: 6 additions & 4 deletions src/rqt_plot/data_plot/pyqtgraph_data_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ def parse_version(s):
from pyqtgraph import __version__ as pyqtgraph_version
except RuntimeError:
# pyqtgraph < 1.0 using Qt4 failing on 16.04 because kinetic uses Qt5.
# This raises RuntimeError('the PyQt4.QtCore and PyQt5.QtCore modules both wrap the QObject class')
# This raises RuntimeError('the PyQt4.QtCore and PyQt5.QtCore modules both
# wrap the QObject class')
import pkg_resources
pyqtgraph_version = pkg_resources.get_distribution("pyqtgraph").version

Expand Down Expand Up @@ -83,7 +84,8 @@ def add_curve(self, curve_id, curve_name, curve_color=QColor(Qt.blue), markers_o
symbolBrush = mkBrush(curve_color)
# this adds the item to the plot and legend
if markers_on:
plot = self._plot_widget.plot(name=curve_name, pen=pen, symbol=symbol, symbolPen=symbolPen, symbolBrush=symbolBrush, symbolSize=4)
plot = self._plot_widget.plot(name=curve_name, pen=pen, symbol=symbol,
symbolPen=symbolPen, symbolBrush=symbolBrush, symbolSize=4)
else:
plot = self._plot_widget.plot(name=curve_name, pen=pen)
self._curves[curve_id] = plot
Expand All @@ -94,7 +96,7 @@ def remove_curve(self, curve_id):
self._plot_widget.removeItem(self._curves[curve_id])
del self._curves[curve_id]
self._update_legend()

def _update_legend(self):
# clear and rebuild legend (there is no remove item method for the legend...)
self._plot_widget.clear()
Expand All @@ -103,7 +105,7 @@ def _update_legend(self):
self._plot_widget.addItem(curve)
if self._current_vline:
self._plot_widget.addItem(self._current_vline)

def redraw(self):
pass

Expand Down
26 changes: 15 additions & 11 deletions src/rqt_plot/data_plot/qwt_data_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def __init__(self, *args):

# Initialize data
self.rescale()
#self.move_canvas(0, 0)
# self.move_canvas(0, 0)
self.canvas().setMouseTracking(True)
self.canvas().installEventFilter(self)

Expand All @@ -102,9 +102,11 @@ def eventFilter(self, _, event):
y = self.invTransform(Qwt.QwtPlot.yLeft, event.pos().y())
coords = QPointF(x, y)
if self._picker.isActive() and self._last_click_coordinates is not None:
toolTip = 'origin x: %.5f, y: %.5f' % (self._last_click_coordinates.x(), self._last_click_coordinates.y())
toolTip = 'origin x: %.5f, y: %.5f' % (
self._last_click_coordinates.x(), self._last_click_coordinates.y())
delta = coords - self._last_click_coordinates
toolTip += '\ndelta x: %.5f, y: %.5f\nlength: %.5f' % (delta.x(), delta.y(), QVector2D(delta).length())
toolTip += '\ndelta x: %.5f, y: %.5f\nlength: %.5f' % (
delta.x(), delta.y(), QVector2D(delta).length())
else:
toolTip = 'buttons\nleft: measure\nmiddle: move\nright: zoom x/y\nwheel: zoom y'
self.setToolTip(toolTip)
Expand All @@ -127,7 +129,8 @@ def add_curve(self, curve_id, curve_name, curve_color=QColor(Qt.blue), markers_o
curve_object.attach(self)
curve_object.setPen(curve_color)
if markers_on:
curve_object.setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, QBrush(curve_color), QPen(Qt.black), QSize(4,4)))
curve_object.setSymbol(
Qwt.QwtSymbol(Qwt.QwtSymbol.Ellipse, QBrush(curve_color), QPen(Qt.black), QSize(4, 4)))
self._curves[curve_id] = curve_object

def remove_curve(self, curve_id):
Expand Down Expand Up @@ -156,7 +159,7 @@ def rescale(self):
self._x_limits[1])

self._canvas_display_height = self._y_limits[1] - self._y_limits[0]
self._canvas_display_width = self._x_limits[1] - self._x_limits[0]
self._canvas_display_width = self._x_limits[1] - self._x_limits[0]
self.redraw()

def rescale_axis_x(self, delta__x):
Expand All @@ -173,7 +176,7 @@ def scale_axis_y(self, max_value):
set the y axis height to max_value, about the current center
"""
canvas_display_height = max_value
canvas_offset_y = (self._y_limits[1] + self._y_limits[0])/2.0
canvas_offset_y = (self._y_limits[1] + self._y_limits[0]) / 2.0
y_lower_limit = canvas_offset_y - (canvas_display_height / 2)
y_upper_limit = canvas_offset_y + (canvas_display_height / 2)
self._y_limits = [y_lower_limit, y_upper_limit]
Expand All @@ -185,8 +188,8 @@ def move_canvas(self, delta_x, delta_y):
"""
canvas_offset_x = delta_x * self._canvas_display_width / self.canvas().width()
canvas_offset_y = delta_y * self._canvas_display_height / self.canvas().height()
self._x_limits = [ l + canvas_offset_x for l in self._x_limits]
self._y_limits = [ l + canvas_offset_y for l in self._y_limits]
self._x_limits = [l + canvas_offset_x for l in self._x_limits]
self._y_limits = [l + canvas_offset_y for l in self._y_limits]
self.rescale()

def mousePressEvent(self, event):
Expand All @@ -205,7 +208,8 @@ def mouseMoveEvent(self, event):
zoom_factor = max(-0.6, min(0.6, (self._last_canvas_y - canvas_y) / 20.0 / 2.0))
delta_y = (self.canvas().height() / 2.0) - self._pressed_canvas_y
self.move_canvas(0, zoom_factor * delta_y * 1.0225)
self.scale_axis_y(max(0.005, self._canvas_display_height - (zoom_factor * self._canvas_display_height)))
self.scale_axis_y(
max(0.005, self._canvas_display_height - (zoom_factor * self._canvas_display_height)))
self.rescale_axis_x(self._last_canvas_x - canvas_x)
self._last_canvas_x = canvas_x
self._last_canvas_y = canvas_y
Expand All @@ -222,10 +226,10 @@ def wheelEvent(self, event): # mouse wheel zooms the y-axis
delta_y = (self.canvas().height() / 2.0) - canvas_y
self.move_canvas(0, zoom_factor * delta_y * 1.0225)

self.scale_axis_y(max(0.0005, self._canvas_display_height - zoom_factor * self._canvas_display_height))
self.scale_axis_y(
max(0.0005, self._canvas_display_height - zoom_factor * self._canvas_display_height))
self.limits_changed.emit()


def vline(self, x, color):
qWarning("QwtDataPlot.vline is not implemented yet")

Expand Down
Loading

0 comments on commit 9665c96

Please sign in to comment.