Class PopGraph2D

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.Shifter, AbstractGraph.Shifting, AbstractGraph.Zoomer, AbstractGraph.Zooming, Network.LayoutListener, ContextMenu.Listener, ContextMenu.Provider, Tooltip.Provider
Direct Known Subclasses:
DistrGraph2D, PopGraph1D

public class PopGraph2D extends GenericPopGraph<String, Network2D> implements AbstractGraph.Shifting
The graphical representation of lattices and network structures in 2D. This class adapts a generic population graph view to a 2D canvas, supporting multiple geometry types (triangular, honeycomb, square variants, and generic network layouts) and providing custom drawing, hit-testing and user interaction behavior.

Responsibilities

  • Calculate layout bounds and element sizes for a variety of geometry types based on the current canvas size and configuration.
  • Render lattice cells or network nodes and links to a canvas using an internal graphics context.
  • Map input coordinates (mouse/touch) to node indices for selection and dragging, with geometry-specific hit-test logic.
  • Allow interactive shifting of individual network nodes (dragging) and shifting of lattice views.
  • Expose export capability to draw into an external MyContext2d context (e.g., for image export or printing).

Supported Geometry Types

  • TRIANGULAR — drawn as interleaved up/down triangles
  • HONEYCOMB — drawn as regular hexagons
  • SQUARE, SQUARE_MOORE, SQUARE_NEUMANN, SQUARE_NEUMANN_2ND — drawn as square grids with several decoration/neighbor variations; supports hierarchical gaps when geometry describes a HIERARCHY
  • Generic network — uses Node2D positions and a radius-based scaling to draw nodes and links; supports manual node shifting

Key Concepts & Fields

  • data: a String[] holding per-node CSS color values used to paint each cell/node.
  • Bounds and sizing: internal fields such as side, dw, dw2, dh, dh3 and dR compute per-cell/node sizes and are recalculated in calcBounds.
  • Hierarchy support: when geometry indicates a HIERARCHY, the component accounts for hierarchical gaps and levels (hLevels, hPeriods).
  • Interaction flags: hitNode tracks the currently selected node index, hitDragged indicates whether a node is currently being dragged.

Interaction & Events

  • Mouse Down: left-click resolves a node via findNodeAt and sets up dragging state and CSS cursor classes.
  • Mouse Move: when dragging a selected node, the node position is updated (network nodes) or the view is shifted (lattices). CSS classes are toggled during drag.
  • Mouse Up / Touch End: releases dragging state, restores classes, and can update tooltips as needed.

Rendering

The paint method orchestrates drawing:
  • When a static lattice layout is available it delegates to dedicated drawXxx methods (drawTriangular, drawHoneycomb, drawSquareLattice, drawSquareNeumann2nd).
  • For arbitrary networks the drawNetwork method scales the universe, draws links and nodes (with per-node color optimization) and supports node diameter computation (dR).
  • prepCanvas prepares the canvas transform (scale, translation and zoom) and manages a saved graphics state so drawing is isolated.

Sizing & Limits

  • MIN_DW, MIN_DH and MIN_DR define minimum drawable dimensions; if elements would be smaller than these thresholds, the graph is disabled and a message is displayed.

Performance

Drawing operations use batching and occasional optimizations (e.g., reusing fill style until it changes) but may still be expensive for very large populations or frequent updates.

Extensibility & Limitations

  • 3D geometries (CUBE) are not represented graphically in this class and will display an informational message.
  • Hit-testing for networks uses node bounding checks (Node2D.isHit) and returns the top-most node when overlaps occur.
  • Layouts flagged as LAYOUT_IN_PROGRESS are treated as invalid for hit-testing until the layout completes.

Styling

CSS classes used by the component:
  • .evoludo-PopGraph2D — primary graph element
  • .evoludo-Label2D — label element
  • .evoludo-cursorGrabNode — added while a node is grabbed
  • .evoludo-cursorMoveNode — added while a node is being dragged
Many rendering aspects (frame, linkColor, linkWidth, padding, decorated frame) are controlled by the associated style object.

Usage

Instantiate via the view/module infrastructure this project provides. Ensure to call activate() and allow AbstractGraph.calcBounds() to run with the appropriate canvas size; Tooltip.update() should be invoked whenever the underlying population state changes to refresh the visualization.
Author:
Christoph Hauert
  • Field Details

    • legend

      protected Legend2D legend
      Helper responsible for drawing and hit-testing the legend.
    • INFO_BINNING_TOO_FINE

      private static final String INFO_BINNING_TOO_FINE
      Message shown when the selected binning cannot be rendered in the available graph area.
      See Also:
    • INFO_POPSIZE_TOO_BIG

      private static final String INFO_POPSIZE_TOO_BIG
      Message shown when the selected binning cannot be rendered in the available graph area.
      See Also:
    • side

      int side
      The size of the graph for lattices.
    • dw

      int dw
      The width of a node for lattices.
    • dw2

      int dw2
      Convenience variable. One half of the width of a node for lattices, dw/2.
    • dh

      int dh
      The height of a node for lattices.
    • dh3

      int dh3
      Convenience variable. One third of the height of a node for lattices, dh/3.
    • dR

      double dR
      The diameter of nodes for networks.
    • MIN_DW

      static final int MIN_DW
      The minimum width of a node in pixels.
      See Also:
    • MIN_DH

      static final int MIN_DH
      The minimum height of a node in pixels.
      See Also:
    • MIN_DR

      static final double MIN_DR
      The minimum diameter of a node in pixels.
      See Also:
    • isHierarchy

      boolean isHierarchy
      Convenience variable. The flag indicating whether the backing geometry is a hierarchical structure.
    • hLevels

      int hLevels
      Convenience variable. The number of hierarchical levels.
    • hPeriods

      int[] hPeriods
      Convenience variable. The number of units in each hierarchical level.
    • HIERARCHY_GAP

      static final int HIERARCHY_GAP
      Convenience variable. The gap between subsequent units in hierarchical structures.
      See Also:
    • hitDragged

      protected boolean hitDragged
      The flag to indicate whether GenericPopGraph.hitNode is being dragged.
  • Constructor Details

    • PopGraph2D

      public PopGraph2D(AbstractView<?> view, Module<?> module)
      Create a graph for graphically visualizing the structure of a network (or population). Allocates the canvas and the label and retrieves the shared tooltip and context menu.

      CSS Style Rules

      .evoludo-PopGraph2D
      the graph element.
      .evoludo-Label2D
      the label element.
      Parameters:
      view - the view of this graph
      module - the module backing the graph
  • Method Details

    • onLoad

      protected void onLoad()
      Overrides:
      onLoad in class GenericPopGraph<String, Network2D>
    • onUnload

      protected void onUnload()
      Overrides:
      onUnload in class GenericPopGraph<String, Network2D>
    • setLegendSpecs

      public void setLegendSpecs(Legend2D.Specs specs)
      Assign semantic legend data prepared by the view.
      Parameters:
      specs - legend data
    • setGeometry

      public void setGeometry(AbstractGeometry geometry)
      Description copied from class: GenericPopGraph
      Set the geometry backing the graph.
      Overrides:
      setGeometry in class GenericPopGraph<String, Network2D>
      Parameters:
      geometry - the structure of the population
    • activate

      public void activate()
      Description copied from class: AbstractGraph
      Perform necessary preparations to show the graph in the GUI. Attaches mouse and touch handlers for graphs that implement AbstractGraph.Zooming or AbstractGraph.Shifting interfaces.
      Overrides:
      activate in class GenericPopGraph<String, Network2D>
      See Also:
    • addLegendPositionMenu

      private void addLegendPositionMenu(ContextMenu menu)
      Add submenu to select the legend position.
      Parameters:
      menu - the context menu to populate
    • addLegendPositionItem

      private void addLegendPositionItem(ContextMenu menu, String label, GraphStyle.Position position)
      Add radio item for selecting legend position.
      Parameters:
      menu - submenu to populate
      label - item label
      position - target legend position
    • addZoomMenu

      protected void addZoomMenu(ContextMenu menu)
      Description copied from class: AbstractGraph
      Add zoom menu items to context menu if graph supports zooming.
      Overrides:
      addZoomMenu in class AbstractGraph<String[]>
      Parameters:
      menu - the context menu to populate
    • onResize

      public void onResize()
      Specified by:
      onResize in interface RequiresResize
      Overrides:
      onResize in class GenericPopGraph<String, Network2D>
    • ensureData

      protected void ensureData()
      Ensure that the data array is properly initialized based on the current geometry. Temporary display constraints do not discard the backing colour data so the graph can immediately redraw when more space becomes available.
    • rebinGraphData

      public void rebinGraphData(int oldBins, int newBins)
      Rebin graph data when the number of bins changes.

      Default implementation does nothing. Subclasses can override to preserve rendered state/history across bin changes.

      Parameters:
      oldBins - previous number of bins per axis
      newBins - new number of bins per axis
    • paint

      public boolean paint(boolean force)
      Draw the graph. For re-drawing the graph, set force to true.

      Depending on the backing geometry this either

      1. shows a message, if no graphical representation is available, e.g. for 3D cubic lattices, or if there are too many nodes so that each node becomes too small to display on screen.
      2. shows lattice geometries.
      3. initiates the generic layouting process for arbitrary network structures.
      Overrides:
      paint in class AbstractGraph<String[]>
      Parameters:
      force - true to force re-drawing of graph
      Returns:
      true if painting skipped
      See Also:
    • drawLattice

      protected void drawLattice()
      Description copied from class: GenericPopGraph
      Draws structures with static layout of lattices.
      Specified by:
      drawLattice in class GenericPopGraph<String, Network2D>
      See Also:
    • drawTriangular

      private void drawTriangular()
      Draw triangular lattice.
    • drawHoneycomb

      private void drawHoneycomb()
      Draw honeycomb lattice.
    • drawSquareLattice

      private void drawSquareLattice()
      Draw square (hierarchical) lattice (SQUARE, SQUARE_MOORE, SQUARE_NEUMANN).
    • hierarchyGapAt

      private int hierarchyGapAt(int idx)
      Compute number of hierarchy gaps that occur before the given index. This encapsulates the previous inline loop that counted levels until the first non-divisor was encountered.
      Parameters:
      idx - the row or column index
      Returns:
      total gap in pixels to subtract/add for this index
    • drawSquareNeumann2nd

      private void drawSquareNeumann2nd()
      Draw the special SQUARE_NEUMANN_2ND lattice.
    • drawNetwork

      protected void drawNetwork()
      Description copied from class: GenericPopGraph
      Draws the network.
      Specified by:
      drawNetwork in class GenericPopGraph<String, Network2D>
    • drawFrameOverlay

      protected void drawFrameOverlay(boolean decoratedFrame)
      Draw frame and legend overlays without the content clip. Subclasses that keep content pan/zoom separate can reuse this after mapping viewport ranges.
      Parameters:
      decoratedFrame - true to draw the decorated frame
    • getTooltipAt

      public String getTooltipAt(int x, int y)
      Description copied from interface: Tooltip.Provider
      Get the tooltip information for the location with coordinates (x, y). The returned string may include HTML elements for formatting.
      Specified by:
      getTooltipAt in interface Tooltip.Provider
      Overrides:
      getTooltipAt in class GenericPopGraph<String, Network2D>
      Parameters:
      x - the x-coordinate for the tooltip
      y - the y-coordinate for the tooltip
      Returns:
      the (formatted) string with the tooltip info
    • prepCanvas

      private boolean prepCanvas()
      Helper method to get the canvas ready for drawing the graph.
      Returns:
      true if the canvas is ready for drawing
    • getMaxViewCornerX

      protected double getMaxViewCornerX(double zoom)
      Description copied from class: AbstractGraph
      Get the maximum horizontal view-corner offset for the zoom factor zoom.
      Overrides:
      getMaxViewCornerX in class AbstractGraph<String[]>
      Parameters:
      zoom - the zoom factor
      Returns:
      the maximum horizontal offset
    • getMaxViewCornerY

      protected double getMaxViewCornerY(double zoom)
      Description copied from class: AbstractGraph
      Get the maximum vertical view-corner offset for the zoom factor zoom.
      Overrides:
      getMaxViewCornerY in class AbstractGraph<String[]>
      Parameters:
      zoom - the zoom factor
      Returns:
      the maximum vertical offset
    • calcBounds

      public void calcBounds(int width, int height)
      Description copied from class: AbstractGraph
      Calculate bounds of drawing area.
      Overrides:
      calcBounds in class AbstractGraph<String[]>
      Parameters:
      width - the width of the drawing area
      height - the height of the drawing area
    • adjustBoundsForLegend

      protected void adjustBoundsForLegend()
      Adjust bounds to make room for legend.
      Overrides:
      adjustBoundsForLegend in class AbstractGraph<String[]>
    • handleNoRepresentation

      private void handleNoRepresentation(GeometryType type)
      Handle geometries without graphical representation.
      Parameters:
      type - the geometry type
    • handleTriangular

      private void handleTriangular(int width, int height)
      Handle triangular lattice geometry.
      Parameters:
      width - the width of the canvas
      height - the height of the canvas
    • handleHoneycomb

      private void handleHoneycomb(int width, int height)
      Handle honeycomb lattice geometry.
      Parameters:
      width - the width of the canvas
      height - the height of the canvas
    • handleSquare

      private void handleSquare(int width, int height)
      Handle square lattice geometry.
      Parameters:
      width - the width of the canvas
      height - the height of the canvas
    • handleNetwork

      private void handleNetwork(int width, int height)
      Handle generic network geometry.
      Parameters:
      width - the width of the canvas
      height - the height of the canvas
    • getCSSColorAt

      public String getCSSColorAt(int node)
      Get the color of the node at index node as a CSS color string.
      Specified by:
      getCSSColorAt in class GenericPopGraph<String, Network2D>
      Parameters:
      node - the index of the node
      Returns:
      the color of the node
    • findNodeAt

      public int findNodeAt(int x, int y)
      Find the index of the node at the location with coordinates (x, y).
      Specified by:
      findNodeAt in class GenericPopGraph<String, Network2D>
      Parameters:
      x - the x-coordinate of the location
      y - the y-coordinate of the location
      Returns:
      the index of the node
    • findTriangularNode

      private int findTriangularNode(int x, int y)
      Find the index of the node at the location with coordinates (x, y) in a triangular lattice.
      Parameters:
      x - the x-coordinate of the location
      y - the y-coordinate of the location
      Returns:
      the index of the node
    • findHoneycombNode

      private int findHoneycombNode(int x, int y)
      Find the index of the node at the location with coordinates (x, y) in a honeycomb lattice.
      Parameters:
      x - the x-coordinate of the location
      y - the y-coordinate of the location
      Returns:
      the index of the node
    • findSquareNode

      private int findSquareNode(int x, int y)
      Find the index of the node at the location with coordinates (x, y) in a (hierarchical) square lattice.
      Parameters:
      x - the x-coordinate of the location
      y - the y-coordinate of the location
      Returns:
      the index of the node
    • findNetworkNode

      private int findNetworkNode(int sx, int sy)
      Locate the node under the given screen coordinates for general network layouts.
      Parameters:
      sx - screen x-coordinate
      sy - screen y-coordinate
      Returns:
      node index or -1 if none hit
    • supportsNodeDragging

      protected boolean supportsNodeDragging()
      Check whether the current graph state supports dragging individual nodes. Only non-lattice network layouts with established node positions are draggable. Static lattice layouts should fall back to the inherited shifter instead.
      Returns:
      true if node dragging is available
    • onMouseDown

      public void onMouseDown(MouseDownEvent event)

      If a node has been hit by a left-click, remember the node's index and the current mouse coordinates. This information might be used by subsequent MouseMoveEvents.

      If a node has been hit by a left-click, remember the node's index and the current mouse coordinates. This information might be used by subsequent MouseMoveEvents.

      CSS Style Rules

      .evoludo-cursorGrabNode
      added to graph element.
      Specified by:
      onMouseDown in interface MouseDownHandler
      Overrides:
      onMouseDown in class AbstractGraph<String[]>
      See Also:
    • onMouseUp

      public void onMouseUp(MouseUpEvent event)

      Cancel all interactions with the graph and reset node and mouse information.

      CSS Style Rules

      .evoludo-cursorMoveView
      removed from graph element.
      .evoludo-cursorGrabNode
      removed from graph element.
      .evoludo-cursorMoveNode
      removed from graph element.
      Specified by:
      onMouseUp in interface MouseUpHandler
      Overrides:
      onMouseUp in class AbstractGraph<String[]>
      See Also:
    • onMouseMove

      public void onMouseMove(MouseMoveEvent event)

      If the left mouse-key is pressed the graph is shifted within its viewport. Note this requires that the zoom level of the graph exceeds 1.

      CSS Style Rules

      .evoludo-cursorMoveView
      added to graph element when shifting the view.

      If a node has been hit by a MouseDownEvent and is being dragged, the position of the node is shifted. This allows to customize the display of the graph.

      CSS Style Rules

      .evoludo-cursorMoveNode
      added to graph element when dragging a node.
      Specified by:
      onMouseMove in interface MouseMoveHandler
      Overrides:
      onMouseMove in class AbstractGraph<String[]>
      See Also:
    • onTouchEnd

      public void onTouchEnd(TouchEndEvent event)

      The number of touches on the graph changed.

      The number of touches on the graph changed.

      Specified by:
      onTouchEnd in interface TouchEndHandler
      Overrides:
      onTouchEnd in class AbstractGraph<String[]>
    • onTouchMove

      public void onTouchMove(TouchMoveEvent event)

      The graph reacts to different kinds of touch moves:

      Move one finger
      Shift view
      Pinch two fingers
      Zoom view
      move one finger on node
      shift node.
      Specified by:
      onTouchMove in interface TouchMoveHandler
      Overrides:
      onTouchMove in class AbstractGraph<String[]>
    • inside

      protected boolean inside(int x, int y)
      Description copied from class: AbstractGraph
      Check if the event coordinates are inside the interactive plot area. Default implementation accepts all coordinates.
      Overrides:
      inside in class AbstractGraph<String[]>
      Parameters:
      x - the x-coordinate relative to the graph element
      y - the y-coordinate relative to the graph element
      Returns:
      true if inside the interactive plot area
    • shiftNodeBy

      public void shiftNodeBy(int nodeidx, int dx, int dy)
      Shift a single node with index nodeidx by (dx, dy). Positive dx shift the node to the right and positive dy shift upwards.
      Parameters:
      nodeidx - the index of the node
      dx - the horizontal shift of the node
      dy - the vertical shift of the node
    • export

      public void export(AbstractGraph.MyContext2d ctx)
      Description copied from class: AbstractGraph
      Export the graphical context ctx.
      Specified by:
      export in class AbstractGraph<String[]>
      Parameters:
      ctx - the graphical context to export