コード例 #1
0
 public void ungroupCluster(Cluster cluster) {
   GraphModel gm = Lookup.getDefault().lookup(GraphController.class).getModel();
   if (gm != null) {
     HierarchicalGraph graph = gm.getHierarchicalGraphVisible();
     graph.ungroupNodes(cluster.getMetaNode());
     cluster.setMetaNode(null);
   }
 }
コード例 #2
0
  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"));
    }
  }
コード例 #3
0
 public void setEnable(boolean enable) {
   if (enable) {
     if (observer == null) {
       observer = graphModel.createGraphObserver(graphModel.getGraph(), false);
     }
   } else if (observer != null && !observer.isDestroyed()) {
     observer.destroy();
     observer = null;
   }
   if (!isAlive()) {
     start();
   }
 }
コード例 #4
0
  public boolean execute() {
    GraphModel graphModel = workspace.getLookup().lookup(GraphModel.class);
    Graph graph = null;
    if (exportVisible) {
      graph = graphModel.getGraphVisible();
    } else {
      graph = graphModel.getGraph();
    }
    try {
      exportData(graph);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    return !cancel;
  }
コード例 #5
0
  public AppearanceModelImpl(Workspace workspace) {
    this.workspace = workspace;
    this.graphModel = Lookup.getDefault().lookup(GraphController.class).getGraphModel(workspace);
    this.defaultInterpolator = Interpolator.LINEAR;
    this.functionLock = new Object();
    this.transformerUIs = initTransformerUIs();
    this.nodeTransformers = initNodeTransformers();
    this.edgeTransformers = initEdgeTransformers();
    this.forcedPartition = new HashSet<String>();
    this.forcedRanking = new HashSet<String>();
    this.forcedColumnsRefresh = new ArrayList<Column>();

    // Functions
    functionsMain = new FunctionsModel(graphModel.getGraph());
    refreshFunctions(graphModel.getGraph());
  }
コード例 #6
0
 public boolean requireUpdate() {
   if (graph == null) {
     // Try to get a graph
     GraphModel graphModel = controller.getModel();
     if (graphModel != null) {
       graph = graphModel.getHierarchicalGraphVisible();
     }
   }
   // Refresh reader if sight changed
   Graph g = graph;
   if (g != null) {
     if (g.getGraphModel().getVisibleView().getViewId() != graphView) {
       reset();
     }
     return g.getNodeVersion() > nodeVersion || g.getEdgeVersion() > edgeVersion;
   }
   return false;
 }
コード例 #7
0
 @Override
 public Collection getValues() {
   Object[] labels = model.getEdgeTypeLabels();
   ArrayList<Object> col = new ArrayList<Object>(labels.length);
   for (Object l : labels) {
     if (!(l == null && graph.getEdgeCount(0) == 0)) {
       col.add(l);
     }
   }
   return col;
 }
コード例 #8
0
  @Override
  public void execute(GraphModel gm, AttributeModel am) {
    Graph graph = gm.getUndirectedGraphVisible();
    graph.readLock();

    // calculate all Euclidean distances between all nodes
    double[] distances = geometry.calculateManyEuclideanDistances(graph.getNodes().toArray());
    // calculate the variation of coefficient over the distances
    result = String.valueOf(math.variationCoefficient(distances));
    graph.readUnlockAll();
  }
コード例 #9
0
ファイル: DynamicNbEdges.java プロジェクト: hbruch/gephi
  @Override
  public void loop(GraphView window, Interval interval) {
    Graph graph = graphModel.getGraph(window);

    int count = graph.getEdgeCount();

    graph.setAttribute(NB_EDGES, count, interval.getLow());
    graph.setAttribute(NB_EDGES, count, interval.getHigh());

    counts.put(interval.getLow(), count);
    counts.put(interval.getHigh(), count);
  }
コード例 #10
0
 private boolean isRanking(Graph graph, Column column) {
   if (column.isDynamic() && column.isNumber()) {
     ElementIterable<? extends Element> iterable =
         AttributeUtils.isNodeColumn(column) ? graph.getNodes() : graph.getEdges();
     for (Element el : iterable) {
       if (el.getAttribute(column, graph.getView()) != null) {
         iterable.doBreak();
         return true;
       }
     }
   } else if (!column.isDynamic() && column.isIndexed() && column.isNumber()) {
     Index index;
     if (AttributeUtils.isNodeColumn(column)) {
       index = localScale ? graphModel.getNodeIndex(graph.getView()) : graphModel.getNodeIndex();
     } else {
       index = localScale ? graphModel.getEdgeIndex(graph.getView()) : graphModel.getEdgeIndex();
     }
     if (index.countValues(column) > 0) {
       return true;
     }
   }
   return false;
 }
コード例 #11
0
 private boolean isPartition(Graph graph, Column column) {
   if (column.isDynamic()) {
     Set<Object> set = new HashSet<Object>();
     boolean hasNullValue = false;
     int elements = 0;
     ElementIterable<? extends Element> iterable =
         AttributeUtils.isNodeColumn(column) ? graph.getNodes() : graph.getEdges();
     for (Element el : iterable) {
       TimeMap val = (TimeMap) el.getAttribute(column);
       if (val != null) {
         Object[] va = val.toValuesArray();
         for (Object v : va) {
           if (v != null) {
             set.add(v);
           } else {
             hasNullValue = true;
           }
           elements++;
         }
       }
     }
     double ratio = set.size() / (double) elements;
     return ratio <= 0.9;
   } else if (column.isIndexed()) {
     Index index;
     if (AttributeUtils.isNodeColumn(column)) {
       index = graphModel.getNodeIndex(graph.getView());
     } else {
       index = graphModel.getEdgeIndex(graph.getView());
     }
     int valueCount = index.countValues(column);
     int elementCount = index.countElements(column);
     double ratio = valueCount / (double) elementCount;
     return ratio <= 0.9;
   }
   return false;
 }
コード例 #12
0
  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);
    }
  }
コード例 #13
0
ファイル: EdgesDataTable.java プロジェクト: hbruch/gephi
  @Override
  public List<? extends ElementDataColumn<Edge>> getFakeDataColumns(
      GraphModel graphModel, DataTablesModel dataTablesModel) {
    ArrayList<PropertyDataColumn<Edge>> propertiesColumns =
        new ArrayList<PropertyDataColumn<Edge>>();

    propertiesColumns.add(SOURCE_COLUMN);
    propertiesColumns.add(TARGET_COLUMN);
    propertiesColumns.add(TYPE_COLUMN);
    if (graphModel.isMultiGraph()) {
      propertiesColumns.add(KIND_COLUMN);
    }

    return propertiesColumns;
  }
コード例 #14
0
  public void script() {

    NetworkLayer nl = MultiLayerNetwork.getSelected();

    if (pc == null) pc = Lookup.getDefault().lookup(ProjectController.class);

    // Init a project - and therefore a workspace
    Project pro = pc.getCurrentProject();

    if (pro == null) {
      pc.newProject();
      pro = pc.getCurrentProject();
    }

    Workspace workspace = pc.newWorkspace(pro);

    // Get controllers and models
    ImportController importController = Lookup.getDefault().lookup(ImportController.class);
    GraphModel graphModel =
        Lookup.getDefault().lookup(GraphController.class).getGraphModel(workspace);
    //        AttributeModel attributeModel =
    // Lookup.getDefault().lookup(AttributeController.class).getModel();

    // Import database
    EdgeListHiveDatabaseImpl db = new EdgeListHiveDatabaseImpl();

    db.setDBName("default"); // !!!
    db.setHost("127.0.0.1");
    //       db.setHost( HadoopClusterDefaults.HIVE_SERVER_IP );
    db.setPort(10000); // !!!

    db.setUsername("kamir");
    db.setPasswd("8cwrr");

    db.setSQLDriver(new HiveJDBCDriver());

    String tab = "edgelist_es_de_erfurt2";

    db.setNodeQuery(
        "SELECT UNIQUE( " + tab + ".source ) AS id, " + tab + ".source AS label FROM " + tab);
    db.setEdgeQuery(
        "SELECT "
            + tab
            + ".source AS source, "
            + tab
            + ".target AS target "
            + tab
            + ".q0 AS weight FROM "
            + tab);

    ImporterEdgeList edgeListImporter = new ImporterEdgeList();

    Container container = null;

    String url = SQLUtils.getUrl(db.getSQLDriver(), db.getHost(), db.getPort(), db.getDBName());

    System.out.println(url);

    javax.swing.JOptionPane.showMessageDialog(null, "Go ... Hive! \n> " + url);

    try {
      container = importController.importDatabase(db, edgeListImporter);

      //            container.setAllowAutoNode(false);      //Don't create missing nodes
      container.getLoader().setEdgeDefault(EdgeDirectionDefault.UNDIRECTED); // Force UNDIRECTED

      // Append imported data to GraphAPI
      importController.process(container, new DefaultProcessor(), workspace);
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      if (container != null) System.out.println(container.getReport().getText());
    }

    // See if graph is well imported
    UndirectedGraph graph = graphModel.getUndirectedGraph();
    System.out.println("Nodes: " + graph.getNodeCount());
    System.out.println("Edges: " + graph.getEdgeCount());

    // Layout - 100 Yifan Hu passes
    //        YifanHuLayout layout = new YifanHuLayout(null, new StepDisplacement(1f));
    //        layout.setGraphModel(graphModel);
    //        layout.resetPropertiesValues();
    //        layout.initAlgo();
    //        for (int i = 0; i < 100 && layout.canAlgo(); i++) {
    //            layout.goAlgo();
    //        }
    //        layout.endAlgo();

  }
コード例 #15
0
  public void updateWorld() {
    // System.out.println("update world");
    cacheMarker++;

    GraphModel graphModel = controller.getModel();
    if (graphModel == null) {
      engine.worldUpdated(cacheMarker);
      return;
    }
    if (gm != null && gm != graphModel) {
      reset();
    }
    gm = graphModel;
    HierarchicalGraph graph;
    if (graphModel.isDirected()) {
      undirected = false;
      graph = graphModel.getHierarchicalDirectedGraphVisible();
    } else if (graphModel.isUndirected()) {
      undirected = true;
      graph = graphModel.getHierarchicalUndirectedGraphVisible();
    } else if (graphModel.isMixed()) {
      undirected = false;
      graph = graphModel.getHierarchicalMixedGraphVisible();
    } else {
      undirected = false;
      graph = graphModel.getHierarchicalDirectedGraphVisible();
    }

    if (dynamicModel == null) {
      DynamicController dynamicController = Lookup.getDefault().lookup(DynamicController.class);
      dynamicModel = dynamicController.getModel();
    }

    graphView = graph.getView().getViewId();

    ModelClass[] object3dClasses = engine.getModelClasses();

    graph.readLock();

    ModelClass nodeClass = object3dClasses[AbstractEngine.CLASS_NODE];
    if (nodeClass.isEnabled()
        && (graph.getNodeVersion() > nodeVersion || modeManager.requireModeChange())) {
      updateNodes(graph);
      nodeClass.setCacheMarker(cacheMarker);
    }

    ModelClass edgeClass = object3dClasses[AbstractEngine.CLASS_EDGE];
    if (edgeClass.isEnabled()
        && (graph.getEdgeVersion() > edgeVersion || modeManager.requireModeChange())) {
      updateEdges(graph);
      updateMetaEdges(graph);
      edgeClass.setCacheMarker(cacheMarker);
      if (!undirected && vizConfig.isShowArrows()) {
        object3dClasses[AbstractEngine.CLASS_ARROW].setCacheMarker(cacheMarker);
      }
    }

    ModelClass potatoClass = object3dClasses[AbstractEngine.CLASS_POTATO];
    if (potatoClass.isEnabled()
        && (graph.getNodeVersion() > nodeVersion || modeManager.requireModeChange())) {
      updatePotatoes(graph);
      potatoClass.setCacheMarker(cacheMarker);
    }

    nodeVersion = graph.getNodeVersion();
    edgeVersion = graph.getEdgeVersion();

    graph.readUnlock();

    engine.worldUpdated(cacheMarker);
  }
コード例 #16
0
  private void executeDynamic(DynamicStatistics statistics, DynamicLongTask dynamicLongTask) {
    GraphController graphController = Lookup.getDefault().lookup(GraphController.class);
    GraphModel graphModel = graphController.getGraphModel();

    double window = statistics.getWindow();
    double tick = statistics.getTick();

    GraphView currentView = graphModel.getVisibleView();
    Interval bounds = statistics.getBounds();
    if (bounds == null) {
      if (currentView.isMainView()) {
        bounds = graphModel.getTimeBounds();
      } else {
        bounds = currentView.getTimeInterval();
      }
      statistics.setBounds(bounds);
    }

    if (dynamicLongTask != null) {
      // Count
      int c = (int) ((bounds.getHigh() - window - bounds.getLow()) / tick);
      dynamicLongTask.start(c);
    }

    // Init
    statistics.execute(graphModel);

    // Loop
    for (double low = bounds.getLow(); low <= bounds.getHigh() - window; low += tick) {
      double high = low + window;

      Graph graph = graphModel.getGraphVisible();

      graph.writeLock();

      GraphView view = graphModel.createView();
      Subgraph g = graphModel.getGraph(view);

      TimeIndex<Node> nodeIndex = graphModel.getNodeTimeIndex(currentView);
      if (Double.isInfinite(nodeIndex.getMinTimestamp())
          && Double.isInfinite(nodeIndex.getMaxTimestamp())) {
        for (Node node : graph.getNodes()) {
          g.addNode(node);
        }
      } else {
        for (Node node : nodeIndex.get(new Interval(low, high))) {
          g.addNode(node);
        }
      }

      TimeIndex<Edge> edgeIndex = graphModel.getEdgeTimeIndex(currentView);
      if (Double.isInfinite(edgeIndex.getMinTimestamp())
          && Double.isInfinite(edgeIndex.getMaxTimestamp())) {
        for (Edge edge : graph.getEdges()) {
          if (g.contains(edge.getSource()) && g.contains(edge.getTarget())) {
            g.addEdge(edge);
          }
        }
      } else {
        for (Edge edge : edgeIndex.get(new Interval(low, high))) {
          if (g.contains(edge.getSource()) && g.contains(edge.getTarget())) {
            g.addEdge(edge);
          }
        }
      }

      graph.writeUnlock();

      statistics.loop(g.getView(), new Interval(low, high));

      // Cancelled?
      if (dynamicLongTask != null && dynamicLongTask.isCancelled()) {
        return;
      } else if (dynamicLongTask != null) {
        dynamicLongTask.progress();
      }
    }
    statistics.end();
    model.addReport(statistics);
  }
コード例 #17
0
  @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();
    }
  }
コード例 #18
0
  public PreviewUIControllerImpl() {
    listeners = new ArrayList<PropertyChangeListener>();
    ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
    graphController = Lookup.getDefault().lookup(GraphController.class);
    pc.addWorkspaceListener(
        new WorkspaceListener() {

          public void initialize(Workspace workspace) {
            workspace.add(new PreviewUIModelImpl());
            enableRefresh();
          }

          public void select(Workspace workspace) {
            // Make sure AttributeModel is created before graph model:
            Lookup.getDefault().lookup(AttributeController.class).getModel();

            graphModel = graphController.getModel();
            graphModel.addGraphListener(PreviewUIControllerImpl.this);

            model = workspace.getLookup().lookup(PreviewUIModelImpl.class);
            if (model == null) {
              model = new PreviewUIModelImpl();
              workspace.add(model);
            }
            fireEvent(SELECT, model);
          }

          public void unselect(Workspace workspace) {
            if (graphModel != null) {
              graphModel.removeGraphListener(PreviewUIControllerImpl.this);
              graphModel = null;
            }
            fireEvent(UNSELECT, model);
          }

          public void close(Workspace workspace) {}

          public void disable() {
            if (graphModel != null) {
              graphModel.removeGraphListener(PreviewUIControllerImpl.this);
              graphModel = null;
            }
            fireEvent(SELECT, null);
            model = null;
          }
        });
    if (pc.getCurrentWorkspace() != null) {
      model = pc.getCurrentWorkspace().getLookup().lookup(PreviewUIModelImpl.class);
      if (model == null) {
        model = new PreviewUIModelImpl();
        pc.getCurrentWorkspace().add(model);
      }
      graphModel = graphController.getModel();
      graphModel.addGraphListener(this);
    }

    previewController = Lookup.getDefault().lookup(PreviewController.class);

    // Register editors
    // Overriding default Preview API basic editors that don't support CustomEditor
    PropertyEditorManager.registerEditor(EdgeColor.class, EdgeColorPropertyEditor.class);
    PropertyEditorManager.registerEditor(
        DependantOriginalColor.class, DependantOriginalColorPropertyEditor.class);
    PropertyEditorManager.registerEditor(DependantColor.class, DependantColorPropertyEditor.class);
  }
コード例 #19
0
  public Graph retrieveGraph(GraphModel graphModel, boolean isFilterGraph) {
    Graph graph = graphModel.getGraph();

    graph.clear();
    Map<Integer, JsonObject> nMap;
    Map<Integer, JsonObject> eMap;
    if (!isFilterGraph) {
      nMap = nodesMap;
      eMap = edgesMap;
    } else {
      nMap = nodesMapFilter;
      eMap = edgesMapFilter;
    }

    for (Entry<Integer, JsonObject> enSet : nMap.entrySet()) {
      Map<String, Object> map = enSet.getValue().getMap();
      Node node = graphModel.factory().newNode(enSet.getValue().getValue("id"));
      for (Entry<String, Object> attSet : map.entrySet()) {
        if (!attSet.getKey().equalsIgnoreCase("id")
            && !attSet.getKey().equalsIgnoreCase("x")
            && !attSet.getKey().equalsIgnoreCase("y")
            && !attSet.getKey().equalsIgnoreCase("cR")
            && !attSet.getKey().equalsIgnoreCase("size")
            && !attSet.getKey().equalsIgnoreCase("cG")
            && !attSet.getKey().equalsIgnoreCase("cB")) {
          node.setAttribute(attSet.getKey(), attSet.getValue());
        }
        if (attSet.getKey().equalsIgnoreCase("x")) {
          node.setX((float) attSet.getValue());
        }
        if (attSet.getKey().equalsIgnoreCase("y")) {
          node.setY((float) attSet.getValue());
        }
      }
      node.setSize((float) Double.parseDouble(map.get("size").toString()));
      node.setColor(
          new Color(
              (float) Double.parseDouble(map.get("cR").toString()),
              (float) Double.parseDouble(map.get("cG").toString()),
              (float) Double.parseDouble(map.get("cB").toString())));
      graph.addNode(node);
    }
    for (Entry<Integer, JsonObject> enSet : eMap.entrySet()) {
      Map<String, Object> map = enSet.getValue().getMap();
      Edge edge =
          graphModel
              .factory()
              .newEdge(
                  map.get("id"),
                  graph.getNode(map.get("source")),
                  graph.getNode(map.get("target")),
                  1,
                  Double.parseDouble(map.get("weight").toString()),
                  true);
      for (Entry<String, Object> attSet : map.entrySet()) {
        if (!attSet.getKey().equalsIgnoreCase("id")
            && !attSet.getKey().equalsIgnoreCase("source")
            && !attSet.getKey().equalsIgnoreCase("target")
            && !attSet.getKey().equalsIgnoreCase("size")
            && !attSet.getKey().equalsIgnoreCase("cR")
            && !attSet.getKey().equalsIgnoreCase("cG")
            && !attSet.getKey().equalsIgnoreCase("cB")) {
          edge.setAttribute(attSet.getKey(), attSet.getValue());
        }
      }
      edge.setWeight(Double.parseDouble(map.get("size").toString()));
      edge.setColor(
          new Color(
              (float) Double.parseDouble(map.get("cR").toString()),
              (float) Double.parseDouble(map.get("cG").toString()),
              (float) Double.parseDouble(map.get("cB").toString())));
      graph.addEdge(edge);
    }

    return graph;
  }
コード例 #20
0
 @Override
 public int count(Object value) {
   return graph.getEdgeCount(model.getEdgeType(value));
 }
コード例 #21
0
  private void writeEdges(XMLStreamWriter xmlWriter, HierarchicalGraph graph) throws Exception {
    if (cancel) {
      return;
    }
    xmlWriter.writeStartElement(EDGES);

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

    EdgeIterable edgeIterable =
        exportHierarchy ? graph.getEdgesTree() : graph.getEdgesAndMetaEdges();
    for (Edge edge : edgeIterable) {
      xmlWriter.writeStartElement(EDGE);

      if (edge.getEdgeData().getId() != null
          && !edge.getEdgeData().getId().equals(Integer.toString(edge.getId()))) {
        xmlWriter.writeAttribute(EDGE_ID, edge.getEdgeData().getId());
      }
      xmlWriter.writeAttribute(EDGE_SOURCE, edge.getSource().getNodeData().getId());
      xmlWriter.writeAttribute(EDGE_TARGET, edge.getTarget().getNodeData().getId());

      if (edge.isDirected() && graphModel.isMixed()) {
        xmlWriter.writeAttribute(EDGE_TYPE, "directed");
      } else if (!edge.isDirected() && graphModel.isMixed()) {
        xmlWriter.writeAttribute(EDGE_TYPE, "undirected");
      }

      String label = edge.getEdgeData().getLabel();
      if (label != null && !label.isEmpty()) {
        xmlWriter.writeAttribute(EDGE_LABEL, label);
      }

      float weight = edge.getWeight();
      if (weight != 1f) {
        xmlWriter.writeAttribute(EDGE_WEIGHT, "" + weight);
      }

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

      if (exportColors) {
        writeEdgeColor(xmlWriter, edge);
      }

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

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

    xmlWriter.writeEndElement();
  }
コード例 #22
0
  public boolean execute() {
    attributeModel = workspace.getLookup().lookup(AttributeModel.class);
    graphModel = workspace.getLookup().lookup(GraphModel.class);
    HierarchicalGraph graph = null;
    if (exportVisible) {
      graph = graphModel.getHierarchicalGraphVisible();
    } else {
      graph = graphModel.getHierarchicalGraph();
    }
    Progress.start(progress);
    graph.readLock();

    // Options
    if (normalize) {
      calculateMinMax(graph);
    }

    // Calculate progress units count
    int max = 0;
    if (exportHierarchy) {
      for (Node n : graph.getNodesTree()) {
        max++;
      }
      for (Edge e : graph.getEdgesTree()) {
        max++;
      }
    } else {
      max = graph.getNodeCount();
      for (Edge e : graph.getEdgesAndMetaEdges()) {
        max++;
      }
    }
    Progress.switchToDeterminate(progress, max);

    try {
      XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
      outputFactory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.FALSE);

      XMLStreamWriter xmlWriter = outputFactory.createXMLStreamWriter(writer);
      xmlWriter = new IndentingXMLStreamWriter(xmlWriter);

      xmlWriter.writeStartDocument("UTF-8", "1.0");
      xmlWriter.setPrefix("", GEXF_NAMESPACE);
      xmlWriter.writeStartElement(GEXF_NAMESPACE, GEXF);
      xmlWriter.writeNamespace("", GEXF_NAMESPACE);
      xmlWriter.writeAttribute(GEXF_VERSION, "1.1");

      if (exportColors || exportPosition || exportSize) {
        xmlWriter.writeNamespace(VIZ, VIZ_NAMESPACE);
      }
      xmlWriter.writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
      xmlWriter.writeAttribute("xsi:schemaLocation", GEXF_NAMESPACE_LOCATION);

      if (exportDynamic) {
        DynamicController dynamicController = Lookup.getDefault().lookup(DynamicController.class);
        dynamicModel = dynamicController != null ? dynamicController.getModel(workspace) : null;
        visibleInterval =
            dynamicModel == null
                ? null
                : exportVisible
                    ? dynamicModel.getVisibleInterval()
                    : new TimeInterval(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
      }

      writeMeta(xmlWriter);
      writeGraph(xmlWriter, graph);

      xmlWriter.writeEndElement();
      xmlWriter.writeEndDocument();
      xmlWriter.close();

    } catch (Exception e) {
      graph.readUnlockAll();
      if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
      }
      throw new RuntimeException(e);
    }

    graph.readUnlock();

    Progress.finish(progress);
    return !cancel;
  }
コード例 #23
0
  public void process() {
    // Workspace
    ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
    if (workspace == null) {
      workspace = pc.newWorkspace(pc.getCurrentProject());
      pc.openWorkspace(workspace);
    }
    if (container.getSource() != null) {
      pc.setSource(workspace, container.getSource());
    }

    // Architecture
    GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getModel(workspace);

    HierarchicalGraph graph = null;
    switch (container.getEdgeDefault()) {
      case DIRECTED:
        graph = graphModel.getHierarchicalDirectedGraph();
        break;
      case UNDIRECTED:
        graph = graphModel.getHierarchicalUndirectedGraph();
        break;
      case MIXED:
        graph = graphModel.getHierarchicalMixedGraph();
        break;
      default:
        graph = graphModel.getHierarchicalMixedGraph();
        break;
    }
    GraphFactory factory = graphModel.factory();

    // Attributes - Creates columns for properties
    attributeModel = Lookup.getDefault().lookup(AttributeController.class).getModel(workspace);
    attributeModel.mergeModel(container.getAttributeModel());

    // Dynamic
    if (container.getTimeFormat() != null) {
      DynamicController dynamicController = Lookup.getDefault().lookup(DynamicController.class);
      if (dynamicController != null) {
        dynamicController.setTimeFormat(container.getTimeFormat());
      }
    }

    int nodeCount = 0;
    // Create all nodes
    for (NodeDraftGetter draftNode : container.getNodes()) {
      Node n = factory.newNode(draftNode.isAutoId() ? null : draftNode.getId());
      flushToNode(draftNode, n);
      draftNode.setNode(n);
      nodeCount++;
    }

    // Push nodes in data structure
    for (NodeDraftGetter draftNode : container.getNodes()) {
      Node n = draftNode.getNode();
      NodeDraftGetter[] parents = draftNode.getParents();
      if (parents != null) {
        for (int i = 0; i < parents.length; i++) {
          Node parent = parents[i].getNode();
          graph.addNode(n, parent);
        }
      } else {
        graph.addNode(n);
      }
    }

    // Create all edges and push to data structure
    int edgeCount = 0;
    for (EdgeDraftGetter edge : container.getEdges()) {
      Node source = edge.getSource().getNode();
      Node target = edge.getTarget().getNode();
      Edge e = null;
      switch (container.getEdgeDefault()) {
        case DIRECTED:
          e =
              factory.newEdge(
                  edge.isAutoId() ? null : edge.getId(), source, target, edge.getWeight(), true);
          break;
        case UNDIRECTED:
          e =
              factory.newEdge(
                  edge.isAutoId() ? null : edge.getId(), source, target, edge.getWeight(), false);
          break;
        case MIXED:
          e =
              factory.newEdge(
                  edge.isAutoId() ? null : edge.getId(),
                  source,
                  target,
                  edge.getWeight(),
                  edge.getType().equals(EdgeType.UNDIRECTED) ? false : true);
          break;
      }

      flushToEdge(edge, e);
      edgeCount++;
      graph.addEdge(e);
    }
    workspace = null;
  }
コード例 #24
0
 @Override
 public int size() {
   int size = model.getEdgeTypeCount();
   return graph.getEdgeCount(0) == 0 ? size - 1 : size;
 }
コード例 #25
0
ファイル: Poets.java プロジェクト: gabrovski/knowevo
  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;
    }
  }