private void updateNodes(HierarchicalGraph graph) {
    Modeler nodeInit = engine.getModelClasses()[AbstractEngine.CLASS_NODE].getCurrentModeler();

    NodeIterable nodeIterable;
    nodeIterable = graph.getNodes();

    for (Node node : nodeIterable) {

      Model obj = node.getNodeData().getModel();
      if (obj == null) {
        // Model is null, ADD
        obj = nodeInit.initModel(node.getNodeData());
        engine.addObject(AbstractEngine.CLASS_NODE, (ModelImpl) obj);
      } else if (!obj.isValid()) {
        engine.addObject(AbstractEngine.CLASS_NODE, (ModelImpl) obj);
      }
      obj.setCacheMarker(cacheMarker);

      // Modeaction
      if (modeManager.getMode().equals(ModeManager.AVAILABLE_MODES.HIGHLIGHT)) {
        ModelImpl impl = (ModelImpl) obj;
        //                if (!node.isVisible()) {
        //                    ColorLayer.layerColor(impl, 0.8f, 0.8f, 0.8f);
        //                }
      }
    }
  }
 private void writeListNode(Node node, boolean writeSeparator) throws IOException {
   String label = node.getNodeData().getLabel();
   if (label == null) {
     label = node.getNodeData().getId();
   }
   writer.append(label);
   if (writeSeparator) {
     writer.append(SEPARATOR);
   }
 }
  public void script() {
    // Init a project - and therefore a workspace
    ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
    pc.newProject();
    Workspace workspace = pc.getCurrentWorkspace();

    // Get controllers and models
    ImportController importController = Lookup.getDefault().lookup(ImportController.class);

    // Import file
    Container container;
    try {
      File file =
          new File(
              getClass().getResource("/org/gephi/toolkit/demos/resources/polblogs.gml").toURI());
      container = importController.importFile(file);
      container.getLoader().setEdgeDefault(EdgeDefault.DIRECTED); // Force DIRECTED
      container.setAllowAutoNode(false); // Don't create missing nodes
    } catch (Exception ex) {
      ex.printStackTrace();
      return;
    }

    // Append imported data to GraphAPI
    importController.process(container, new DefaultProcessor(), workspace);

    // List node columns
    AttributeController ac = Lookup.getDefault().lookup(AttributeController.class);
    AttributeModel model = ac.getModel();
    for (AttributeColumn col : model.getNodeTable().getColumns()) {
      System.out.println(col);
    }

    // Add boolean column
    AttributeColumn testCol = model.getNodeTable().addColumn("test", AttributeType.BOOLEAN);

    // Write values to nodes
    GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getModel();
    for (Node n : graphModel.getGraph().getNodes()) {
      n.getNodeData().getAttributes().setValue(testCol.getIndex(), Boolean.TRUE);
    }

    // Iterate values - fastest
    AttributeColumn sourceCol = model.getNodeTable().getColumn("source");
    for (Node n : graphModel.getGraph().getNodes()) {
      System.out.println(n.getNodeData().getAttributes().getValue(sourceCol.getIndex()));
    }

    // Iterate values - normal
    for (Node n : graphModel.getGraph().getNodes()) {
      System.out.println(n.getNodeData().getAttributes().getValue("source"));
    }
  }
 private void writeNodeColor(XMLStreamWriter xmlWriter, Node node) throws Exception {
   int r = Math.round(node.getNodeData().r() * 255f);
   int g = Math.round(node.getNodeData().g() * 255f);
   int b = Math.round(node.getNodeData().b() * 255f);
   if (r != 0 || g != 0 || b != 0) {
     xmlWriter.writeStartElement(VIZ, NODE_COLOR, VIZ_NAMESPACE);
     xmlWriter.writeAttribute("r", "" + r);
     xmlWriter.writeAttribute("g", "" + g);
     xmlWriter.writeAttribute("b", "" + b);
     xmlWriter.writeEndElement();
   }
 }
  private void writeNodes(XMLStreamWriter xmlWriter, HierarchicalGraph graph) throws Exception {
    if (cancel) {
      return;
    }
    xmlWriter.writeStartElement(NODES);

    AttributeColumn dynamicCol =
        dynamicCol = attributeModel.getNodeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN);

    NodeIterable nodeIterable = exportHierarchy ? graph.getNodesTree() : graph.getNodes();
    for (Node node : nodeIterable) {
      xmlWriter.writeStartElement(NODE);

      String id = node.getNodeData().getId();
      xmlWriter.writeAttribute(NODE_ID, id);
      if (node.getNodeData().getLabel() != null && !node.getNodeData().getLabel().isEmpty()) {
        xmlWriter.writeAttribute(NODE_LABEL, node.getNodeData().getLabel());
      }

      if (exportHierarchy) {
        Node parent = graph.getParent(node);
        if (parent != null) {
          xmlWriter.writeAttribute(NODE_PID, parent.getNodeData().getId());
        }
      }

      if (exportDynamic && dynamicCol != null && visibleInterval != null) {
        TimeInterval timeInterval =
            (TimeInterval) node.getNodeData().getAttributes().getValue(dynamicCol.getIndex());
        if (timeInterval != null) {
          writeTimeInterval(xmlWriter, timeInterval);
        }
      }

      if (exportAttributes && node.getNodeData().getAttributes() != null) {
        AttributeRow attributeRow = (AttributeRow) node.getNodeData().getAttributes();
        writeAttValues(xmlWriter, attributeRow, visibleInterval);
      }

      if (exportSize) {
        writeNodeSize(xmlWriter, node);
      }

      if (exportPosition) {
        writeNodePosition(xmlWriter, node);
      }

      if (exportColors) {
        writeNodeColor(xmlWriter, node);
      }

      xmlWriter.writeEndElement();
      Progress.progress(progress);
      if (cancel) {
        break;
      }
    }

    xmlWriter.writeEndElement();
  }
 private void writeNodeSize(XMLStreamWriter xmlWriter, Node node) throws Exception {
   xmlWriter.writeStartElement(VIZ, NODE_SIZE, VIZ_NAMESPACE);
   float size = node.getNodeData().getSize();
   if (normalize) {
     size = (size - minSize) / (maxSize - minSize);
   }
   xmlWriter.writeAttribute("value", "" + size);
   xmlWriter.writeEndElement();
 }
  public void coarsen(HierarchicalGraph g) {
    HierarchicalGraph graph = g;
    int retract = 0;
    int count = 0;
    for (Edge e : graph.getEdgesAndMetaEdges().toArray()) {
      Node a = e.getSource();
      Node b = e.getTarget();
      count++;
      if (graph.getParent(a) == graph.getParent(b) && graph.getLevel(a) == 0) {
        float x = (a.getNodeData().x() + b.getNodeData().x()) / 2;
        float y = (a.getNodeData().y() + b.getNodeData().y()) / 2;

        Node parent = graph.groupNodes(new Node[] {a, b});
        parent.getNodeData().setX(x);
        parent.getNodeData().setY(y);
        graph.retract(parent);
        retract++;
      }
    }
  }
  public void refine(HierarchicalGraph graph) {
    double r = 10;
    int count = 0;
    int refined = 0;
    for (Node node : graph.getTopNodes().toArray()) {
      count++;
      if (graph.getChildrenCount(node) == 2) {
        refined++;
        float x = node.getNodeData().x();
        float y = node.getNodeData().y();

        for (Node child : graph.getChildren(node)) {
          double t = Math.random();
          child.getNodeData().setX((float) (x + r * Math.cos(t)));
          child.getNodeData().setY((float) (y + r * Math.sin(t)));
        }
        graph.ungroupNodes(node);
      }
    }
    // System.out.println("COUNT = " + count);
    // System.out.println("REFINED = " + refined);
  }
 private void writeNodePosition(XMLStreamWriter xmlWriter, Node node) throws Exception {
   float x = node.getNodeData().x();
   if (normalize && x != 0.0) {
     x = (x - minX) / (maxX - minX);
   }
   float y = node.getNodeData().y();
   if (normalize && y != 0.0) {
     y = (y - minY) / (maxY - minY);
   }
   float z = node.getNodeData().z();
   if (normalize && z != 0.0) {
     z = (z - minZ) / (maxZ - minZ);
   }
   if (!(x == 0 && y == 0 && z == 0)) {
     xmlWriter.writeStartElement(VIZ, NODE_POSITION, VIZ_NAMESPACE);
     xmlWriter.writeAttribute("x", "" + x);
     xmlWriter.writeAttribute("y", "" + y);
     if (z != 0) {
       xmlWriter.writeAttribute("z", "" + z);
     }
     xmlWriter.writeEndElement();
   }
 }
  public void groupCluster(Cluster cluster) {
    GraphModel gm = Lookup.getDefault().lookup(GraphController.class).getModel();
    if (gm != null) {
      HierarchicalGraph graph = gm.getHierarchicalGraphVisible();
      Node[] newGroup = cluster.getNodes();
      float centroidX = 0;
      float centroidY = 0;
      int len = 0;
      Node group = graph.groupNodes(newGroup);
      cluster.setMetaNode(group);

      group.getNodeData().setLabel("Group");
      group.getNodeData().setSize(10f);
      for (Node child : newGroup) {
        centroidX += child.getNodeData().x();
        centroidY += child.getNodeData().y();
        len++;
      }
      centroidX /= len;
      centroidY /= len;
      group.getNodeData().setX(centroidX);
      group.getNodeData().setY(centroidY);
    }
  }
  private void calculateMinMax(Graph graph) {
    minX = Float.POSITIVE_INFINITY;
    maxX = Float.NEGATIVE_INFINITY;
    minY = Float.POSITIVE_INFINITY;
    maxY = Float.NEGATIVE_INFINITY;
    minZ = Float.POSITIVE_INFINITY;
    maxZ = Float.NEGATIVE_INFINITY;
    minSize = Float.POSITIVE_INFINITY;
    maxSize = Float.NEGATIVE_INFINITY;

    for (Node node : graph.getNodes()) {
      NodeData nodeData = node.getNodeData();
      minX = Math.min(minX, nodeData.x());
      maxX = Math.max(maxX, nodeData.x());
      minY = Math.min(minY, nodeData.y());
      maxY = Math.max(maxY, nodeData.y());
      minZ = Math.min(minZ, nodeData.z());
      maxZ = Math.max(maxZ, nodeData.z());
      minSize = Math.min(minSize, nodeData.getSize());
      maxSize = Math.max(maxSize, nodeData.getSize());
    }
  }
 private void writeColumns(Clusterer clusterer) {
   Cluster[] clusters = clusterer.getClusters();
   if (clusters != null && clusters.length > 0) {
     ClustererBuilder builder = getBuilder(clusterer);
     AttributeModel am = Lookup.getDefault().lookup(AttributeController.class).getModel();
     String id = "clustering_" + builder.getName();
     String title = "Clustering (" + builder.getName() + ")";
     AttributeColumn col = am.getNodeTable().getColumn(id);
     if (col == null) {
       col =
           am.getNodeTable()
               .addColumn(id, title, AttributeType.INT, AttributeOrigin.COMPUTED, null);
       StatusDisplayer.getDefault()
           .setStatusText("A new column \"" + title + "\" has been created");
     }
     for (int i = 0; i < clusters.length; i++) {
       Integer clusterId = new Integer(i);
       for (Node n : clusters[i].getNodes()) {
         n.getNodeData().getAttributes().setValue(col.getIndex(), clusterId);
       }
     }
   }
 }
  @Override
  public void execute(GraphModel graphModel, AttributeModel attributeModel) {
    // Graph graph = graphModel.getGraphVisible();
    HierarchicalGraph graph = null;
    // get visible graph
    if (directed) {
      graph = graphModel.getHierarchicalDirectedGraphVisible();
    } else {
      graph = graphModel.getHierarchicalUndirectedGraphVisible();
    }

    // lock graph
    graph.readLock();
    try {
      Progress.start(progressTicket, graph.getNodeCount());
      // all coefficients
      nodeCoefficients = new double[graph.getNodeCount()];

      // attribute column
      AttributeTable nodeTable = attributeModel.getNodeTable();
      AttributeColumn clusteringColumn = nodeTable.getColumn("newClusteringCoefficient");
      if (clusteringColumn == null) {
        clusteringColumn =
            nodeTable.addColumn(
                "newClusteringCoefficient",
                "Local Clustering Coefficient",
                AttributeType.DOUBLE,
                AttributeOrigin.COMPUTED,
                0.0);
      }

      int i = 0;
      // for each node
      for (Node e : graph.getNodes()) {
        // compute coefficient
        double coeficient = 0.0;
        double denominator = (graph.getDegree(e) * (graph.getDegree(e) - 1));
        if (!directed) {
          denominator /= 2;
        }
        double numerator = 0.0;
        // get neighbors as list
        List<Node> n2 = Arrays.asList(graph.getNeighbors(e).toArray());
        List<Node> neighbors2 = new ArrayList<Node>(n2);
        for (Node neighbor1 : graph.getNeighbors(e)) {
          neighbors2.remove(neighbor1);
          // count edges betwwen neighbors
          for (Node neighbor2 : neighbors2) {
            if (graph.getEdge(neighbor1, neighbor2) != null
                || graph.getEdge(neighbor2, neighbor1) != null) {
              numerator++;
            }
          }
        }
        // compute coefficient
        if (denominator > 0) {
          coeficient = numerator / denominator;
        } else {
          coeficient = 0.0;
        }
        averageCoefficient += coeficient;
        nodeCoefficients[i] = coeficient;
        i++;
        // set attribute
        AttributeRow row = (AttributeRow) e.getNodeData().getAttributes();
        row.setValue(clusteringColumn, coeficient);
        Progress.progress(progressTicket);
        if (cancel) {
          break;
        }
      }
      if (graph.getNodeCount() > 0) {
        averageCoefficient = averageCoefficient / graph.getNodeCount();
      }

      graph.readUnlockAll();
    } catch (Exception e) {
      e.printStackTrace();
      // Unlock graph
      graph.readUnlockAll();
    }
  }
Beispiel #14
0
  @Test
  public void testPNG() {
    try {

      // Init a project - and therefore a workspace
      ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
      pc.newProject();
      Workspace workspace = pc.getCurrentWorkspace();

      // Append container to graph structure
      String sample = "/org/gephi/desktop/welcome/samples/Les Miserables.gexf";
      final InputStream stream = WelcomeTopComponent.class.getResourceAsStream(sample);
      ImportController importController = Lookup.getDefault().lookup(ImportController.class);
      FileImporter fileImporter = importController.getFileImporter(".gexf");
      Container container = importController.importFile(stream, fileImporter);

      importController.process(container, new DefaultProcessor(), workspace);

      // Add self loop
      GraphController graphController = Lookup.getDefault().lookup(GraphController.class);
      Graph graph = graphController.getModel().getGraph();
      Node node = graph.getNode(12);
      System.out.println("Self loop " + node.getNodeData().getLabel());
      graph.addEdge(graphController.getModel().factory().newEdge(node, node, 31, true));

      // Set label edges
      for (Edge edge : graphController.getModel().getGraph().getEdges()) {
        edge.getEdgeData().setLabel("Label test");
      }

      // svg document

      // attribute ???
      AttributeController attributeController =
          Lookup.getDefault().lookup(AttributeController.class);
      AttributeModel attributeModel = null;

      // preview
      PreviewController previewController = Lookup.getDefault().lookup(PreviewController.class);
      PreviewModel previewModel = previewController.getModel(workspace);
      PreviewProperties previewProperties = previewModel.getProperties();
      previewController.refreshPreview(workspace);

      previewModel.getProperties().putValue("width", 1000);
      previewModel.getProperties().putValue("height", 1000);
      ProcessingTarget target =
          (ProcessingTarget)
              previewController.getRenderTarget(RenderTarget.PROCESSING_TARGET, workspace);

      previewProperties.putValue(LegendModel.LEGEND_PROPERTIES, new LegendModel(workspace));

      LegendModel legendManager = previewProperties.getValue(LegendModel.LEGEND_PROPERTIES);
      Integer itemIndex = legendManager.getCurrentIndex();

      // creating item
      Item item = addGroupsItem(itemIndex, graph, attributeModel);
      //            Item item = addTextItem(itemIndex, graph, attributeModel);

      // add item
      LegendController.getInstance().addItemToLegendModel(workspace, item);

      // render
      previewController.refreshPreview(workspace);
      previewController.render(target);

      File fileToSave = new File("/Volumes/edubecks/edubecks/Untitled.png");
      OutputStream fos = new FileOutputStream(fileToSave);
      Writer writer = new OutputStreamWriter(fos, "UTF-8");

      //            // saving
      //            int width = 1000;
      //            int height = 1000;
      //            PGraphicsJava2D pg2 = (PGraphicsJava2D) target.getGraphics();
      //            BufferedImage img = new BufferedImage(width, height,
      // BufferedImage.TYPE_INT_ARGB);
      //
      //            System.out.println("@Var: pg2.pixels: "+pg2.pixels);
      //            img.setRGB(0, 0, width, height, pg2.pixels, 0, width);
      //            ImageIO.write(img, "png", fileToSave);
      //            stream.close();

      PNGExporter pngExporter = new PNGExporter();
      //            pngExporter.setHeight(2000);
      //            pngExporter.setWidth(2000);
      pngExporter.setWorkspace(workspace);
      pngExporter.setOutputStream(fos);
      pngExporter.execute();

    } catch (Exception e) {
      Exceptions.printStackTrace(e);
    }
  }
Beispiel #15
0
  private void doPoetGraph(String path, String poet) {
    System.out.println(poet);
    ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
    pc.newProject();
    Workspace workspace = pc.getCurrentWorkspace();
    GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getModel();
    UndirectedGraph directedGraph = graphModel.getUndirectedGraph();

    ExportController ec = Lookup.getDefault().lookup(ExportController.class);

    ArrayList<String> queue = new ArrayList<String>();
    ArrayList<Integer> depthqueue = new ArrayList<Integer>();
    queue.add(poet);
    depthqueue.add(0);
    int depth = 0;
    int nodecount = 0;

    while (queue.size() != 0 && depth < 3 && nodecount < 20) {
      String name = queue.remove(0);
      depth = depthqueue.remove(0);

      Node n = directedGraph.getNode(name);
      if (n == null) {
        n = graphModel.factory().newNode(name);
        n.getNodeData().setLabel(name);
        directedGraph.addNode(n);
        nodecount++;
      }

      Iterator<String> it = edges.get(poet).keySet().iterator();
      while (it.hasNext()) {
        String to = it.next();
        Node slave = directedGraph.getNode(to);
        if (slave == null) {
          slave = graphModel.factory().newNode(to);
          slave.getNodeData().setLabel(to);
          directedGraph.addNode(slave);
        }
        Edge e = graphModel.factory().newEdge(n, slave, edges.get(poet).get(to) * 15, false);
        directedGraph.addEdge(e);
        queue.add(to);
        depthqueue.add(depth + 1);
      }
    }

    // Preview
    PreviewModel previewModel = Lookup.getDefault().lookup(PreviewController.class).getModel();
    previewModel.getProperties().putValue(PreviewProperty.SHOW_NODE_LABELS, Boolean.TRUE);
    previewModel.getProperties().putValue(PreviewProperty.EDGE_COLOR, new EdgeColor(Color.BLUE));
    previewModel.getProperties().putValue(PreviewProperty.EDGE_THICKNESS, new Float(0.005f));
    previewModel
        .getProperties()
        .putValue(PreviewProperty.NODE_LABEL_COLOR, new DependantOriginalColor(Color.RED));
    previewModel
        .getProperties()
        .putValue(
            PreviewProperty.NODE_LABEL_FONT,
            previewModel
                .getProperties()
                .getFontValue(PreviewProperty.NODE_LABEL_FONT)
                .deriveFont(12));

    YifanHuLayout layout = new YifanHuLayout(null, new StepDisplacement(1f));
    layout.setGraphModel(graphModel);
    layout.resetPropertiesValues();
    layout.setOptimalDistance(120f);

    layout.initAlgo();
    for (int i = 0; i < 100 && layout.canAlgo(); i++) {
      layout.goAlgo();
    }

    try {
      ec.exportFile(new File(path + poet + ".svg"));
    } catch (IOException ex) {
      ex.printStackTrace();
      return;
    }
  }