Class ParaGraph
Object
UIObject
Widget
Panel
SimplePanel
FocusPanel
AbstractGraph<double[]>
ParaGraph
- All Implemented Interfaces:
DoubleClickHandler, HasAllDragAndDropHandlers, HasAllFocusHandlers, HasAllGestureHandlers, HasAllKeyHandlers, HasAllMouseHandlers, HasAllTouchHandlers, HasBlurHandlers, HasClickHandlers, HasContextMenuHandlers, HasDoubleClickHandlers, HasDragEndHandlers, HasDragEnterHandlers, HasDragHandlers, HasDragLeaveHandlers, HasDragOverHandlers, HasDragStartHandlers, HasDropHandlers, HasFocusHandlers, HasGestureChangeHandlers, HasGestureEndHandlers, HasGestureStartHandlers, HasKeyDownHandlers, HasKeyPressHandlers, HasKeyUpHandlers, HasMouseDownHandlers, HasMouseMoveHandlers, HasMouseOutHandlers, HasMouseOverHandlers, HasMouseUpHandlers, HasMouseWheelHandlers, HasTouchCancelHandlers, HasTouchEndHandlers, HasTouchMoveHandlers, HasTouchStartHandlers, MouseDownHandler, MouseMoveHandler, MouseOutHandler, MouseUpHandler, MouseWheelHandler, TouchEndHandler, TouchMoveHandler, TouchStartHandler, HasAttachHandlers, EventHandler, HasHandlers, EventListener, AcceptsOneWidget, Focusable, HasFocus, HasOneWidget, HasVisibility, HasWidgets, HasWidgets.ForIsWidget, IsWidget, RequiresResize, SourcesClickEvents, SourcesFocusEvents, SourcesKeyboardEvents, SourcesMouseEvents, SourcesMouseWheelEvents, Iterable<Widget>, AbstractGraph.HasTrajectory, AbstractGraph.Shifter, AbstractGraph.Shifting, AbstractGraph.Zoomer, AbstractGraph.Zooming, ContextMenu.Listener, ContextMenu.Provider, Tooltip.Provider
public class ParaGraph
extends AbstractGraph<double[]>
implements AbstractGraph.Zooming, AbstractGraph.Shifting, AbstractGraph.HasTrajectory, DoubleClickHandler
ParaGraph is a specialized 2D parametric/phase-plane graph component for
visualizing trajectories produced by a simulation module. Each data sample is
expected to be a
double[] whose first element is the time and the
remaining elements represent the state vector. ParaGraph maps those state
vectors into phase-plane coordinates via a HasPhase2D.Data2Phase mapper and
draws the resulting parametric curve onto a canvas.
Key responsibilities:
- Maintain a bounded history of parametric data points in a
RingBuffer<double[]>, where each stored array has the time prepended as the first element. - Coalesce incoming samples to conserve memory: samples are appended only when the estimated distance (in phase plane units) to the previous stored point exceeds a configurable threshold (derived from a minimum pixel spacing), unless explicitly forced.
- Handle special time values (NaN) and duplicate times: duplicate times replace the last sample; NaN times mark new trajectory segments and update the recorded initial state accordingly.
- Map simulation state <-> phase coordinates using a
HasPhase2D.Data2Phaseinstance. If the mapper implementsBasicTooltipProviderit will be used as the tooltip provider for parametric tooltips. - Render the trajectory with optional start/end markers and custom markers. The drawing code takes into account current axis ranges, scaling, translation and zooming.
- Provide interactive features:
- Double-click or single-touch on the phase plane to convert the clicked phase coordinates back into a simulation initial state and set it on the view.
- Context menu actions to clear the canvas and toggle autoscaling of axes.
- Tooltip support for coordinates via a configured tooltip provider.
- Autoscale axes to fit the visible data when enabled. Autoscaling computes min/max ranges from the mapper over the current buffer and rounds to sensible tick-friendly bounds. Percent scales are clamped to [0,1] when configured.
- Export trajectory data to a text format (time, x, y) using the configured
mapper and a
Formatterfor numeric formatting.
Rendering details:
- Painting is scheduled with
Scheduler.scheduleDeferred(Scheduler.ScheduledCommand)to avoid redundant immediate repaints; apaintScheduledflag prevents oversubscription of repaint requests. - Canvas transform sequence: global scale, translation for view corner and bounds, additional zoom factor, and Y-axis flip to map mathematical coordinates to canvas pixel coordinates.
- Line width is increased slightly when using semi-transparent trajectory colors to improve visibility.
Buffering and sampling:
bufferThresholdis computed incalcBoundsfromMIN_PIXELSand the current scale and axis ranges. It represents the squared minimal distance (in data units) required between successive stored samples and prevents storing points closer than a few screen pixels.- Initial trajectory starting point is stored in
initand updated whenever the buffer begins a new segment (empty buffer) or when a NaN time indicates a new starting point.
Usage notes:
- Call
setMap(Data2Phase)to provide a domain-specific mapping between model state and phase-plane coordinates. A defaultTraitMapis created lazily if none is set. - Use
addData(double, double[], boolean)to append samples from the simulation. The method clones and prepends the time to the provided array before storing it in the buffer. - Enable or disable autoscaling via the context menu or
autoscale().
- Author:
- Christoph Hauert
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from class AbstractGraph
AbstractGraph.HasLogScaleY, AbstractGraph.HasTrajectory, AbstractGraph.MyContext2d, AbstractGraph.Shifter, AbstractGraph.Shifting, AbstractGraph.ZoomCommand, AbstractGraph.Zoomer, AbstractGraph.ZoomingNested classes/interfaces inherited from class UIObject
UIObject.DebugIdImpl, UIObject.DebugIdImplEnabledNested classes/interfaces inherited from interface HasWidgets
HasWidgets.ForIsWidget -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate ContextMenuCheckBoxItemThe context menu item to autoscale the axes.private doubleThreshold for storing new data point in buffer.private ContextMenuItemThe context menu item to clear the canvas.(package private) booleanThe flag to indicate autoscaling of axes.(package private) double[]The starting point of the most recent trajectory.(package private) HasPhase2D.Data2PhaseThe map for converting data to phase plane coordinates.private static final doubleThe minimum distance between two subsequent points in pixels.private booleanThe flag to indicate whether painting is already scheduled.Fields inherited from class AbstractGraph
bounds, buffer, canvas, colors, contextMenu, CSS_CURSOR_MOVE_VIEW, CURSOR_GRAB_NODE_CLASS, CURSOR_MOVE_NODE_CLASS, CURSOR_ZOOM_IN_CLASS, CURSOR_ZOOM_OUT_CLASS, DEFAULT_BUFFER_SIZE, doubleClickHandler, element, g, hasMessage, hasZoom, leftMouseButton, logger, logYMenu, markerColors, markers, MIN_BUFFER_SIZE, MIN_MSEC_BETWEEN_UPDATES, module, mouseDownHandler, mouseMoveHandler, mouseOutHandler, mouseUpHandler, mouseWheelHandler, mouseX, mouseY, PIHALF, pinchDist, pinchX, pinchY, scale, shifter, style, tooltip, tooltipProvider, touchEndHandler, touchEndTime, touchMoveHandler, touchStartHandler, updatetime, view, viewCorner, wrapper, zoomer, zoomFactor, zoomInertiaTimer, zoomInMenu, zoomOutMenu, zoomResetMenuFields inherited from class UIObject
DEBUG_ID_PREFIXFields inherited from interface AbstractGraph.Zooming
ZOOM_INCR, ZOOM_MAX -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidactivate()Perform necessary preparations to show the graph in the GUI.voidaddData(double t, double[] data, boolean force) Add data to the graph.voidAutomatically adjust the range of both axes to fit the data in the buffer.voidcalcBounds(int width, int height) Calculate bounds of drawing area.private doubledistSq(double[] vec, double[] buf) Helper method to calculate the distance squared between two vectors.private voiddrawCustomMarkers(Point2D pt, double xScale, double yScale) Draw custom markers stored inAbstractGraph.markers.private voiddrawStartEndMarkers(Point2D aPt, double xScale, double yScale) Draw start and end markers for the trajectory.private voiddrawTrajectory(Point2D currPt, Point2D nextPt, double xScale, double yScale) Draw the trajectory stored in the buffer.voidExport the graphical contextctx.voidexportTrajectory(StringBuilder export) Export the trajectory of the graph toexport.getMap()Get the map for converting data to phase plane coordinates.getTooltipAt(int x, int y) Get the tooltip information for the location with coordinates(x, y).private voidhandleEmptyBuffer(double t, double[] data) Handle the case that the buffer is empty.private voidhandleNaNTime(double lastt, double t, double[] data, int len) Handle the case that the timetisNaN.private booleaninside(double x, double y) Check if point (in user coordinates but not yet scaled to axes) lies inside of phase plane.voidonDoubleClick(DoubleClickEvent event) protected voidonLoad()voidonTouchStart(TouchStartEvent event) booleanpaint(boolean force) Draw the graph.private voidpaintPara(boolean withMarkers) Paint the trajectory in the phase plane.voidpopulateContextMenuAt(ContextMenu menu, int x, int y) Populate context menumenuin listening widget at (relative) position(x,y).private voidprocessInitXY(double x, double y) Helper method to convert screen coordinates into an initial configuration and set the controller's initial state.protected voidSchedule painting of the graph.voidSet the map for converting data to phase plane coordinates.Methods inherited from class AbstractGraph
addContextMenuHandler, autoscale, calcBounds, clearCanvas, clearGraph, clearHistory, clearMessage, contains, convertToScaledCoordinates, convertToScaledCoordinates, deactivate, displayMessage, doUpdate, drawFrame, drawFrame, fill, fillCircle, fillCircle, fillCircle, fillRect, fillTextVertical, getBuffer, getModule, getStyle, hasHistory, hasMessage, init, onMouseDown, onMouseMove, onMouseOut, onMouseUp, onMouseWheel, onResize, onTouchEnd, onTouchMove, onUnload, paint, parse, prependTime2Data, reset, resetTransforms, setBufferCapacity, setColors, setFont, setLogY, setMarkers, setMarkers, setStrokeStyleAt, setTooltipProvider, shift, stroke, strokeCircle, strokeCircle, strokeCircle, strokeLine, strokeLine, strokeRect, zoom, zoom, zoom, zoomMethods inherited from class FocusPanel
addBlurHandler, addClickHandler, addClickListener, addDoubleClickHandler, addDragEndHandler, addDragEnterHandler, addDragHandler, addDragLeaveHandler, addDragOverHandler, addDragStartHandler, addDropHandler, addFocusHandler, addFocusListener, addGestureChangeHandler, addGestureEndHandler, addGestureStartHandler, addKeyboardListener, addKeyDownHandler, addKeyPressHandler, addKeyUpHandler, addMouseDownHandler, addMouseListener, addMouseMoveHandler, addMouseOutHandler, addMouseOverHandler, addMouseUpHandler, addMouseWheelHandler, addMouseWheelListener, addTouchCancelHandler, addTouchEndHandler, addTouchMoveHandler, addTouchStartHandler, getTabIndex, removeClickListener, removeFocusListener, removeKeyboardListener, removeMouseListener, removeMouseWheelListener, setAccessKey, setFocus, setTabIndexMethods inherited from class SimplePanel
add, getContainerElement, getWidget, iterator, remove, setWidget, setWidgetMethods inherited from class Panel
add, adopt, clear, doAttachChildren, doDetachChildren, orphan, removeMethods inherited from class Widget
addAttachHandler, addBitlessDomHandler, addDomHandler, addHandler, asWidget, asWidgetOrNull, createHandlerManager, delegateEvent, fireEvent, getHandlerCount, getLayoutData, getParent, isAttached, isOrWasAttached, onAttach, onBrowserEvent, onDetach, removeFromParent, setLayoutData, sinkEvents, unsinkEventsMethods inherited from class UIObject
addStyleDependentName, addStyleName, ensureDebugId, ensureDebugId, ensureDebugId, getAbsoluteLeft, getAbsoluteTop, getElement, getOffsetHeight, getOffsetWidth, getStyleElement, getStyleName, getStyleName, getStylePrimaryName, getStylePrimaryName, getTitle, isVisible, isVisible, onEnsureDebugId, removeStyleDependentName, removeStyleName, resolvePotentialElement, setElement, setElement, setHeight, setPixelSize, setSize, setStyleDependentName, setStyleName, setStyleName, setStyleName, setStyleName, setStylePrimaryName, setStylePrimaryName, setTitle, setVisible, setVisible, setWidth, sinkBitlessEvent, toStringMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface AbstractGraph.Shifter
shiftMethods inherited from interface AbstractGraph.Zoomer
zoomMethods inherited from interface AbstractGraph.Zooming
zoom, zoomMethods inherited from interface ContextMenu.Listener
getAbsoluteLeft, getAbsoluteTopMethods inherited from interface HasHandlers
fireEventMethods inherited from interface HasTouchCancelHandlers
addTouchCancelHandlerMethods inherited from interface HasTouchEndHandlers
addTouchEndHandlerMethods inherited from interface HasTouchMoveHandlers
addTouchMoveHandlerMethods inherited from interface HasTouchStartHandlers
addTouchStartHandlerMethods inherited from interface Iterable
forEach, spliteratorMethods inherited from interface MouseDownHandler
onMouseDownMethods inherited from interface MouseMoveHandler
onMouseMoveMethods inherited from interface MouseOutHandler
onMouseOutMethods inherited from interface MouseUpHandler
onMouseUpMethods inherited from interface MouseWheelHandler
onMouseWheelMethods inherited from interface TouchEndHandler
onTouchEndMethods inherited from interface TouchMoveHandler
onTouchMove
-
Field Details
-
init
double[] initThe starting point of the most recent trajectory. -
map
The map for converting data to phase plane coordinates. -
doAutoscale
boolean doAutoscaleThe flag to indicate autoscaling of axes. -
bufferThreshold
private double bufferThresholdThreshold for storing new data point in buffer. Roughly corresponds to the squared distance between two points that are at least a pixel apart. -
MIN_PIXELS
private static final double MIN_PIXELSThe minimum distance between two subsequent points in pixels.- See Also:
-
paintScheduled
private boolean paintScheduledThe flag to indicate whether painting is already scheduled. Subsequent requests are ignored. -
clearMenu
The context menu item to clear the canvas. -
autoscaleMenu
The context menu item to autoscale the axes.
-
-
Constructor Details
-
ParaGraph
-
-
Method Details
-
onLoad
protected void onLoad()- Overrides:
onLoadin classAbstractGraph<double[]>
-
activate
public void activate()Description copied from class:AbstractGraphPerform necessary preparations to show the graph in the GUI. Attaches mouse and touch handlers for graphs that implementAbstractGraph.ZoomingorAbstractGraph.Shiftinginterfaces.- Overrides:
activatein classAbstractGraph<double[]>- See Also:
-
setMap
Set the map for converting data to phase plane coordinates.- Parameters:
map- the conversion map
-
getMap
Get the map for converting data to phase plane coordinates.- Returns:
- the conversion map
-
addData
public void addData(double t, double[] data, boolean force) Add data to the graph. The timetis prepended to the data as the first element.- Parameters:
t- the time of the datadata- the data to addforce-trueto force adding the data- Implementation Notes:
- The data array is cloned and the time prepended before adding it to the buffer.
- In order to conserve memory the data is added only if the
distance between
the new data point and the last point in the buffer is larger
than threshold
bufferThreshold, unlessforce == true.
-
handleEmptyBuffer
private void handleEmptyBuffer(double t, double[] data) Handle the case that the buffer is empty. Add data to the buffer and set the initial state.- Parameters:
t- the time at which the data is recordeddata- the data to add
-
handleNaNTime
private void handleNaNTime(double lastt, double t, double[] data, int len) Handle the case that the timetisNaN. If the last time in the buffer is alsoNaNthe last data point is replaced by the new data, otherwise the new data is appended to the buffer. The initial state is updated accordingly.- Parameters:
lastt- the time of the last data point in the buffert- the time of the datadata- the data to addlen- the length of the data array (including time)
-
distSq
private double distSq(double[] vec, double[] buf) Helper method to calculate the distance squared between two vectors.- Parameters:
vec- the first vectorbuf- the second vector- Returns:
- the squared distance
-
paint
public boolean paint(boolean force) Description copied from class:AbstractGraphDraw the graph. For re-drawing the graph, setforcetotrue.- Overrides:
paintin classAbstractGraph<double[]>- Parameters:
force-trueto force re-drawing of graph- Returns:
trueif painting skipped
-
paintPara
private void paintPara(boolean withMarkers) Paint the trajectory in the phase plane. IfwithMarkersistruethe start and end points of the trajectory are marked with green and red circles, respectively.- Parameters:
withMarkers-trueto mark start and end points
-
drawTrajectory
-
drawStartEndMarkers
Draw start and end markers for the trajectory.- Parameters:
aPt- the storage for a pointxScale- the x-axis scaleyScale- the y-axis scale
-
drawCustomMarkers
Draw custom markers stored inAbstractGraph.markers.- Parameters:
pt- temporary storage for pointsxScale- the x-axis scaleyScale- the y-axis scale
-
calcBounds
public void calcBounds(int width, int height) Description copied from class:AbstractGraphCalculate bounds of drawing area.- Overrides:
calcBoundsin classAbstractGraph<double[]>- Parameters:
width- the width of the drawing areaheight- the height of the drawing area
-
autoscale
public void autoscale()Automatically adjust the range of both axes to fit the data in the buffer. -
schedulePaint
protected void schedulePaint()Schedule painting of the graph. If painting is already scheduled, subsequent requests are ignored.- See Also:
-
export
Description copied from class:AbstractGraphExport the graphical contextctx.- Specified by:
exportin classAbstractGraph<double[]>- Parameters:
ctx- the graphical context to export
-
onDoubleClick
- Specified by:
onDoubleClickin interfaceDoubleClickHandler
-
processInitXY
private void processInitXY(double x, double y) Helper method to convert screen coordinates into an initial configuration and set the controller's initial state.- Parameters:
x- thex-coordinate on screeny- they-coordinate on screen
-
onTouchStart
Description copied from class:AbstractGraphThe graph reacts to different kinds of touches: short touches or taps (
<250msec) and long touches (>250msec). Long touches trigger different actions depending on the number of fingers:- Single finger
- Initiate shifting the view
- Two fingers
- Initiate pinching zoom.
- Specified by:
onTouchStartin interfaceTouchStartHandler- Overrides:
onTouchStartin classAbstractGraph<double[]>- See Also:
-
getTooltipAt
Description copied from interface:Tooltip.ProviderGet the tooltip information for the location with coordinates(x, y). The returned string may include HTML elements for formatting.- Specified by:
getTooltipAtin interfaceTooltip.Provider- Parameters:
x- thex-coordinate for the tooltipy- they-coordinate for the tooltip- Returns:
- the (formatted) string with the tooltip info
-
inside
private boolean inside(double x, double y) Check if point (in user coordinates but not yet scaled to axes) lies inside of phase plane.- Parameters:
x-x-coordinate of pointy-y-coordinate of point- Returns:
trueif inside
-
populateContextMenuAt
Description copied from class:AbstractGraphPopulate context menumenuin listening widget at (relative) position(x,y).Adds buffer size menu and queries the view to add further functionality.
- Specified by:
populateContextMenuAtin interfaceContextMenu.Provider- Overrides:
populateContextMenuAtin classAbstractGraph<double[]>- Parameters:
menu- context menu entries are added herex- horizontal coordinate (relative to listening widget)y- horizontal coordinate (relative to listening widget)- See Also:
-
exportTrajectory
Description copied from interface:AbstractGraph.HasTrajectoryExport the trajectory of the graph toexport.- Specified by:
exportTrajectoryin interfaceAbstractGraph.HasTrajectory- Parameters:
export- the string builder to export the trajectory
-