コード例 #1
0
  public void mouseClicked(MouseEvent e) {

    if (!(e.getSource().getClass().getName()).equalsIgnoreCase("VisualItem")
        && !UILib.isButtonPressed(e, button1)) {
      if (gv.getDisplay().getCursor().getType() == (Cursor.DEFAULT_CURSOR)) {
        // release all focus and neighbour highlight
        TupleSet ts = vis.getGroup(Visualization.FOCUS_ITEMS);
        if (gv.getRecStatus() == 2 && gv.fromIndirect && (ts.getTupleCount() == 0) && !gv.fromAll)
          gv.showDirectGraph();

        ts.clear();
        vis.removeGroup("depthEdge");
        gv.releaseSearchFocus();
      }
    }

    if (UILib.isButtonPressed(e, button1) && e.getClickCount() == 1) {
      if (gv.getDisplay().getCursor().getName().equals("zoom")) admin.toggleZoom();
      else if (gv.getDisplay().getCursor().getName().equals("zoomout")) admin.toggleZoomOut();
      else if (gv.getDisplay().getCursor().getName().equals("zoomin")) admin.toggleZoomIn();
      else if (gv.getDisplay().getCursor().getName().equals("zoomout1")) admin.toggleZoomOut1();
      else if (gv.getDisplay().getCursor().getName().equals("zoomin1")) admin.toggleZoomIn1();
      else if (gv.getDisplay().getCursor().getName().equals("pan")) admin.togglePan();
    }
  }
コード例 #2
0
  /*
   * Test method for 'prefuse.Visualization.getSourceData(String)'
   */
  @Test
  public void testGetSourceData() {
    Assert.assertEquals(m_t, m_vis.getSourceData("t"));
    Assert.assertEquals(m_t, m_vt0.getSourceData());

    Assert.assertEquals(m_g, m_vis.getSourceData("g"));
    Assert.assertEquals(m_g.getNodeTable(), m_vis.getSourceData("g.nodes"));
    Assert.assertEquals(m_g.getEdgeTable(), m_vis.getSourceData("g.edges"));
    Assert.assertEquals(m_g.getNodeTable(), m_vn0.getSourceData());
  }
コード例 #3
0
  public JPanel demo(Graph g, final String label) {
    // create a new radial tree view
    final PhysioMapRadialGraphView gview =
        new PhysioMapRadialGraphView(settings, g, label, semsimmodel);
    Visualization vis = gview.getVisualization();

    // create a search panel for the tree map
    SearchQueryBinding sq =
        new SearchQueryBinding(
            (Table) vis.getGroup(treeNodes),
            label,
            (SearchTupleSet) vis.getGroup(Visualization.SEARCH_ITEMS));
    JSearchPanel search = sq.createSearchPanel();
    search.setShowResultCount(true);
    search.setBorder(BorderFactory.createEmptyBorder(5, 5, 4, 0));
    search.setFont(FontLib.getFont("Verdana", Font.PLAIN, 11));

    final JTextArea title = new JTextArea();
    title.setPreferredSize(new Dimension(450, 500));
    title.setMaximumSize(new Dimension(450, 500));
    title.setMinimumSize(new Dimension(450, 500));

    title.setAlignmentY(CENTER_ALIGNMENT);
    title.setLineWrap(true);
    title.setWrapStyleWord(true);
    title.setBorder(BorderFactory.createEmptyBorder(3, 0, 0, 0));
    title.setFont(FontLib.getFont("Verdana", Font.PLAIN, 11));

    gview.addControlListener(
        new ControlAdapter() {
          public void itemEntered(VisualItem item, MouseEvent e) {}

          public void itemExited(VisualItem item, MouseEvent e) {
            title.setText(null);
          }
        });

    Box searchbox = new Box(BoxLayout.X_AXIS);
    searchbox.add(Box.createHorizontalStrut(10));
    searchbox.add(search);
    searchbox.add(Box.createHorizontalStrut(3));

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(searchbox, BorderLayout.NORTH);
    panel.add(gview, BorderLayout.CENTER);
    panel.add(Box.createGlue(), BorderLayout.SOUTH);

    Color BACKGROUND = Color.WHITE;
    Color FOREGROUND = Color.DARK_GRAY;
    UILib.setColor(panel, BACKGROUND, FOREGROUND);

    return panel;
  }
コード例 #4
0
    public void itemReleased(VisualItem item, MouseEvent e) {
      if (!SwingUtilities.isLeftMouseButton(e)) return;
      if (dragged) {
        activeItem = null;
        item.setFixed(wasFixed);
        dragged = false;
      }
      // clear the focus
      Visualization vis = item.getVisualization();
      vis.getFocusGroup(Visualization.FOCUS_ITEMS).clear();

      vis.cancel("forces");
    }
コード例 #5
0
  /** @see prefuse.visual.VisualItem#validateBounds() */
  public Rectangle2D validateBounds() {
    if (isValidated()) return getBounds();

    Visualization v = getVisualization();

    // set the new bounds from the renderer and validate
    getRenderer().setBounds(this);
    setValidated(true);

    // report damage from the new bounds and return
    Rectangle2D bounds = getBounds();
    v.damageReport(this, bounds);
    return bounds;
  }
コード例 #6
0
    public void itemPressed(VisualItem item, MouseEvent e) {
      if (!SwingUtilities.isLeftMouseButton(e)) return;

      // set the focus to the current node
      Visualization vis = item.getVisualization();
      vis.getFocusGroup(Visualization.FOCUS_ITEMS).setTuple(item);

      item.setFixed(true);
      dragged = false;
      Display d = (Display) e.getComponent();
      down = d.getAbsoluteCoordinate(e.getPoint(), down);

      vis.run("forces");
    }
コード例 #7
0
 @Override
 public void itemPressed(VisualItem item, MouseEvent e) {
   // on right-mouse press, start dragging the document
   if (SwingUtilities.isRightMouseButton(e)) {
     // debug
     System.out.println("debug: " + this.getClass().getName() + ": item pressed w/ right mouse");
     // drag, set the focus to the current node
     Visualization vis = item.getVisualization();
     vis.getFocusGroup(Visualization.FOCUS_ITEMS).setTuple(item);
     item.setFixed(true);
     dragged = false;
     Display d = controller.getDocumentGrid();
     down = d.getAbsoluteCoordinate(e.getPoint(), down);
   }
 }
コード例 #8
0
  public void displayLayout() {
    Insets i = m_display.getInsets();
    int w = m_display.getWidth();
    int h = m_display.getHeight();
    int iw = i.left + i.right;
    int ih = i.top + i.bottom;
    int aw = 85;
    int ah = 15;

    m_dataB.setRect(i.left, i.top, w - iw - aw, h - ih - ah);
    m_xlabB.setRect(i.left, h - ah - i.bottom, w - iw - aw, ah - 10);
    m_ylabB.setRect(i.left, i.top, w - iw, h - ih - ah);

    m_vis.run("update");
    m_vis.run("xlabels");
  }
コード例 #9
0
 /*
  * Test method for 'prefuse.Visualization.getSourceTuple(VisualItem)'
  */
 @Test
 public void testGetSourceTuple() {
   Assert.assertEquals(m_t0, m_vis.getSourceTuple(m_vt0));
   Assert.assertEquals(m_n0, m_vis.getSourceTuple(m_vn0));
   Assert.assertEquals(m_t0, m_vt0.getSourceTuple());
   Assert.assertEquals(m_n0, m_vn0.getSourceTuple());
 }
コード例 #10
0
  /**
   * updates the focus group to the step if a sequence is being collapsed or to the start node of
   * the sequence if the sequence is being expanded
   *
   * @param id
   */
  public void updateFocusGroup(int nodeId, Visualization vis) {
    Iterator visualItems = vis.items();
    VisualItem item = null;
    final String group = Visualization.FOCUS_ITEMS;

    while (visualItems.hasNext()) {
      item = (VisualItem) visualItems.next();
      if (item instanceof TableNodeItem && item.getInt(ID) == nodeId) {
        TupleSet ts = vis.getFocusGroup(group);
        ts.setTuple(item);
        break;
      }
    }

    vis.run("animate");
  }
コード例 #11
0
 @Test
 public void testRepeatGroup() {
   Table t = new Table();
   Graph g = new Graph();
   try {
     m_vis.add("t", t);
     Assert.fail("Should not allow duplicate groups");
   } catch (Exception e) {
   }
   try {
     m_vis.addFocusGroup(Visualization.FOCUS_ITEMS, t);
     Assert.fail("Should not allow duplicate groups");
   } catch (Exception e) {
   }
   try {
     m_vis.add("g", g);
     Assert.fail("Should not allow duplicate groups");
   } catch (Exception e) {
   }
   m_vis.removeGroup("t");
   try {
     m_vis.add("t", t);
   } catch (Exception e) {
     Assert.fail("Should be able to re-use group name after removal");
   }
   m_vis.removeGroup("g");
   try {
     m_vis.add("g", t);
   } catch (Exception e) {
     Assert.fail("Should be able to re-use group name after removal");
   }
 }
コード例 #12
0
  @Before
  public void setUp() {
    m_vis = new Visualization();
    m_t = TableTest.getTestCaseTable();
    m_g = GraphTest.getTestCaseGraph();

    m_t0 = m_t.getTuple(0);
    m_n0 = m_g.getNode(0);

    VisualTable vt = (VisualTable) m_vis.add("t", m_t);
    VisualGraph vg = (VisualGraph) m_vis.add("g", m_g);

    m_vt0 = vt.getItem(0);
    m_vn0 = (NodeItem) vg.getNode(0);

    TupleSet ts = m_vis.getFocusGroup(Visualization.FOCUS_ITEMS);
    ts.addTuple(m_vt0);
    ts.addTuple(m_vn0);
  }
コード例 #13
0
 public MultipleFocusControl(
     Visualization v, String activity, String filterGroup, boolean focusFixed) {
   super(1, activity);
   this.v = v;
   this.focusedTupleSet = v.getFocusGroup(group);
   this.focusFixed = focusFixed;
   if (focusFixed) {
     focusedTupleSet.addTupleSetListener(DOFIX);
   }
   setFilter(new InGroupPredicate(filterGroup));
 }
コード例 #14
0
  @Override
  public void itemClicked(VisualItem item, MouseEvent e) {

    Visualization vis = item.getVisualization();
    DDGDisplay d = (DDGDisplay) vis.getDisplay(0);

    // revalidates the display by finding the item with the same position as
    // the mouse pointer
    if (revalidated) {
      String state = collapseExpand(item);
      if (state.equals(START)) {
        updateFocusGroup(stepId, item.getVisualization());
        vis.run("color");
        vis.run("repaint");
      }
      if (state.equals(STEP)) {
        expandOneLevel(item);
        updateFocusGroup(startId, item.getVisualization());
        vis.run("color");
        vis.run("repaint");
      }
      revalidated = false;
    } else {
      revalidated = true;
      VisualItem myItem = d.findItem(e.getPoint());
      itemClicked(myItem, e);
    }
  }
コード例 #15
0
  /**
   * collapses nodes between a start node and a finish node when the start node is clicked expand
   * nodes between a start and finish node when the step connecting them is clicked
   *
   * @param item
   */
  public String collapseExpand(VisualItem item) {

    if (item instanceof TableNodeItem && item.getString(TYPE).equals(START)) {

      TableNodeItem nodeItem = (TableNodeItem) item;

      if (finishNode(nodeItem) != null && getChild(finishNode(nodeItem)) != null) {

        setNodesAndEdgesInvisible(nodeItem, finishNode(nodeItem));
        setStepVisible(nodeItem);
        setIsolatedNodesInvisible(nodeItem.getGraph());

        Visualization vis = item.getVisualization();
        vis.run("layout");
      }

      return START;
    }

    if (item instanceof TableNodeItem && item.getString(TYPE).equals(STEP)) {

      TableNodeItem nodeItem = (TableNodeItem) item;
      TableNodeItem startNode = getStepParent(nodeItem);
      startId = (getChild(startNode)).getInt(ID);
      TableNodeItem finishNode = getStepChild(nodeItem);

      setStepInvisible(nodeItem);
      setNodesAndEdgesVisible(startNode, finishNode, true);
      setIsolatedNodesVisible(nodeItem.getGraph());

      Visualization vis = item.getVisualization();
      vis.run("layout");

      return STEP;
    }

    return "Other";
  }
コード例 #16
0
  /**
   * expands one level at a time when step node is clicked
   *
   * @param item
   */
  public void expandOneLevel(VisualItem item) {

    Visualization vis = item.getVisualization();
    TableNodeItem stepItem = (TableNodeItem) item;
    TableNodeItem stepParent = getStepParent(stepItem);
    TableNodeItem stepChild = getStepChild(stepItem);

    int finishNodeId = 0;
    Iterator visualItems = vis.visibleItems();
    VisualItem node;

    while (visualItems.hasNext()) {
      node = (VisualItem) visualItems.next();
      if (node instanceof TableNodeItem
          && node.getInt(ID) > (stepParent.getInt(ID) + 1)
          && node.getInt(ID) < stepChild.getInt(ID)
          && node.getString(TYPE).equals(START)
          && node.getInt(ID) > finishNodeId) {
        collapseExpand(node);
        finishNodeId = finishNode((TableNodeItem) node).getInt(ID);
      }
    }
  }
コード例 #17
0
 /*
  * Test method for 'prefuse.Visualization.removeGroup(String)'
  */
 @Test
 public void testRemoveGroup() {
   m_vis.removeGroup("g");
   Assert.assertEquals(null, m_vis.getGroup("g"));
   Assert.assertEquals(null, m_vis.getGroup("g.nodes"));
   Assert.assertEquals(null, m_vis.getGroup("g.edges"));
   Assert.assertEquals(null, m_vis.getSourceData("g"));
   Assert.assertEquals(null, m_vis.getSourceData("g.nodes"));
   Assert.assertEquals(null, m_vis.getSourceData("g.edges"));
   Assert.assertEquals(false, m_vis.getFocusGroup("_focus_").containsTuple(m_n0));
 }
コード例 #18
0
ファイル: Viz.java プロジェクト: arjunguha/dabble
  public static void main(String[] argv) {

    // -- 1. load the data ------------------------------------------------

    // load the socialnet.xml file. it is assumed that the file can be
    // found at the root of the java classpath
    Graph graph = null;
    try {
      graph = new GraphMLReader().readGraph(System.in);
    } catch (DataIOException e) {
      e.printStackTrace();
      System.err.println("Error loading graph. Exiting...");
      System.exit(1);
    }

    // -- 2. the visualization --------------------------------------------

    // add the graph to the visualization as the data group "graph"
    // nodes and edges are accessible as "graph.nodes" and "graph.edges"
    Visualization vis = new Visualization();
    vis.add("graph", graph);
    vis.setInteractive("graph.edges", null, false);

    // -- 3. the renderers and renderer factory ---------------------------

    // draw the "name" label for NodeItems
    LabelRenderer r = new LabelRenderer("label");
    r.setRoundedCorner(8, 8); // round the corners

    EdgeRenderer eRender =
        new EdgeRenderer(Constants.EDGE_TYPE_CURVE, Constants.EDGE_ARROW_FORWARD);

    // create a new default renderer factory
    // return our name label renderer as the default for all non-EdgeItems
    // includes straight line edges for EdgeItems by default
    vis.setRendererFactory(new DefaultRendererFactory(r, eRender));

    // -- 4. the processing actions ---------------------------------------

    // create our nominal color palette
    // pink for females, baby blue for males
    int[] palette =
        new int[] {
          ColorLib.rgb(190, 190, 255), ColorLib.rgb(255, 180, 180), ColorLib.rgb(128, 128, 128),
        };
    // map nominal data values to colors using our provided palette
    DataColorAction fill =
        new DataColorAction(
            "graph.nodes", "type", Constants.NOMINAL, VisualItem.FILLCOLOR, palette);

    // use black for node text
    ColorAction text = new ColorAction("graph.nodes", VisualItem.TEXTCOLOR, ColorLib.gray(0));
    // use light grey for edges
    ColorAction edges = new ColorAction("graph.edges", VisualItem.STROKECOLOR, ColorLib.gray(200));
    ColorAction arrows = new ColorAction("graph.edges", VisualItem.FILLCOLOR, ColorLib.gray(200));

    // create an action list containing all color assignments
    ActionList color = new ActionList();
    color.add(fill);
    color.add(text);
    color.add(edges);
    color.add(arrows);

    // Add a size action
    DataSizeAction size = new DataSizeAction("graph.nodes", "type", 2, Constants.LINEAR_SCALE);
    vis.putAction("size", size);

    // create an action list with an animated layout
    ActionList layout = new ActionList(Activity.INFINITY);
    layout.add(new ForceDirectedLayout("graph"));
    layout.add(new RepaintAction());

    // add the actions to the visualization
    vis.putAction("color", color);
    vis.putAction("layout", layout);

    // -- 5. the display and interactive controls -------------------------

    Display d = new Display(vis);
    d.setSize(720, 500); // set display size
    // drag individual items around
    d.addControlListener(new DragControl());
    // pan with left-click drag on background
    d.addControlListener(new PanControl());
    // zoom with right-click drag
    d.addControlListener(new ZoomControl());

    // -- 6. launch the visualization -------------------------------------

    // create a new window to hold the visualization
    JFrame frame = new JFrame("IFDS Visualization");
    // ensure application exits when window is closed
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(d);
    frame.pack(); // layout components in window
    frame.setVisible(true); // show the window

    // assign the colors
    vis.run("color");
    // start up the animated layout
    vis.run("layout");
  }
コード例 #19
0
  public Display getGraphDisplay(
      GraphLayoutType glType, final ExperimentPanel expPanel, String highlightName) {
    Display display = new Display();
    int X = expPanel.getDetailWidth();
    int Y = expPanel.getDetailHeight();
    display.setSize(X, Y); // set display size
    // display.setHighQuality(true);
    // display.setPreferredSize(new Dimension(600,600));
    display.addControlListener(new DragControl()); // drag items around
    display.addControlListener(new PanControl()); // pan with background left-drag
    display.addControlListener(new WheelZoomControl()); // zoom with vertical right-drag
    display.addControlListener(
        new ZoomToFitControl(Visualization.ALL_ITEMS, 50, 500, Control.MIDDLE_MOUSE_BUTTON));
    display.addControlListener(new NeighborHighlightControl());

    Visualization vis = new Visualization();
    if (clusterGraph == null) {
      clusterGraph = this.toGraph();
    }
    vis.add("graph", clusterGraph);
    LabelRenderer r = new LabelRenderer("name");
    r.setHorizontalAlignment(Constants.CENTER);
    // r.setRoundedCorner(8, 8); // round the corners

    DefaultRendererFactory rf = new DefaultRendererFactory(r);
    rf.setDefaultEdgeRenderer(new EdgeRenderer(Constants.EDGE_TYPE_CURVE));
    vis.setRendererFactory(rf);
    int[] palette = new int[] {ColorLib.rgb(255, 180, 180), ColorLib.rgb(190, 190, 255)};
    DataColorAction fill =
        new DataColorAction(
            "graph.nodes", "type", Constants.NOMINAL, VisualItem.FILLCOLOR, palette);
    fill.add(VisualItem.FIXED, ColorLib.rgb(255, 100, 100));
    fill.add(VisualItem.HIGHLIGHT, ColorLib.rgb(255, 200, 125));
    int[] text_palette = new int[] {ColorLib.gray(0), ColorLib.gray(255)};
    DataColorAction text =
        new DataColorAction(
            "graph.nodes",
            "indeterminate",
            Constants.NUMERICAL,
            VisualItem.TEXTCOLOR,
            text_palette);
    // ColorAction text = new ColorAction("graph.nodes", VisualItem.TEXTCOLOR, ColorLib.gray(0));
    ColorAction edges = new ColorAction("graph.edges", VisualItem.STROKECOLOR, ColorLib.gray(200));

    ActionList color = new ActionList(Activity.INFINITY);
    color.add(text);
    color.add(fill);
    color.add(edges);
    color.add(new RepaintAction());

    if (highlightName != null) {
      String pred = "name='" + highlightName + "'";
      Iterator iter = vis.items("graph.nodes", ExpressionParser.predicate(pred));
      while (iter.hasNext()) {
        NodeItem ni = (NodeItem) iter.next();
        highlightedItem = ni;
        ni.setFixed(true);
        Iterator iterEdge = ni.edges();
        while (iterEdge.hasNext()) {
          EdgeItem eItem = (EdgeItem) iterEdge.next();
          NodeItem nItem = eItem.getAdjacentItem(ni);
          if (eItem.isVisible()) {
            eItem.setHighlighted(true);
            nItem.setHighlighted(true);
          }
        }
      }
    }

    ActionList layout = new ActionList();
    switch (glType) {
      case BALLOON_TREE:
        layout.add(new BalloonTreeLayout("graph"));
        break;
      case FORCE_DIRECTED:
        layout = new ActionList(Activity.INFINITY);
        layout.add(new ForceDirectedLayout("graph"));
        break;
      case NODE_LINK_TREE:
        layout.add(new NodeLinkTreeLayout("graph"));
        break;
      case RADIAL_TREE:
        layout.add(new RadialTreeLayout("graph"));
        break;
    }
    // layout.add(fill);
    layout.add(new RepaintAction());

    vis.putAction("color", color);
    vis.putAction("layout", layout);
    display.setVisualization(vis);
    vis.run("color");
    vis.run("layout");
    // Rectangle2D bounds = vis.getBounds(Visualization.ALL_ITEMS);
    // GraphicsLib.expand(bounds, 50 + (int)(1/display.getScale()));
    // DisplayLib.fitViewToBounds(display,bounds,1);
    // vis.runAfter("layout",1000);

    Control shutoffHighlight =
        new HoverActionControl("color") {
          // public void itemEntered(VisualItem item, MouseEvent evt) {
          // }
          public void itemExited(VisualItem item, MouseEvent evt) {
            if (highlightedItem != null) {
              highlightedItem.setFixed(false);
              Iterator iterEdge = highlightedItem.edges();
              while (iterEdge.hasNext()) {
                EdgeItem eItem = (EdgeItem) iterEdge.next();
                NodeItem nItem = eItem.getAdjacentItem(highlightedItem);
                if (eItem.isVisible()) {
                  eItem.setHighlighted(false);
                  nItem.setHighlighted(false);
                }
              }
              highlightedItem = null;
            }
          }
        };
    display.addControlListener(shutoffHighlight);

    Control selectItem =
        new FocusControl() {

          public void itemClicked(VisualItem item, MouseEvent evt) {
            if (item.isInGroup("graph.nodes")) {
              if (item.getString("type").equals("peptide")) {
                Peptide pep = minPeptides.get(item.getString("name"));
                expPanel.showPeptide(pep, true);
              }
              if (item.getString("type").equals("protein")) {
                Protein pro = minProteins.get(item.getString("name"));
                expPanel.showProtein(pro, true);
              }
              String pred = "name='" + item.getString("name") + "'";
              Iterator iter =
                  item.getVisualization().items("graph.nodes", ExpressionParser.predicate(pred));
              while (iter.hasNext()) {
                NodeItem ni = (NodeItem) iter.next();
                highlightedItem = ni;
                ni.setFixed(true);
                Iterator iterEdge = ni.edges();
                while (iterEdge.hasNext()) {
                  EdgeItem eItem = (EdgeItem) iterEdge.next();
                  NodeItem nItem = eItem.getAdjacentItem(ni);
                  if (eItem.isVisible()) {
                    eItem.setHighlighted(true);
                    nItem.setHighlighted(true);
                  }
                }
              }
            }
          }
        };
    display.addControlListener(selectItem);

    final JPopupMenu menu = new JPopupMenu();

    // Create and add a menu item
    // JMenuItem printItem = new JMenuItem("Print This");
    // printItem.addActionListener(new java.awt.event.ActionListener() {

    //    public void actionPerformed(java.awt.event.ActionEvent evt) {
    //        PrintUtilities.printComponent(display);
    //    }
    // });
    // menu.add(printItem);

    // Set the component to show the popup menu
    display.addMouseListener(
        new MouseAdapter() {

          public void mousePressed(MouseEvent evt) {
            if (evt.isPopupTrigger()) {
              menu.show(evt.getComponent(), evt.getX(), evt.getY());
            }
          }

          public void mouseReleased(MouseEvent evt) {
            if (evt.isPopupTrigger()) {
              menu.show(evt.getComponent(), evt.getX(), evt.getY());
            }
          }
        });
    display.pan(X / 2.0, Y / 2.0);
    return display;
  }
コード例 #20
0
  /*
   * Test method for 'prefuse.Visualization.reset()'
   */
  @Test
  public void testReset() {
    m_vis.reset();

    Assert.assertEquals(null, m_vis.getGroup("t"));
    Assert.assertEquals(null, m_vis.getSourceData("t"));

    Assert.assertEquals(null, m_vis.getGroup("g"));
    Assert.assertEquals(null, m_vis.getGroup("g.nodes"));
    Assert.assertEquals(null, m_vis.getGroup("g.edges"));
    Assert.assertEquals(null, m_vis.getSourceData("g"));
    Assert.assertEquals(null, m_vis.getSourceData("g.nodes"));
    Assert.assertEquals(null, m_vis.getSourceData("g.edges"));

    Assert.assertEquals(0, m_vis.size("t"));
    Assert.assertEquals(0, m_vis.size("g"));
    Assert.assertEquals(0, m_vis.size("g.nodes"));
    Assert.assertEquals(0, m_vis.size("g.edges"));
    Assert.assertEquals(0, m_vis.getFocusGroup("_focus_").getTupleCount());
    Assert.assertEquals(false, m_vis.items().hasNext());
  }
コード例 #21
0
 /*
  * Test method for 'prefuse.Visualization.getVisualItem(String,Tuple)'
  */
 @Test
 public void testGetVisualItem() {
   Assert.assertEquals(m_vt0, m_vis.getVisualItem("t", m_t0));
   Assert.assertEquals(m_vn0, m_vis.getVisualItem("g", m_n0));
   Assert.assertEquals(m_vn0, m_vis.getVisualItem("g.nodes", m_n0));
 }
コード例 #22
0
  public Congress(Table t) {
    super(new BorderLayout());

    // --------------------------------------------------------------------
    // STEP 1: setup the visualized data

    final Visualization vis = new Visualization();
    m_vis = vis;

    final String group = "by_state";

    // filter to show only candidates receiving more than $100,000
    Predicate p = (Predicate) ExpressionParser.parse("[" + TOTAL_RECEIPTS + "] >= 100000");
    VisualTable vt = vis.addTable(group, t, p);

    // add a new column containing a label string showing
    // candidate name, party, state, year, and total receipts
    vt.addColumn(
        "label",
        "CONCAT(CAP(Candidate), ' (', "
            + "CAP([Party Designation]), '-', [State Code], "
            + "') ', Year, ': $', FORMAT([Total Receipts],2))");

    // add calculation for senators
    vt.addColumn("Senate", "District <= 0");

    vis.setRendererFactory(
        new RendererFactory() {
          AbstractShapeRenderer sr = new ShapeRenderer();
          Renderer arY = new AxisRenderer(Constants.RIGHT, Constants.TOP);
          Renderer arX = new AxisRenderer(Constants.CENTER, Constants.FAR_BOTTOM);

          public Renderer getRenderer(VisualItem item) {
            return item.isInGroup("ylab") ? arY : item.isInGroup("xlab") ? arX : sr;
          }
        });

    // --------------------------------------------------------------------
    // STEP 2: create actions to process the visual data

    // set up dynamic queries, search set
    RangeQueryBinding receiptsQ = new RangeQueryBinding(vt, RECEIPTS);
    ListQueryBinding yearsQ = new ListQueryBinding(vt, "Year");
    SearchQueryBinding searchQ = new SearchQueryBinding(vt, "Candidate");

    // construct the filtering predicate
    AndPredicate filter = new AndPredicate(searchQ.getPredicate());
    filter.add(yearsQ.getPredicate());
    filter.add(receiptsQ.getPredicate());

    // set up the actions
    AxisLayout xaxis = new AxisLayout(group, "State Code", Constants.X_AXIS, VisiblePredicate.TRUE);
    AxisLayout yaxis = new AxisLayout(group, RECEIPTS, Constants.Y_AXIS, VisiblePredicate.TRUE);
    // yaxis.setScale(Constants.LOG_SCALE);
    yaxis.setRangeModel(receiptsQ.getModel());
    receiptsQ.getNumberModel().setValueRange(0, 65000000, 0, 65000000);

    xaxis.setLayoutBounds(m_dataB);
    yaxis.setLayoutBounds(m_dataB);

    AxisLabelLayout ylabels = new AxisLabelLayout("ylab", yaxis, m_ylabB);
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    nf.setMaximumFractionDigits(0);
    ylabels.setNumberFormat(nf);

    AxisLabelLayout xlabels = new AxisLabelLayout("xlab", xaxis, m_xlabB, 15);
    vis.putAction("xlabels", xlabels);

    // dems = blue, reps = red, other = gray
    int[] palette =
        new int[] {
          ColorLib.rgb(150, 150, 255), ColorLib.rgb(255, 150, 150), ColorLib.rgb(180, 180, 180)
        };
    DataColorAction color =
        new DataColorAction(group, "Party", Constants.ORDINAL, VisualItem.STROKECOLOR, palette);

    int[] shapes = new int[] {Constants.SHAPE_RECTANGLE, Constants.SHAPE_DIAMOND};
    DataShapeAction shape = new DataShapeAction(group, "Senate", shapes);

    Counter cntr = new Counter(group);

    ActionList draw = new ActionList();
    draw.add(cntr);
    draw.add(color);
    draw.add(shape);
    draw.add(xaxis);
    draw.add(yaxis);
    draw.add(ylabels);
    draw.add(new ColorAction(group, VisualItem.FILLCOLOR, 0));
    draw.add(new RepaintAction());
    vis.putAction("draw", draw);

    ActionList update = new ActionList();
    update.add(new VisibilityFilter(group, filter));
    update.add(cntr);
    update.add(xaxis);
    update.add(yaxis);
    update.add(ylabels);
    update.add(new RepaintAction());
    vis.putAction("update", update);

    UpdateListener lstnr =
        new UpdateListener() {
          public void update(Object src) {
            vis.run("update");
          }
        };
    filter.addExpressionListener(lstnr);

    // --------------------------------------------------------------------
    // STEP 4: set up a display and ui components to show the visualization

    m_display = new Display(vis);
    m_display.setItemSorter(
        new ItemSorter() {
          public int score(VisualItem item) {
            int score = super.score(item);
            if (item.isInGroup(group)) score += item.getInt(TOTAL_RECEIPTS);
            return score;
          }
        });
    m_display.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    m_display.setSize(700, 450);
    m_display.setHighQuality(true);
    m_display.addComponentListener(
        new ComponentAdapter() {
          public void componentResized(ComponentEvent e) {
            displayLayout();
          }
        });
    displayLayout();

    m_details = new JFastLabel(m_title);
    m_details.setPreferredSize(new Dimension(75, 20));
    m_details.setVerticalAlignment(SwingConstants.BOTTOM);

    m_total.setPreferredSize(new Dimension(500, 20));
    m_total.setHorizontalAlignment(SwingConstants.RIGHT);
    m_total.setVerticalAlignment(SwingConstants.BOTTOM);

    ToolTipControl ttc = new ToolTipControl("label");
    Control hoverc =
        new ControlAdapter() {
          public void itemEntered(VisualItem item, MouseEvent evt) {
            if (item.isInGroup(group)) {
              m_total.setText(item.getString("label"));
              item.setFillColor(item.getStrokeColor());
              item.setStrokeColor(ColorLib.rgb(0, 0, 0));
              item.getVisualization().repaint();
            }
          }

          public void itemExited(VisualItem item, MouseEvent evt) {
            if (item.isInGroup(group)) {
              m_total.setText(m_totalStr);
              item.setFillColor(item.getEndFillColor());
              item.setStrokeColor(item.getEndStrokeColor());
              item.getVisualization().repaint();
            }
          }
        };
    m_display.addControlListener(ttc);
    m_display.addControlListener(hoverc);

    // --------------------------------------------------------------------
    // STEP 5: launching the visualization

    this.addComponentListener(lstnr);

    // details
    Box infoBox = new Box(BoxLayout.X_AXIS);
    infoBox.add(Box.createHorizontalStrut(5));
    infoBox.add(m_details);
    infoBox.add(Box.createHorizontalGlue());
    infoBox.add(Box.createHorizontalStrut(5));
    infoBox.add(m_total);
    infoBox.add(Box.createHorizontalStrut(5));

    // set up search box
    JSearchPanel searcher = searchQ.createSearchPanel();
    searcher.setLabelText("Candidate: ");
    searcher.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0));

    // create dynamic queries
    Box radioBox = new Box(BoxLayout.X_AXIS);
    radioBox.add(Box.createHorizontalStrut(5));
    radioBox.add(searcher);
    radioBox.add(Box.createHorizontalGlue());
    radioBox.add(Box.createHorizontalStrut(5));
    radioBox.add(yearsQ.createRadioGroup());
    radioBox.add(Box.createHorizontalStrut(16));

    JRangeSlider slider = receiptsQ.createVerticalRangeSlider();
    slider.setThumbColor(null);
    slider.setMinExtent(150000);
    slider.addMouseListener(
        new MouseAdapter() {
          public void mousePressed(MouseEvent e) {
            m_display.setHighQuality(false);
          }

          public void mouseReleased(MouseEvent e) {
            m_display.setHighQuality(true);
            m_display.repaint();
          }
        });

    vis.run("draw");
    vis.run("xlabels");

    add(infoBox, BorderLayout.NORTH);
    add(m_display, BorderLayout.CENTER);
    add(slider, BorderLayout.EAST);
    add(radioBox, BorderLayout.SOUTH);
    UILib.setColor(this, ColorLib.getColor(255, 255, 255), Color.GRAY);
    slider.setForeground(Color.LIGHT_GRAY);
    UILib.setFont(radioBox, FontLib.getFont("Tahoma", 15));
    m_details.setFont(FontLib.getFont("Tahoma", 18));
    m_total.setFont(FontLib.getFont("Tahoma", 16));
  }
コード例 #23
0
    @Override
    public void itemReleased(VisualItem item, MouseEvent e) {
      // when right-mouse released, release the dragged document glyph
      if (!SwingUtilities.isRightMouseButton(e)) {
        return;
      }
      // debug
      System.out.println("debug: " + this.getClass().getName() + ": item released");
      if (dragged) {
        activeItem = null;
        item.setFixed(wasFixed);
        dragged = false;
      }
      // clear the focus
      Visualization vis = item.getVisualization();
      vis.getFocusGroup(Visualization.FOCUS_ITEMS).clear();

      // determine whether item is in same region or new region;
      //  if new region, call controller to update attr vals
      double x = item.getX();
      double y = item.getY();
      double w = item.getDouble(WIDTH);
      double h = item.getDouble(HEIGHT);
      int newRegionX = -1;
      int newRegionY = -1;
      String xAttrName = docGridLayout.getXAttr();
      String yAttrName = docGridLayout.getYAttr();
      List<String> xCats = docGridLayout.getXCats();
      List<String> yCats = docGridLayout.getYCats();
      List<Integer> xCatRegionSizes = docGridLayout.getXCatRegionSizes();
      List<Integer> yCatRegionSizes = docGridLayout.getYCatRegionSizes();
      List<Integer> xCatPositions = docGridLayout.getXCatPositions();
      List<Integer> yCatPositions = docGridLayout.getYCatPositions();
      // for each region, get start and range;
      for (int i = 0; i < xCats.size(); i++) {
        int xRegionStart = xCatPositions.get(i);
        int xRegionEnd = xRegionStart + xCatRegionSizes.get(i);
        if (xRegionStart < x + (w / 2.) && x + (w / 2.) < xRegionEnd) {
          newRegionX = i;
        }
      }
      for (int i = 0; i < yCats.size(); i++) {
        int yRegionStart = yCatPositions.get(i);
        int yRegionEnd = yRegionStart + yCatRegionSizes.get(i);
        if (yRegionStart < y + (h / 2.) && y + (h / 2.) < yRegionEnd) {
          newRegionY = i;
        }
      }

      int docID = item.getInt(DocumentGridTable.NODE_ID);

      // debug
      //            System.out.println("debug: item moved:
      // docID="+docID+"xOrig="+xCats.get(origRegionX)+", xNew="+xCats.get(newRegionX)+",
      // yOrig="+yCats.get(origRegionY)+", yNew="+yCats.get(newRegionY));

      // update for x and y separately
      //            if (origRegionX != newRegionX && newRegionX != -1) {
      String newCatX = xCats.get(newRegionX);
      controller.updateDocumentAttr(docID, xAttrName, newCatX);
      controller.documentAttributesUpdated(docID);
      //            }
      //            if (origRegionY != newRegionY && newRegionY != -1) {
      String newCatY = yCats.get(newRegionY);
      controller.updateDocumentAttr(docID, yAttrName, newCatY);
      controller.documentAttributesUpdated(docID);
      //            }

    }
コード例 #24
0
  public static JComponent demo(Graph g, String label) {

    // create a new, empty visualization for our data
    final Visualization vis = new Visualization();
    VisualGraph vg = vis.addGraph(graph, g);
    vis.setValue(edges, null, VisualItem.INTERACTIVE, Boolean.FALSE);
    int[] palette =
        new int[] {
          ColorLib.rgb(77, 175, 74),
          ColorLib.rgb(55, 126, 184),
          ColorLib.rgb(228, 26, 28),
          ColorLib.rgb(152, 78, 163),
          ColorLib.rgb(255, 127, 0)
        };

    int[] shape_palette =
        new int[] {Constants.SHAPE_ELLIPSE, Constants.SHAPE_RECTANGLE, Constants.SHAPE_TRIANGLE_UP};

    TupleSet focusGroup = vis.getGroup(Visualization.FOCUS_ITEMS);
    focusGroup.addTupleSetListener(
        new TupleSetListener() {
          public void tupleSetChanged(TupleSet ts, Tuple[] add, Tuple[] rem) {
            for (int i = 0; i < rem.length; ++i) ((VisualItem) rem[i]).setFixed(false);
            for (int i = 0; i < add.length; ++i) {
              ((VisualItem) add[i]).setFixed(false);
              ((VisualItem) add[i]).setFixed(true);
            }
            vis.run("draw");
          }
        });

    // set up the renderers

    /*      ShapeRenderer s = new ShapeRenderer();
    s.rectangle(0, 0, 30, 30);
    vis.setRendererFactory(new DefaultRendererFactory(s));*/

    MyRenderer tr = new MyRenderer(label);
    // MyRenderer tr = new MyRenderer(label);
    DefaultRendererFactory d = new DefaultRendererFactory(tr);

    EdgeRenderer MyEdgeRenderer = new EdgeRenderer();
    d.add(new InGroupPredicate(edges), MyEdgeRenderer);
    vis.setRendererFactory(d);

    // -- set up the actions ----------------------------------------------

    int maxhops = 1024, hops = 1024;
    final GraphDistanceFilter filter = new GraphDistanceFilter(graph, hops);

    ActionList draw = new ActionList();
    draw.add(filter);

    // draw.add(new ColorAction(nodes, VisualItem.FILLCOLOR, ColorLib.rgb(180,180,255)));
    draw.add(new ColorAction(nodes, VisualItem.STROKECOLOR, 0));
    draw.add(new ColorAction(nodes, VisualItem.TEXTCOLOR, ColorLib.rgb(0, 0, 0)));
    draw.add(new ColorAction(edges, VisualItem.FILLCOLOR, ColorLib.gray(100)));
    draw.add(new ColorAction(edges, VisualItem.STROKECOLOR, ColorLib.gray(170)));
    draw.add(new DataShapeAction(nodes, "type", shape_palette));

    DataColorAction fill =
        new DataColorAction(
            "graph.nodes", "type", Constants.NOMINAL, VisualItem.FILLCOLOR, palette);
    // use black for node text
    ColorAction text = new ColorAction("graph.nodes", VisualItem.TEXTCOLOR, ColorLib.gray(0));
    // use light grey for edges
    ColorAction edges = new ColorAction("graph.edges", VisualItem.STROKECOLOR, ColorLib.gray(200));

    // create an action list containing all color assignments
    ActionList color = new ActionList();
    color.add(fill);
    color.add(text);
    color.add(edges);

    //        ColorAction fill = new ColorAction(nodes,
    //                VisualItem.FILLCOLOR, ColorLib.rgb(200,200,255));
    fill.add("_fixed", ColorLib.rgb(255, 100, 100));
    fill.add("_highlight", ColorLib.rgb(255, 200, 125));

    // Instead have to use  GridLayout here - how do i create
    ForceDirectedLayout fdl = new ForceDirectedLayout(graph);
    // GridLayout fdl = new GridLayout(graph);
    ForceSimulator fsim = fdl.getForceSimulator();
    fsim.getForces()[0].setParameter(0, -5f);

    ActionList animate = new ActionList(Activity.INFINITY);
    // ActionList animate = new ActionList(vis);

    animate.add(fdl);
    animate.add(fill);
    animate.add(new RepaintAction());

    // finally, we register our ActionList with the Visualization.
    // we can later execute our Actions by invoking a method on our
    // Visualization, using the name we've chosen below.
    vis.putAction("draw", draw);
    vis.putAction("layout", animate);
    vis.runAfter("draw", "layout");
    vis.putAction("color", color);
    // vis.putAction("layout", layout);

    // --------------------------------------------------------------------
    // STEP 4: set up a display to show the visualization

    Display display = new Display(vis);
    display.setSize(2000, 2000);
    display.setForeground(Color.GRAY);
    display.setBackground(Color.WHITE);

    // main display controls
    display.addControlListener(new FocusControl(1));
    display.addControlListener(new DragControl());
    display.addControlListener(new PanControl());
    display.addControlListener(new ZoomControl());
    display.addControlListener(new WheelZoomControl());
    display.addControlListener(new ZoomToFitControl());
    display.addControlListener(new NeighborHighlightControl());

    display.setForeground(Color.GRAY);
    display.setBackground(Color.WHITE);

    // --------------------------------------------------------------------
    // STEP 5: launching the visualization

    // create a panel for editing force values
    final JForcePanel fpanel = new JForcePanel(fsim);

    final JValueSlider slider = new JValueSlider("Distance", 0, maxhops, hops);
    slider.addChangeListener(
        new ChangeListener() {
          public void stateChanged(ChangeEvent e) {
            filter.setDistance(slider.getValue().intValue());
            vis.run("draw");
          }
        });
    slider.setBackground(Color.WHITE);
    slider.setPreferredSize(new Dimension(300, 30));
    slider.setMaximumSize(new Dimension(300, 30));

    Box cf = new Box(BoxLayout.Y_AXIS);
    cf.add(slider);
    cf.setBorder(BorderFactory.createTitledBorder("Connectivity Filter"));
    fpanel.add(cf);

    fpanel.add(Box.createVerticalGlue());

    // create a new JSplitPane to present the interface
    JSplitPane split = new JSplitPane();
    split.setLeftComponent(display);
    split.setRightComponent(fpanel);
    split.setOneTouchExpandable(true);
    split.setContinuousLayout(false);
    split.setDividerLocation(530);
    split.setDividerLocation(800);

    // position and fix the default focus node
    NodeItem focus = (NodeItem) vg.getNode(0);
    PrefuseLib.setX(focus, null, 400);
    PrefuseLib.setY(focus, null, 250);
    focusGroup.setTuple(focus);

    // now we run our action list and return
    return split;
  }
コード例 #25
0
ファイル: MPtrack.java プロジェクト: palas94/CSP--ASSGN2
  public MPtrack(Table t) {
    super(new BorderLayout());

    // --------------------------------------------------------------------
    // STEP 1: setup the visualized data

    final Visualization vis = new Visualization();
    m_vis = vis;

    final String group = "by_state";

    VisualTable vt = vis.addTable(group, t);

    vis.setRendererFactory(
        new RendererFactory() {
          AbstractShapeRenderer sr = new ShapeRenderer(30);
          Renderer arY = new AxisRenderer(Constants.RIGHT, Constants.TOP);
          Renderer arX = new AxisRenderer(Constants.CENTER, Constants.FAR_BOTTOM);

          public Renderer getRenderer(VisualItem item) {
            return item.isInGroup("ylab") ? arY : item.isInGroup("xlab") ? arX : sr;
          }
        });

    // --------------------------------------------------------------------

    // set up the actions
    AxisLayout xaxis = new AxisLayout(group, "States", Constants.X_AXIS, VisiblePredicate.TRUE);
    AxisLayout yaxis = new AxisLayout(group, PARTY, Constants.Y_AXIS, VisiblePredicate.TRUE);
    // yaxis.setScale(Constants.LOG_SCALE);

    xaxis.setLayoutBounds(m_dataB);
    yaxis.setLayoutBounds(m_dataB);

    AxisLabelLayout ylabels = new AxisLabelLayout("ylab", yaxis, m_ylabB, 5);

    AxisLabelLayout xlabels = new AxisLabelLayout("xlab", xaxis, m_xlabB, 5);
    vis.putAction("xlabels", xlabels);

    int[] palette = new int[] {ColorLib.rgb(150, 150, 255)};

    int[] palette2 = new int[200];

    for (int i = 0; i < 200; i++) {
      palette2[i] = ColorLib.rgba(255, 0, 0, 2 * i);
    }

    /*
    DataColorAction color = new DataColorAction(group, "Party",
            Constants.ORDINAL, VisualItem.STROKECOLOR, palette);
            */

    DataColorAction color2 =
        new DataColorAction(group, "Attendance", Constants.ORDINAL, VisualItem.FILLCOLOR, palette2);

    ActionList draw = new ActionList();
    draw.add(color2);
    draw.add(xaxis);
    draw.add(yaxis);
    draw.add(ylabels);
    draw.add(new RepaintAction());
    vis.putAction("draw", draw);

    ActionList update = new ActionList();
    update.add(xaxis);
    update.add(yaxis);
    update.add(ylabels);
    update.add(new RepaintAction());
    vis.putAction("update", update);

    UpdateListener lstnr =
        new UpdateListener() {
          public void update(Object src) {
            vis.run("update");
          }
        };

    // --------------------------------------------------------------------
    // STEP 4: set up a display and ui components to show the visualization

    m_display = new Display(vis);

    m_display.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    m_display.setSize(700, 450);
    m_display.setHighQuality(true);
    m_display.addComponentListener(
        new ComponentAdapter() {
          public void componentResized(ComponentEvent e) {
            displayLayout();
          }
        });
    displayLayout();

    m_details = new JFastLabel(m_title);
    m_details.setPreferredSize(new Dimension(75, 20));
    m_details.setVerticalAlignment(SwingConstants.BOTTOM);

    ToolTipControl ttc = new ToolTipControl("label");
    Control hoverc =
        new ControlAdapter() {
          public void itemEntered(VisualItem item, MouseEvent evt) {
            if (item.isInGroup(group)) {
              item.setFillColor(item.getStrokeColor());
              item.setStrokeColor(ColorLib.rgb(0, 0, 0));
              item.getVisualization().repaint();
            }
          }

          public void itemExited(VisualItem item, MouseEvent evt) {
            if (item.isInGroup(group)) {
              item.setFillColor(item.getEndFillColor());
              item.setStrokeColor(item.getEndStrokeColor());
              item.getVisualization().repaint();
            }
          }
        };
    m_display.addControlListener(ttc);
    m_display.addControlListener(hoverc);

    // --------------------------------------------------------------------
    // STEP 5: launching the visualization

    this.addComponentListener(lstnr);

    // details
    Box infoBox = new Box(BoxLayout.X_AXIS);
    infoBox.add(Box.createHorizontalStrut(5));
    infoBox.add(m_details);
    infoBox.add(Box.createHorizontalGlue());
    infoBox.add(Box.createHorizontalStrut(5));
    infoBox.add(Box.createHorizontalStrut(5));

    // create dynamic queries
    Box radioBox = new Box(BoxLayout.X_AXIS);
    radioBox.add(Box.createHorizontalStrut(5));
    radioBox.add(Box.createHorizontalGlue());
    radioBox.add(Box.createHorizontalStrut(5));
    radioBox.add(Box.createHorizontalStrut(16));

    vis.run("draw");
    vis.run("xlabels");

    add(infoBox, BorderLayout.NORTH);
    add(m_display, BorderLayout.CENTER);
    add(radioBox, BorderLayout.SOUTH);
    UILib.setColor(this, ColorLib.getColor(255, 255, 255), Color.GRAY);
    UILib.setFont(radioBox, FontLib.getFont("Tahoma", 15));
    m_details.setFont(FontLib.getFont("Tahoma", 18));
  }
コード例 #26
0
  /* (non-Javadoc)
   * @see org.lukep.javavis.visualisation.views.AbstractVisualisationView#visit(org.lukep.javavis.visualisation.visualisers.PrefuseVisualiser, org.lukep.javavis.ui.swing.WorkspaceContext, prefuse.Display)
   */
  @Override
  public void visit(PrefuseVisualiser visualiser, WorkspaceContext wspContext, Display display) {

    display.reset();

    // -- 1. load the data ------------------------------------------------

    Graph graph = new Graph();
    graph.addColumn("type", String.class);
    graph.addColumn("name", String.class);
    graph.addColumn("model", IGenericModelNode.class);
    graph.addColumn("metricMeasurement", double.class);

    // create package vertices
    ProjectModel modelStore = wspContext.getModelStore();
    HashMap<IGenericModelNode, Node> parentNodeMap =
        new HashMap<IGenericModelNode, Node>(modelStore.getPackageMap().size() + 10);
    Node curNode;

    for (PackageModel pkg : modelStore.getPackageMap().values()) {

      // add the package node
      curNode = graph.addNode();
      curNode.setString("type", pkg.getModelTypeName());
      curNode.setString("name", pkg.getSimpleName());
      curNode.set("model", pkg);

      // link to the parent with an edge
      IGenericModelNode parentPackage = pkg.getParent();
      if (parentPackage != null
          && parentPackage instanceof PackageModel
          && parentNodeMap.containsKey(parentPackage)) {

        // link to the parent package with an edge
        graph.addEdge(parentNodeMap.get(parentPackage), curNode);
      }

      parentNodeMap.put(pkg, curNode);
    }

    // create class and method nodes
    Queue<IGenericModelNode> modelQueue =
        new LinkedList<IGenericModelNode>(modelStore.getClassMap().values());
    IGenericModelNode model;

    while (modelQueue.peek() != null) {
      model = modelQueue.remove();

      curNode = graph.addNode();
      curNode.setString("type", model.getModelTypeName());
      curNode.setString("name", model.getSimpleName());
      curNode.set("model", model);

      // add children to iterModels
      if (model.getChildCount() > 0) {
        for (Relationship r : model.getChildren())
          if (r.getRelationshipType() == RelationshipType.ENCLOSED_IN)
            modelQueue.add(r.getTarget());
        parentNodeMap.put(model, curNode);
      }

      // link to the parent package
      if (parentNodeMap.containsKey(model.getParent())) {
        graph.addEdge(parentNodeMap.get(model.getParent()), curNode);
      }

      // grab metric measurement if applicable
      if (model instanceof IMeasurableNode
          && wspContext.getMetric().testAppliesTo(model.getModelTypeName())) {
        curNode.setDouble(
            "metricMeasurement",
            ((IMeasurableNode) (model)).getMetricMeasurement(wspContext.getMetric()).getResult());
      }
    }

    // -- 2. the visualisation --------------------------------------------

    // TODO implement a Visualization cache
    Visualization vis = new Visualization();
    vis.add("graph", graph);
    vis.setInteractive("graph.edges", null, false);

    // -- 3. the renderers and renderer factory ---------------------------

    LabelRenderer r = new LabelRenderer("name");
    r.setRoundedCorner(8, 8);

    vis.setRendererFactory(new DefaultRendererFactory(r));

    // -- 4. the processing actions ---------------------------------------

    // create our nominal color palette
    // pink for classes, baby blue for packages
    int[] palette = ColorLib.getCoolPalette();
    // create a metric palette
    int[] mPalette = ColorLib.getInterpolatedPalette(0xFF00AA6D, 0xFFFFAA6D);

    // TODO replace
    int[] mPalette2 = new int[mPalette.length + 1];
    mPalette2[0] = Color.lightGray.getRGB();
    for (int i = 1; i < mPalette.length; i++) mPalette2[i] = mPalette[i];

    // map nominal data values to colors using our provided palette
    DataColorAction fill =
        new DataColorAction(
            "graph.nodes", "type", Constants.NOMINAL, VisualItem.FILLCOLOR, palette);
    DataColorAction fillMetrics =
        new DataColorAction(
            "graph.nodes",
            "metricMeasurement",
            Constants.NUMERICAL,
            VisualItem.FILLCOLOR,
            mPalette2);
    // use black for node text
    ColorAction text = new ColorAction("graph.nodes", VisualItem.TEXTCOLOR, ColorLib.gray(0));
    // use light grey for edges
    ColorAction edges = new ColorAction("graph.edges", VisualItem.STROKECOLOR, ColorLib.gray(200));

    // create an action list containing all color assignments
    ActionList colour = new ActionList();
    colour.add(fillMetrics);
    colour.add(text);
    colour.add(edges);

    // create an action list with an animated layout
    ActionList layout = new ActionList(Activity.INFINITY);
    // layout.add(new ForceDirectedLayout("graph"));
    layout.add(new NodeLinkTreeLayout("graph"));
    layout.add(new RepaintAction());

    // add the actions to the visualisation
    vis.putAction("colour", colour);
    vis.putAction("layout", layout);

    // -- 5. the display and interactive controls -------------------------

    display.setVisualization(vis);

    // -- 6. launch the visualization -------------------------------------

    vis.run("colour");
    vis.run("layout");
  }
コード例 #27
0
 private void runActivity(Visualization vis) {
   if (activity != null) {
     vis.run(activity);
   }
 }
コード例 #28
0
ファイル: TabularDataVis.java プロジェクト: csp301team/trial
  /*
   * Constructor for the class
   * This is where all the important stuff happens
   */
  public TabularDataVis(Table t) {
    super(new BorderLayout());

    /*
     * Step 1: Setup the Visualization
     */

    // create a new visualization object, and assign it to the global variable
    final Visualization vis = new Visualization();
    g_vis = vis;

    // create a visual abstraction of the table data (loaded in the buildFrame method)
    // call our data "canUrban"
    VisualTable vt = vis.addTable("canUrban", t);

    // add a new column containing a label string showing
    // the Geographic name and population
    // note: uses the prefuse expression language
    vt.addColumn(
        "label", "CONCAT([Geographic name], ' (Population: ', FORMAT([2006 Population],0), ')')");

    // add a new column that divides the provinces by their geographic location (derived values)
    // note: uses the prefuse expression language
    vt.addColumn(
        "geographic location",
        "IF ([Province]='BC') THEN 1 ELSE "
            + "(IF ([Province] = 'AB' OR [Province] = 'SK' OR [Province] = 'MB') THEN 2 ELSE "
            + "(IF ([Province] = 'ON' OR [Province] = 'QC') THEN 3 ELSE"
            + "(IF ([Province] = 'NS' OR [Province] = 'NB' OR [Province] = 'PE' OR [Province] = 'NL') THEN 4 ELSE 5)))");

    // add a new column that converts the population data to ordinal data (derived values)
    // note: uses the prefuse expression language
    vt.addColumn(
        "population ordinal",
        "IF ([2006 Population] > 5000000) THEN 7 ELSE "
            + "(IF ([2006 Population] > 1000000) THEN 6 ELSE "
            + "(IF ([2006 Population] > 250000) THEN 5 ELSE "
            + "(IF ([2006 Population] > 100000) THEN 4 ELSE "
            + "(IF ([2006 Population] > 50000) THEN 3 ELSE "
            + "(IF ([2006 Population] > 20000) THEN 2 ELSE 1)))))");

    // create a new renderer factory for drawing the visual items
    vis.setRendererFactory(
        new RendererFactory() {

          // specify the default shape renderer (the actions will decide how to actually render the
          // visual elements)
          AbstractShapeRenderer sr = new ShapeRenderer();
          // renderers for the axes
          Renderer arY = new AxisRenderer(Constants.RIGHT, Constants.TOP);
          Renderer arX = new AxisRenderer(Constants.CENTER, Constants.FAR_BOTTOM);

          // return the appropriate renderer for a given visual item
          public Renderer getRenderer(VisualItem item) {
            return item.isInGroup("ylab") ? arY : item.isInGroup("xlab") ? arX : sr;
          }
        });

    /*
     * Step 2: Add X-Axis
     */

    // add the x-axis
    AxisLayout xaxis =
        new AxisLayout("canUrban", "Province", Constants.X_AXIS, VisiblePredicate.TRUE);

    // ensure the axis spans the width of the data container
    xaxis.setLayoutBounds(g_dataB);

    // add the labels to the x-axis
    AxisLabelLayout xlabels = new AxisLabelLayout("xlab", xaxis, g_xlabB, 15);

    /*
     * Step 3: Add the Y-Axis and its dynamic query feature
     */

    // dynamic query based on population data
    RangeQueryBinding populationQ = new RangeQueryBinding(vt, "2006 Population");
    AndPredicate filter = new AndPredicate(populationQ.getPredicate());

    // add the y-axis
    AxisLayout yaxis =
        new AxisLayout("canUrban", "2006 Population", Constants.Y_AXIS, VisiblePredicate.TRUE);

    // set the range controls on the y-axis
    yaxis.setRangeModel(populationQ.getModel());
    populationQ.getNumberModel().setValueRange(0, 6000000, 0, 6000000);

    // ensure the y-axis spans the height of the data container
    yaxis.setLayoutBounds(g_dataB);

    // add the labels to the y-axis
    AxisLabelLayout ylabels = new AxisLabelLayout("ylab", yaxis, g_ylabB);
    NumberFormat nf = NumberFormat.getIntegerInstance();
    nf.setMaximumFractionDigits(0);
    ylabels.setNumberFormat(nf);

    /*
     * Step 4: Add the search box
     */

    // dynamic query based on Geographic name data
    SearchQueryBinding searchQ = new SearchQueryBinding(vt, "Geographic name");
    filter.add(searchQ.getPredicate()); // reuse the same filter as the population query

    /*
     * Step 5: Colours and Shapes
     */

    // assign a set of five perceptually distinct colours to assign to the provinces
    // chosen from ColorBrewer (5-class qualitative Set1)
    int[] palette =
        new int[] {
          ColorLib.rgb(77, 175, 74),
          ColorLib.rgb(55, 126, 184),
          ColorLib.rgb(228, 26, 28),
          ColorLib.rgb(152, 78, 163),
          ColorLib.rgb(255, 127, 0)
        };

    // specify the stroke (exterior line) based on the ordinal data
    DataColorAction color =
        new DataColorAction(
            "canUrban", "geographic location", Constants.ORDINAL, VisualItem.STROKECOLOR, palette);

    // specify the fill (interior) as a static colour (white)
    ColorAction fill = new ColorAction("canUrban", VisualItem.FILLCOLOR, 0);

    // represent all the data points with rectangles
    ShapeAction shape = new ShapeAction("canUrban", Constants.SHAPE_RECTANGLE);

    // assign the size of the visual element based on the population data (we
    // converted the 2006 Population data to ordinal values)
    DataSizeAction size = new DataSizeAction("canUrban", "population ordinal");

    // setup a counter to keep track of which data points are currently being viewed
    Counter cntr = new Counter("canUrban");

    /*
     * Step 6: Create the action list for drawing the visual elements
     */

    ActionList draw = new ActionList();
    draw.add(cntr);
    draw.add(color);
    draw.add(fill);
    draw.add(shape);
    draw.add(size);
    draw.add(xaxis);
    draw.add(yaxis);
    draw.add(ylabels);
    draw.add(new RepaintAction());
    vis.putAction("draw", draw);
    vis.putAction("xlabels", xlabels);

    /*
     * create the action list for updating the visual elements
     * (during interactive operations and re-sizing of the window)
     */
    ActionList update = new ActionList();
    update.add(new VisibilityFilter("canUrban", filter)); // filter performs the size/name filtering
    update.add(cntr);
    update.add(xaxis);
    update.add(yaxis);
    update.add(ylabels);
    update.add(new RepaintAction());
    vis.putAction("update", update);

    // create an update listener that will update the visualization when fired
    UpdateListener lstnr =
        new UpdateListener() {

          public void update(Object src) {
            vis.run("update");
          }
        };

    // add this update listener to the filter, so that when the filter changes (i.e.,
    // the user adjusts the axis parameters, or enters a name for filtering), the
    // visualization is updated
    filter.addExpressionListener(lstnr);

    /*
     * Step 7: Setup the Display and the other Interface components
     * (scroll bar, query box, tool tips)
     */

    // create the display
    g_display = new Display(vis);

    // set the display properties
    g_display.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
    g_display.setSize(700, 450);
    g_display.setHighQuality(true);

    // call the function that sets the sizes of the containers that contain
    // the data and the axes
    displayLayout();

    // whenever the window is re-sized, update the layout of the axes
    g_display.addComponentListener(
        new ComponentAdapter() {

          public void componentResized(ComponentEvent e) {
            displayLayout();
          }
        });

    // title label (top left)
    JFastLabel g_details = new JFastLabel("Canadian Urban Population");
    g_details.setPreferredSize(new Dimension(350, 20));
    g_details.setVerticalAlignment(SwingConstants.BOTTOM);

    // total label (top right)
    g_total.setPreferredSize(new Dimension(350, 20));
    g_total.setHorizontalAlignment(SwingConstants.RIGHT);
    g_total.setVerticalAlignment(SwingConstants.BOTTOM);

    // tool tips
    ToolTipControl ttc = new ToolTipControl("label");
    Control hoverc =
        new ControlAdapter() {

          public void itemEntered(VisualItem item, MouseEvent evt) {
            if (item.isInGroup("canUrban")) {
              g_total.setText(item.getString("label"));
              item.setFillColor(item.getStrokeColor());
              item.setStrokeColor(ColorLib.rgb(0, 0, 0));
              item.getVisualization().repaint();
            }
          }

          public void itemExited(VisualItem item, MouseEvent evt) {
            if (item.isInGroup("canUrban")) {
              g_total.setText(g_totalStr);
              item.setFillColor(item.getEndFillColor());
              item.setStrokeColor(item.getEndStrokeColor());
              item.getVisualization().repaint();
            }
          }
        };
    g_display.addControlListener(ttc);
    g_display.addControlListener(hoverc);

    // vertical slider for adjusting the population filter
    JRangeSlider slider = populationQ.createVerticalRangeSlider();
    slider.setThumbColor(null);
    slider.setToolTipText("drag the arrows to filter the data");
    // smallest window: 200,000
    slider.setMinExtent(200000);
    slider.addMouseListener(
        new MouseAdapter() {

          public void mousePressed(MouseEvent e) {
            g_display.setHighQuality(false);
          }

          public void mouseReleased(MouseEvent e) {
            g_display.setHighQuality(true);
            g_display.repaint();
          }
        });

    // search box
    JSearchPanel searcher = searchQ.createSearchPanel();
    searcher.setLabelText("Urban Centre: ");
    searcher.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0));

    /*
     * Step 8: Create Containers for the Interface Elements
     */

    // add the listener to this component
    this.addComponentListener(lstnr);

    // container for elements at the top of the screen
    Box topContainer = new Box(BoxLayout.X_AXIS);
    topContainer.add(Box.createHorizontalStrut(5));
    topContainer.add(g_details);
    topContainer.add(Box.createHorizontalGlue());
    topContainer.add(Box.createHorizontalStrut(5));
    topContainer.add(g_total);
    topContainer.add(Box.createHorizontalStrut(5));

    // container for elements at the bottom of the screen
    Box bottomContainer = new Box(BoxLayout.X_AXIS);
    bottomContainer.add(Box.createHorizontalStrut(5));
    bottomContainer.add(searcher);
    bottomContainer.add(Box.createHorizontalGlue());
    bottomContainer.add(Box.createHorizontalStrut(5));
    bottomContainer.add(Box.createHorizontalStrut(16));

    // fonts, colours, etc.
    UILib.setColor(this, ColorLib.getColor(255, 255, 255), Color.GRAY);
    slider.setForeground(Color.LIGHT_GRAY);
    UILib.setFont(bottomContainer, FontLib.getFont("Tahoma", 15));
    g_details.setFont(FontLib.getFont("Tahoma", 18));
    g_total.setFont(FontLib.getFont("Tahoma", 16));

    // add the containers to the JPanel
    add(topContainer, BorderLayout.NORTH);
    add(g_display, BorderLayout.CENTER);
    add(slider, BorderLayout.EAST);
    add(bottomContainer, BorderLayout.SOUTH);

    /*
     * Step 9: Start the Visualization
     */

    vis.run("draw");
    vis.run("xlabels");
  }