/**
  * Remove all edges connecting dead cells with others Call this after loading this entity from db
  * OR after config is changed. (i.e., after ratio or actualW or actualH is changed)
  */
 public void updateGraph() {
   cellContainer = new Cell[rowCount][colCount];
   initGraph();
   int row, col;
   for (DeadPoint dp : deadPoints) {
     col = getCorrespondingCol(dp.getX());
     row = getCorrespondingRow(dp.getY());
     if (valid(row, col)) g.removeVertex(cellContainer[row][col]);
   }
 }
  /**
   * Disable the cell containing the given point
   *
   * @param x
   * @param y
   */
  public void disableCell(int x, int y) {
    int col = getCorrespondingCol(x);
    int row = getCorrespondingRow(y);

    // If a cell is already dead, it wouldn't be disabled again; Do this to reduce the number of
    // dead points created
    if (valid(row, col) && !cellContainer[row][col].isDead()) {
      cellContainer[row][col].disableCell();
      deadPoints.add(new DeadPoint(x, y, this));

      // removing this cell from the graph and all of its touching edges
      g.removeVertex(cellContainer[row][col]);
    }
  }
Beispiel #3
0
  public static void main(String[] args) throws IOException {
    System.out.println("Enter parameters: N p_w p_r steps:");
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      String paras[] = reader.readLine().split(" ");
      N = Integer.parseInt(paras[0]);
      p_w = Float.parseFloat(paras[1]);
      p_r = Float.parseFloat(paras[2]);
      steps = Integer.parseInt(paras[3]);
    } catch (IOException e) {
      System.out.println("Error reading from user");
    }

    long start = System.currentTimeMillis();

    int simulations = 1;
    for (int t = 1; t <= simulations; t++) {

      // Initialization, generate an empty network of N nodes
      EIM dynamic = new EIM();
      G = new SimpleWeightedGraph<Integer, DefaultWeightedEdge>(DefaultWeightedEdge.class);
      for (int i = 0; i < N; i++) G.addVertex(i);
      String para = "EIM_" + Integer.toString(t);
      String folder = "files/" + "Networks" + "/";
      File f = new File(folder);
      if (f.exists() == false) {
        f.mkdirs();
      }

      // distribution of social space
      socialposition = dynamic.uniform(N);

      for (int s = 0; s < steps; s++) {
        int v = random.nextInt(N);
        // LA process - weighted random walk + link with social distance
        dynamic.localattach(v);
        // GA process
        // no edges, create one random link
        if (G.edgesOf(v).size() == 0) {
          dynamic.globalattach(v);
        } else {
          float prob = random.nextFloat();
          if (prob < p_r) dynamic.globalattach(v);
        }
        // ND process
        int d = random.nextInt(N);
        if (G.edgesOf(d).size() > 0) {
          float prob = random.nextFloat();
          if (prob < p_d) {
            Set<DefaultWeightedEdge> edges = new HashSet(G.edgesOf(d));
            G.removeAllEdges(edges);
          }
        }
        if (s % 100000 == 0) {
          System.out.print("Steps:" + Integer.toString(s) + "	");
          System.out.print("Edges:");
          System.out.print(G.edgeSet().size() + "	");
          System.out.println(
              "Avg_degree: "
                  + Float.toString((float) G.edgeSet().size() * 2 / G.vertexSet().size()));
        }
      }
      // delete isolate nodes
      ArrayList<Integer> nodelist = new ArrayList<Integer>();
      for (int node : G.vertexSet()) nodelist.add(node);
      for (int node : nodelist) {
        if (G.degreeOf(node) == 0) G.removeVertex(node);
      }
      System.out.print("Nodes:");
      System.out.println(G.vertexSet().size());
      System.out.print("Edges:");
      System.out.println(G.edgeSet().size());

      // get largest connected component
      Statistics stat = new Statistics();
      Graph G_LCC = stat.largestConnectedComponent(G);

      ExportGraph export = new ExportGraph();
      export.exportWPairs((SimpleWeightedGraph<Integer, DefaultWeightedEdge>) G_LCC, para, folder);
      System.out.print("Nodes in LCC:");
      System.out.println(G_LCC.vertexSet().size());
      System.out.print("Edges in LCC:");
      System.out.println(G_LCC.edgeSet().size());
      System.out.println("Avg_degree: " + Double.toString(stat.avg_degree(G_LCC)));
      System.out.println("Avg_clustering: " + Double.toString(stat.avg_clustering(G_LCC)));
      System.out.println(
          "Degree assortativity: " + Double.toString(stat.assortativityCoefficient(G_LCC)));
    }

    long elapsedTimeMillis = System.currentTimeMillis() - start;
    float elapsedTimeHour = elapsedTimeMillis / (60 * 60 * 1000F);
    System.out.print("Elapsed time: ");
    System.out.print(elapsedTimeHour);
    System.out.println(" hours.");
  }
  /**
   * Simulate next step for the given particle.
   *
   * @param nextPts
   * @param particleNum
   */
  public void simulateForwardStep(ArrayList<Point> nextPts, Particle thisParticle) {
    HashMap<Vertex, Point> thisObservedPosMap = new HashMap<Vertex, Point>();
    HashMap<Vertex, AntPath> thisAntPathMap = new HashMap<Vertex, AntPath>();

    thisParticle.currentFalsePositives = new ArrayList<Point>();
    for (Point pt : nextPts) {
      Vertex vx = new ObsVertex();
      thisObservedPosMap.put(vx, pt);
    }

    for (AntPath ap : thisParticle.getPaths()) {
      Vertex vx = new PathVertex();
      thisAntPathMap.put(vx, ap);
    }

    /*
     * Compute probability graph for this particle.
     */
    SimpleWeightedGraph<Vertex, DefaultWeightedComparableEdge> probabilityGraph =
        new SimpleWeightedGraph<Vertex, DefaultWeightedComparableEdge>(
            DefaultWeightedComparableEdge.class);
    ValueSortedMap<DefaultWeightedComparableEdge, Double> edgeMap =
        new ValueSortedMap<DefaultWeightedComparableEdge, Double>(true);
    computeLogProbabilityGraph(probabilityGraph, edgeMap, thisObservedPosMap, thisAntPathMap);

    //		displayLogProbabilityGraph(probabilityGraph,thisObservedPosMap,thisAntPathMap,vertexSums);

    /*
     * Generate new ant locations based on probability graph.  We do this by sampling the most likely event,
     * removing this event from the probability graph, updating the prob. graph, then repeating until all
     * observations/causes are accounted for.
     *
     * To do this (relatively) efficiently, we maintain a sorted hash-map of possible observation/cause pairs.
     * To avoid having to rescale the entire hash-map every step, we maintain the current sum of weights.
     *
     * We're also keeping track of the posterior log-probability of the simulated step.
     */

    double logprob = 0;
    int nfp = 0;
    int nfn = 0;

    int doOutput = 0;
    while (edgeMap.size() > 0) {

      /*
       * Sample an event from the probability graph.
       */

      DefaultWeightedComparableEdge event = sampleEdge(probabilityGraph, edgeMap);

      edgeMap.remove(event);
      double edgeWeight = probabilityGraph.getEdgeWeight(event);
      double thisLogProb = edgeWeight;
      logprob = logprob + thisLogProb;

      Vertex v1 = probabilityGraph.getEdgeSource(event);
      Vertex v2 = probabilityGraph.getEdgeTarget(event);

      if (doOutput > 0) {
        System.err.println("edgeWeight: " + edgeWeight);
        doOutput = outputInterestingStuff(v1, v2, probabilityGraph);
      }

      if (v1.getClass().equals(ObsVertex.class)) {
        assert (v2.getClass().equals(PathVertex.class));
        Vertex tv = v1;
        v1 = v2;
        v2 = tv;
      }

      /*
       * Update the probability graph.
       */
      if (!v1.equals(falsePositive)) {
        Set<DefaultWeightedComparableEdge> es = probabilityGraph.edgesOf(v1);
        for (DefaultWeightedComparableEdge ed : es) edgeMap.remove(ed);
        boolean tt = probabilityGraph.removeVertex(v1);
        assert (tt);
      } else {
        nfp += 1;
        thisParticle.currentFalsePositives.add(thisObservedPosMap.get(v2));
      }

      if (!v2.equals(falseNegative)) {
        Set<DefaultWeightedComparableEdge> es = probabilityGraph.edgesOf(v2);
        for (DefaultWeightedComparableEdge ed : es) edgeMap.remove(ed);
        boolean tt = probabilityGraph.removeVertex(v2);
        assert (tt);
      } else nfn += 1;

      // Utils.computeVertexSums(probabilityGraph,vertexSums);

      /*
       * Update AntPath trajectory.
       */

      if (!v1.equals(falsePositive)) {
        AntPath ap = thisAntPathMap.get(v1);
        assert (ap != null);
        Point obs = thisObservedPosMap.get(v2);

        Point newPos = new Point();
        double thislp = sampleConditionalPos(ap, obs, newPos) + thisLogProb;
        ap.updatePosition(newPos, obs, thislp);
      }

      /*
       * Compute likelihoods.
       */
    }
  }
 /**
  * Remove all nodes which are NOT in cells from graph g
  *
  * @param cells
  */
 private void filterGraph(ArrayList<Cell> cells) {
   for (int row = 0; row < rowCount; ++row)
     for (int col = 0; col < colCount; ++col)
       if (!cells.contains(cellContainer[row][col])) g.removeVertex(cellContainer[row][col]);
 }