简体   繁体   中英

Creating node with weight in java graph

I am creating a program to create a graph for bibliography dataset. The graph is directed, has Author node and Paper node, and has 2 types of edges (author to paper edge, paper to paper edge).

I want to get an input from you about whether or not what I am creating is making sense. Right now, it produces the right result when I want to get the outEdge and inEdge from and to a node. But im not sure if this implementation is correct in terms of the methods, designs, and algorithm.

Also, I have a problem with assigning weight to a node. I want to ask how can I do this as well. Right now, what I have tried is as follows:

for (String item : CandidateAuthorType1Unique) {
    double weight = Collections.frequency(CandidateAuthorType1, item);
    n.setWeight(item,weight);;
    System.out.println(n.getName() + " : " + n.getWeight());
}

However, after using setWeight , the getName() method returns null. This means that the weight assigned is not assigned to a certain item. I wonder how to update the weight a certain item.

If I use

for (String item : CandidateAuthorType1Unique) {
    double weight = Collections.frequency(CandidateAuthorType1, item);
    n = new Node(item,weight);
    System.out.println(n.getName() + " : " + n.getWeight());
}   

Does it mean that each time a new node n is created, the old n node will not be stored? How can I checked every node ever created and its weight?

I would like to ask for your input to this program. Any input would be really helpful for me. Thank you.

Main class: Ranker.java

import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.sql.*;

public class Ranker {

    static Graph g;
    static Node n;
    static Edge e;
    static HashMap nodeMap;   // maps Integer NodeIDs to Node object
    String id;
    double weight;

    Ranker() {
            g = new Graph();
            nodeMap = new HashMap();
            n = new Node(id,weight);
    }

    public static void main (String[] args) throws ClassNotFoundException, SQLException, IOException, IllegalArgumentException, IllegalAccessException{

        Ranker Ranker = new Ranker();
        Connection connect = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        HashMap nodeMap =  new HashMap();   // maps Integer NodeIDs to Node objects

        Class.forName("com.mysql.jdbc.Driver");
        connect = DriverManager.getConnection("jdbc:mysql://localhost/arnetminer?"+"user=root&password=1234");
        preparedStatement = connect.prepareStatement("Select fr,t,ty from subedge");

        resultSet = preparedStatement.executeQuery();
        int i=0;

        while(resultSet.next()) {
           g.addEdgeForIndexing(resultSet.getInt(1),resultSet.getInt(2),resultSet.getInt(3));
           i++;             
           System.out.println( "edges added to G = "+i);
        }       

        System.out.println("Loaded " + g.nodeCount() + " nodes.");

        buildNodes();

        System.out.println("Enter first author key:");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String authorkey1 = br.readLine(); 
        int authorID1 = Integer.parseInt(authorkey1);
        String AuthorID1 = "A"+authorID1;
        ArrayList<String> p1 = g.getOutEdgesToP(AuthorID1);
        System.out.println("P1 = " + p1);

        ArrayList<String> p2 = new ArrayList<String>();
        for (int j = 0; j<p1.size();j++){
            ArrayList<String> temp = g.getOutEdgesToP(p1.get(j));
            if (temp!=null)
            p2.addAll(temp);
        }
        System.out.println("P2 = " +p2);

        ArrayList<String> CandidateAuthorType1 = new ArrayList<String>();
        for (int k = 0; k<p2.size(); k++){
            ArrayList<String> temp = g.getInEdgesFromPtoA(p2.get(k));
            if(temp!=null)
                CandidateAuthorType1.addAll(temp);
        }
        System.out.println("Candidate Author Type 1= " + CandidateAuthorType1);

        ArrayList<String> CandidateAuthorType1Unique = removeDuplicates(CandidateAuthorType1);
        System.out.println("-----------------------------------------------");
        System.out.println("Candidate author type 1 and author node weight:");
        for (String item : CandidateAuthorType1Unique) {
            double weight = Collections.frequency(CandidateAuthorType1, item);
            n.setWeight(item,weight);;
            System.out.println(n.getName() + " : " + n.getWeight());
        }       

        ArrayList<String> CandidatePaperType1 = new ArrayList<String>();
        for (int l = 0; l<CandidateAuthorType1.size(); l++){
            ArrayList<String> temp = g.getOutEdgesToP(CandidateAuthorType1.get(l));
            if(temp!=null)
                CandidatePaperType1.addAll(temp);
        }
        System.out.println("Candidate Paper Type 1= " + CandidatePaperType1);
    }   


    private static ArrayList<String> removeDuplicates(ArrayList<String> element){
        ArrayList<String> result = new ArrayList<>();
        HashSet<String> set = new HashSet<>();
        for (String item : element) {
            if (!set.contains(item)) {
            result.add(item);
            set.add(item);
            }
        }
        return result;  
    }

    private static void buildNodes() 
    {
        String nodeID;
        double weight = 0;
        Node n;
        Iterator it = g.nodeIteratorInitial();
        while (it.hasNext()) {
          nodeID = (String) it.next(); 
          if (!nodeMap.containsKey(nodeID)){
              n = new Node(nodeID,weight);
              nodeMap.put(nodeID, 0);
          }
        }
    }
}

Graph.java

import java.lang.reflect.Field;
import java.util.*;

public class Graph {

    private HashSet<String>  nodeIDs;   
    public HashMap<Integer, String> nodeIDsWithTN;
    public HashMap<Integer, String> TNMap;  
    private HashMap<String, ArrayList<String>>  edges;
    private HashMap<String, ArrayList<String>>  reverse;
    private int numNodes;
    private int numEdges;
    private int numReverse;

    public Graph() {
        edges = new HashMap<String, ArrayList<String>>();
        reverse = new HashMap<String, ArrayList<String>>();
        nodeIDs = new HashSet<String>();
        nodeIDsWithTN = new HashMap<Integer, String>();
        TNMap = new HashMap<Integer, String>();
        new HashSet();
    }

    public void addEdgeForIndexing(int from, int to, int T) throws IllegalArgumentException, IllegalAccessException {
        String From = ""+from;
        String To = ""+to;
        int type = T; 
        if(T==1)
        {
            From="A"+from;
            To="P"+to;
        }
        else if(T==2)
        {
            From="P"+from;
            To="P"+to;
        }           
        else
            System.out.println("T ="+T+" value undefined");

            Edge e = new Edge(From,To,type);

            nodeIDs.add(e.From);
            nodeIDs.add(e.To);

            ArrayList<String> tmp = null;
            if (edges.containsKey(e.From))
              tmp = (ArrayList<String>) edges.get(e.From);
            else {
              tmp = new ArrayList<String>();
              edges.put(e.From,tmp);
            }
            tmp.add(e.To);

            ArrayList<String> tmp2 = null;
            if (reverse.containsKey(e.To))
              tmp2 = (ArrayList<String>) reverse.get(e.To);
            else {
              tmp2 = new ArrayList<String>();
              reverse.put(e.To,tmp2);
            }
            tmp2.add(e.From);
    }

    public int nodeCount() {
        if(nodeIDs.size() > 0) 
            return nodeIDs.size();
            // else return numNodes;
        return numEdges;
    }

    public int countInEdges(Integer key) {
        if (!reverse.containsKey(key)) return 0;
            return ((ArrayList<?>) reverse.get(key)).size();
    }

    public int countOutEdges(Integer key) {
        if (!edges.containsKey(key)) return 0;
            return ((ArrayList<?>) edges.get(key)).size();
    }

    public ArrayList<String> getInEdgesFromPtoA(String id) {
        if (!reverse.containsKey(id)) return null;  
            ArrayList<String> a = reverse.get(id);
            ArrayList<String> result = new ArrayList<String>();
                for(int j=0;j<a.size();j++){
                      if(a.get(j).startsWith("A")){
                          result.add(a.get(j));                           
                      }
                 }
        return result;
    }

    public ArrayList<String> getOutEdgesToP(String id) {
        if (!edges.containsKey(id)) return null;    
            ArrayList<String> a = edges.get(id);
            ArrayList<String> result = new ArrayList<String>();
            for(int j=0;j<a.size();j++){
              if(a.get(j).startsWith("P")){
              result.add(a.get(j));                           
              }
            }
        return result;
    }

    public Iterator<String> nodeIteratorInitial() {
        return nodeIDs.iterator();
    }
}

Edge.java

public class Edge {


    String From;
    String To;
    int type;
    private static int counter = 0;
    public Edge(String From, String To, int type) {
        this.From = new String(From);
        this.To = new String(To);
        this.type = type;
    //  System.out.println("edges added from " + From + " to " +  To + " with type "+ type);
    }

    public String getFrom(){
        return From;
    }

    public String getTo(){
        return To;
    }

    public int getType(){
        return type;
    }

    public void setFrom(String From){
        this.From = From;
    }

    public void setTo(String To){
        this.To = To;
    }

    public void setType(int type){
        this.type = type;
    }
}

Node.java

public class Node {

      String id;
      double weight;
      private static int counter = 0;

      public Node(String id,double weight) {
          this.id = id;
          this.weight = weight;;

      }

      public double getWeight(){
            return weight;
      }

      public String getName() {
           return id;
      }

      public void setWeight(String id, double weight){
         if (this.id==id){
          this.weight=weight;}
          System.out.println("The node " + id + " has weight " + weight);
      }


      public void setName(String id){
          this.id=id;
      }

}

As you are initialising n in the Ranker() constructor, when the constructor is called, the String id has not been assigned and therefore always contains the value null . Therefore your Node n also gets the id as null . This is the reason why the weight isn't updated as in your setWeight(String id, double weight) function, the new id is compared to null which always returns false therefore the weight doesn't get updated.

You could make the following changes in your code

1) Remove the n = new Node(id,weight) initialisation in your Ranker() constructor.

2) Add the following lines instead of n.setWeight(item,weight) in your main method in Ranker class.

if (n == null)
    n = new Node(item, weight);
n.setWeight(item, weight);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM