예제 #1
1
파일: Graph.java 프로젝트: karthikrk1/IADSA
  /**
   * Method to find the Euler Tour based on the Hierholzer's algorithm.
   *
   * @param g : Input graph for which the tour is to be found.
   * @return : Returns a list of edges that comprises of the Euler Tour.
   */
  public static List<Edge> findEulerTour(Graph<Vertex> g) {
    Vertex start = g.verts.get(1);
    Stack<Edge> forward = new Stack<Edge>();
    Stack<Edge> backtrack = new Stack<Edge>();
    Edge e = getUnvisitedEdge(start);
    while (e != null) {
      e.visited = true;
      forward.push(e);
      e = getUnvisitedEdge(e.To);
    }

    while (!(forward.isEmpty())) {
      e = forward.pop();
      backtrack.push(e);
      e = getUnvisitedEdge(e.From);
      while (e != null) {
        e.visited = true;
        forward.push(e);
        e = getUnvisitedEdge(e.To);
      }
    }

    List<Edge> path = new LinkedList<Edge>();
    while (!backtrack.isEmpty()) {
      Edge edge = backtrack.pop();
      path.add(edge);
    }
    return path;
  }
예제 #2
0
  /**
   * Sets the covariance for the a<->b edge to the given covariance, if within range. Otherwise does
   * nothing.
   *
   * @param a a <-> b
   * @param b a <-> b
   * @param covar The covariance of a <-> b.
   * @return true if the coefficent was set (i.e. was within range), false if not.
   */
  public boolean setErrorCovariance(Node a, Node b, final double covar) {
    Edge edge = Edges.bidirectedEdge(semGraph.getExogenous(a), semGraph.getExogenous(b));

    if (edgeParameters.get(edge) == null) {
      throw new IllegalArgumentException("Not a covariance parameter in this model: " + edge);
    }

    if (editingEdge == null || !edge.equals(editingEdge)) {
      range = getParameterRange(edge);
      editingEdge = edge;
    }

    if (covar > range.getLow() && covar < range.getHigh()) {
      edgeParameters.put(edge, covar);
      return true;
    } else {
      return false;
    }

    //        if (!paramInBounds(edge, coef)) {
    //            edgeParameters.put(edge, d);
    //            return false;
    //        }
    //
    //        edgeParameters.put(edge, coef);
    //        return true;

    //        if (!paramInBounds(edge, covar)) {
    //            edgeParameters.put(edge, d);
    //            return false;
    //        }
    //
    //        edgeParameters.put(edge, covar);
    //        return true;
  }
예제 #3
0
  public List<Lockset> getLockSets(Lockset ls) {
    for (Edge edge : edges) {
      if (edge.getEntry_lockset().equals(ls)) return edge.getExit_locksets();
    }

    return null;
  }
예제 #4
0
  @Override
  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // render all of the edges
    for (Edge e : graphEdges) e.render(g);
  }
  /** Specified in Node */
  protected Node removeNeighbour(Node neighbour) {
    Iterator it = edges.iterator();
    Edge next;
    while (it.hasNext()) {
      next = (Edge) it.next();
      if (next.to == neighbour) {
        it.remove();
        break;
      }
    }

    // collapse this node if it has degree 2 after removal of neighbour
    if (edges.size() == 2) {
      Edge e1 = (Edge) edges.getFirst();
      Edge e2 = (Edge) edges.getLast();
      Edge ne1, ne2;

      ne1 = e1.to.addNeighbour(e2.to);
      ne2 = e2.to.addNeighbour(e1.to);
      ne1.backedge = ne2;
      ne2.backedge = ne1;
      e1.to.removeNeighbour(this);
      return e2.to.removeNeighbour(this);
    }
    return this;
  }
예제 #6
0
  public void testAddingSelfLoops() {
    Graph graph = graphTest.getGraphInstance();
    if (graphTest.allowsSelfLoops) {
      List<String> ids = generateIds(3);
      Vertex v1 = graph.addVertex(convertId(ids.get(0)));
      Vertex v2 = graph.addVertex(convertId(ids.get(1)));
      Vertex v3 = graph.addVertex(convertId(ids.get(2)));
      graph.addEdge(null, v1, v1, convertId("is_self"));
      graph.addEdge(null, v2, v2, convertId("is_self"));
      graph.addEdge(null, v3, v3, convertId("is_self"));

      if (graphTest.supportsVertexIteration) assertEquals(3, count(graph.getVertices()));
      if (graphTest.supportsEdgeIteration) {
        assertEquals(3, count(graph.getEdges()));
        int counter = 0;
        for (Edge edge : graph.getEdges()) {
          counter++;
          assertEquals(edge.getInVertex(), edge.getOutVertex());
          assertEquals(edge.getInVertex().getId(), edge.getOutVertex().getId());
        }
        assertEquals(counter, 3);
      }
    }
    graph.shutdown();
  }
예제 #7
0
  /** This scales all the x values to be between 0 and 1. */
  private void scaleByMax() {
    // ammendment to what i may have commented before
    // this takes the lowest x and highest x  and uses that as the scaling
    // factor
    double l_x = 5000, h_x = -5000;
    for (int noa = 0; noa < m_groupNum; noa++) {
      if (l_x > m_groups[noa].m_left) {
        l_x = m_groups[noa].m_left;
      }

      if (h_x < m_groups[noa].m_right) {
        h_x = m_groups[noa].m_right;
      }
    }

    Edge e;
    Node r, s;
    double m_scale = h_x - l_x + 1;
    if (m_groupNum > 0) {
      r = m_groups[0].m_p;
      r.setCenter((r.getCenter() - l_x) / m_scale);
      // System.out.println("from scaler " + l_x + " " + m_scale);
      for (int noa = 0; noa < m_groupNum; noa++) {
        r = m_groups[noa].m_p;
        for (int nob = 0; (e = r.getChild(nob)) != null; nob++) {
          s = e.getTarget();
          if (s.getParent(0) == e) {
            s.setCenter((s.getCenter() - l_x) / m_scale);
          }
        }
      }
    }
  }
예제 #8
0
  @Override
  public boolean hasNext() {
    // Multiple hasNext calls with no next...hasNext still true
    if (nextEdge != null) return true;

    while (internalIterator.hasNext()) {
      Edge edge = internalIterator.next();
      Object edgeType = edge.getType();

      if (negate) {
        // When edgeType or type is null compare them directly. Otherwise compare them using equals
        if ((edgeType != null && !edgeType.equals(type))
            || (edgeType == null && edgeType != type)) {
          nextEdge = edge;
          return true;
        }
        // When edgeType or type is null compare them directly. Otherwise compare them using equals
      } else if ((edgeType != null && edgeType.equals(type))
          || (edgeType == null && edgeType == type)) {
        nextEdge = edge;
        return true;
      }
    }

    return false;
  }
예제 #9
0
 /**
  * It returns the sum of the <code>characteristic</code> given value in the Edges of the path.
  *
  * @param characteristic The characteristic.
  * @return Sum of the characteristics.
  */
 public Double getPathWeight(String characteristic) {
   double d = 0;
   for (Edge l : edgePath) {
     d += (Double) l.getAttribute(characteristic, Number.class);
   }
   return d;
 }
예제 #10
0
  private void saveMenuItemActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_saveMenuItemActionPerformed

    this.jTextStatus.setText("");
    if (this.pnGraph.listEdges.isEmpty() && this.pnGraph.listVertexs.isEmpty()) {
      this.jTextStatus.setText("Empty graph, not save");
      return;
    }
    if (this.jSaveFileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
      File file = this.jSaveFileChooser.getSelectedFile();
      try {
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        try {
          for (Vertex Vertex : this.pnGraph.listVertexs) {
            output.write(
                String.format(
                    "Vertex:%d:%d:%d", Vertex.getData(), Vertex.getX_cor(), Vertex.getY_cor()));
            output.newLine();
          }
          for (Edge edge : this.pnGraph.listEdges) {
            output.write(
                String.format(
                    "Edge:%d:%d:%d",
                    edge.getHead().getData(), edge.getTail().getData(), edge.getLength()));
            output.newLine();
          }
          this.jTextStatus.setText("Save graph successfully");
        } finally {
          output.close();
        }
      } catch (IOException e) {
      }
    }
  } // GEN-LAST:event_saveMenuItemActionPerformed
예제 #11
0
파일: UpdateEdge.java 프로젝트: kornl/gMCP
  protected JPanel getMainPanel() {
    JPanel panel = new JPanel();
    String cols = "5dlu, fill:pref:grow, 5dlu, fill:pref:grow, 5dlu";
    String rows = "5dlu, pref, 5dlu, pref, 5dlu";

    FormLayout layout = new FormLayout(cols, rows);
    panel.setLayout(layout);
    CellConstraints cc = new CellConstraints();

    panel.add(new JLabel("Weight for edge:"), cc.xy(2, 2));

    String text = edge.getWS();

    tf = new JTextField(text);
    tf.addActionListener(this);
    panel.add(tf, cc.xy(4, 2));

    jcbAnchored.addActionListener(this);
    jcbAnchored.setSelected(edge.isFixed());
    if (!Configuration.getInstance().getGeneralConfig().getUnAnchor()) {
      panel.add(jcbAnchored, cc.xyw(2, 4, 3));
    }

    return panel;
  }
예제 #12
0
 /**
  * Get the nodes at the other ends of outgoing edges of this node.
  *
  * @return a list of child nodes
  */
 public List<Node> getChildNodes() {
   LinkedList<Node> childNodes = new LinkedList<Node>();
   for (Edge edge : leavingEdges) {
     childNodes.add(edge.getToNode());
   }
   return childNodes;
 }
예제 #13
0
  @Test
  public void testDistance() {
    Node n1 = new Node(0, 0, 0);
    Node n2 = new Node(0, 1, 1);
    Edge e1 = new Edge(n1, n2);
    Assert.assertEquals(e1.getDistance(), 1, DELTA);

    n1 = new Node(0, 0, 0);
    n2 = new Node(0, 0, 1);
    Edge e2 = new Edge(n1, n2);
    Assert.assertEquals(e2.getDistance(), 0, DELTA);

    n1 = new Node(2, -1, 0);
    n2 = new Node(-2, 2, 1);
    Edge e3 = new Edge(n1, n2);
    Assert.assertEquals(e3.getDistance(), 5, DELTA);

    n1 = new Node(3, 5, 0);
    n2 = new Node(1, 2, 1);
    Edge e4 = new Edge(n1, n2);
    Assert.assertEquals(e4.getDistance(), 4, DELTA);

    n1 = new Node(3, 5, 0);
    n2 = new Node(1, 1, 1);
    Edge e5 = new Edge(n1, n2);
    Assert.assertEquals(e5.getDistance(), 4, DELTA);
  }
    @Override
    public Boolean call() throws Exception {
      GraphManager manager = factory.createEdgeManager(scope);

      final long startTime = System.currentTimeMillis();

      for (long i = 0;
          i < writeLimit || System.currentTimeMillis() - startTime < minExecutionTime;
          i++) {

        Edge edge = generator.newEdge();

        Edge returned = manager.writeEdge(edge).toBlocking().last();

        assertNotNull("Returned has a version", returned.getTimestamp());

        writeMeter.mark();

        writeCounter.incrementAndGet();

        if (i % 1000 == 0) {
          logger.info("   Wrote: " + i);
        }
      }

      return true;
    }
예제 #15
0
  @Override
  public void remove(I targetVertexId) {
    // Note that this is very expensive (deserializes all edges).
    ByteArrayEdgeIterator iterator = new ByteArrayEdgeIterator();
    List<Integer> foundStartOffsets = new LinkedList<Integer>();
    List<Integer> foundEndOffsets = new LinkedList<Integer>();
    int lastStartOffset = 0;
    while (iterator.hasNext()) {
      Edge<I, E> edge = iterator.next();
      if (edge.getTargetVertexId().equals(targetVertexId)) {
        foundStartOffsets.add(lastStartOffset);
        foundEndOffsets.add(iterator.extendedDataInput.getPos());
        --edgeCount;
      }
      lastStartOffset = iterator.extendedDataInput.getPos();
    }
    foundStartOffsets.add(serializedEdgesBytesUsed);

    Iterator<Integer> foundStartOffsetIter = foundStartOffsets.iterator();
    Integer foundStartOffset = foundStartOffsetIter.next();
    for (Integer foundEndOffset : foundEndOffsets) {
      Integer nextFoundStartOffset = foundStartOffsetIter.next();
      System.arraycopy(
          serializedEdges,
          foundEndOffset,
          serializedEdges,
          foundStartOffset,
          nextFoundStartOffset - foundEndOffset);
      serializedEdgesBytesUsed -= foundEndOffset - foundStartOffset;
      foundStartOffset = nextFoundStartOffset;
    }
  }
예제 #16
0
파일: Topology.java 프로젝트: zjusbo/cs433
 /**
  * Returns the edge between a and b, if one exists and it is live. Returns null otherwise
  *
  * @param a Int specifying a node
  * @param b Int specifying a node
  * @return The live edge between a and b. If one does not exist then null is returned
  */
 public Edge getLiveEdge(int a, int b) {
   Edge e = getEdge(a, b);
   if (e == null || !e.isLive() || !this.isNodeAlive(a) || !this.isNodeAlive(b)) {
     return null;
   }
   return e;
 }
예제 #17
0
  @Override
  public void addEdge(Edge edge) {
    checkInTransaction();
    if (edge == null) {
      throw new IllegalArgumentException("edge must not be null");
    }
    Vertex source = edge.getSource();
    Vertex target = edge.getTarget();
    // Validate to ensure the model does not become corrupted.
    int si = vertexList.indexOf(source);
    int ti = vertexList.indexOf(target);
    if (si == -1 || ti == -1 || si >= adjacencies.size() || ti >= adjacencies.size()) {
      throw new IllegalStateException("vertices not in model");
    }
    if (source.equals(target)) {
      throw new IllegalStateException("edge endpoints are same");
    }
    if (findEdge(source, target) != null
        || (!edge.isDirected() && findEdge(target, source) != null)) {
      throw new IllegalArgumentException("edge already exists");
    }

    // Add the new edge to the list and make the source vertex
    // adjacent to the target vertex. If the edge is undirected,
    // then make target adjacent to source, as well.
    edgeList.add(edge);
    addAdjacency(source, target);
    if (!edge.isDirected()) {
      addAdjacency(target, source);
    }
    fireModelEvent(new ModelEvent(this, ModelEventType.EDGE_ADDED));
    fireUndoableEdit(new EdgeAddUndoableEdit(this, edge));
  }
예제 #18
0
  // min costs or -1 if flow not feasible
  // graph is changed
  int getMinCostFlow(Map<Integer, Edge>[] graph, int start, int goal, int flowSize) {
    int res = 0;
    while (flowSize > 0) {
      ShortestWayResult shortest = getShortestWay(graph, start, goal);

      if (shortest == null) // Fehler, flow not feasible
      return -1;

      // Update way
      int newFlow = Math.min(shortest.minCapacity, flowSize);
      flowSize -= newFlow;
      res += shortest.costForOne * newFlow;
      Iterator<Integer> it = shortest.way.iterator();
      int akt = it.next();
      while (it.hasNext()) {
        int next = it.next();
        Edge e = graph[akt].remove(next);
        e.capacity -= newFlow;
        if (e.capacity > 0) graph[akt].put(next, e);

        Edge edge = graph[next].get(akt);
        if (edge == null) {
          Edge newEdge = new Edge(newFlow, -e.cost);
          graph[next].put(akt, newEdge);
        } else {
          edge.capacity += newFlow;
        }
        akt = next;
      }
    }
    return res;
  }
예제 #19
0
  /**
   * This will set initial places for the x coord of the nodes.
   *
   * @param start The `number for the first group to start on (I think).
   */
  private void xPlacer(int start) {
    // this can be one of a few x_placers (the first)
    // it will work by placing 1 space inbetween each node
    // ie the first at 0 the second at 1 and so on
    // then it will add to this value the place of the parent
    // node - half of the size
    // i will break this up into several functions
    // first the gap setter;
    // then the shifter
    // it will require a vector shift function added to the node class
    // i will write an additional shifter for the untangler
    // for its particular situation

    Node r;
    Edge e;
    if (m_groupNum > 0) {
      m_groups[0].m_p.setCenter(0);
      for (int noa = start; noa < m_groupNum; noa++) {
        int nob, alter = 0;
        double c = m_groups[noa].m_gap;
        r = m_groups[noa].m_p;
        for (nob = 0; (e = r.getChild(nob)) != null; nob++) {
          if (e.getTarget().getParent(0) == e) {
            e.getTarget().setCenter(nob * c);
          } else {
            alter++;
          }
        }
        m_groups[noa].m_size = (nob - 1 - alter) * c;
        xShift(noa);
      }
    }
  }
예제 #20
0
 private void visit(Set<Edge> visited) {
   boolean fixpoint = false;
   while (!fixpoint) {
     fixpoint = true;
     Vector<Vector<Edge>> newPaths = new Vector<Vector<Edge>>();
     Vector<Vector<Edge>> delPaths = new Vector<Vector<Edge>>();
     for (Vector<Edge> path : paths) {
       Edge e = path.lastElement();
       boolean pathExtended = false;
       for (Edge succ : e.getTarget().getSucc()) {
         if (!visited.contains(succ)) {
           Vector<Edge> newPath = new Vector<Edge>();
           newPath.addAll(path);
           newPath.add(succ);
           newPaths.add(newPath);
           visited.add(succ);
           pathExtended = true;
           fixpoint = false;
         }
       }
       if (pathExtended) delPaths.add(path);
     }
     for (Vector<Edge> path : delPaths) paths.remove(path);
     paths.addAll(newPaths);
   }
 }
예제 #21
0
  /**
   * This scales the x values to between 0 and 1 for each individual line rather than doing them all
   * at once.
   */
  private void scaleByInd() {
    // ammendment to what i may have commented before
    // this takes the lowest x and highest x  on each line and uses that for
    // the line in question
    double l_x, h_x;

    Edge e;
    Node r, s;
    r = m_groups[0].m_p;
    r.setCenter(.5);
    double m_scale;
    for (int noa = 0; noa < m_levelNum; noa++) {
      l_x = m_groups[m_levels[noa].m_start].m_left;
      h_x = m_groups[m_levels[noa].m_end].m_right;
      m_scale = h_x - l_x + 1;
      for (int nob = m_levels[noa].m_start; nob <= m_levels[noa].m_end; nob++) {
        r = m_groups[nob].m_p;
        for (int noc = 0; (e = r.getChild(noc)) != null; noc++) {
          s = e.getTarget();
          if (s.getParent(0) == e) {
            s.setCenter((s.getCenter() - l_x) / m_scale);
          }
        }
      }
    }
  }
예제 #22
0
파일: Graph.java 프로젝트: redbug/IMCrowd
 public void drawEdges(Graphics2D g) {
   synchronized (edges) {
     for (Edge e : edges) {
       e.drawLine(g);
     }
   }
 }
예제 #23
0
 private void writeEdges(Writer writer, List<Edge> edges, Map<Vertex, Integer> ids)
     throws IOException {
   for (Edge e : edges) {
     writeEdgeProperties(
         writer, e, ids.get(e.getVertex(Direction.OUT)), ids.get(e.getVertex(Direction.IN)));
   }
 }
예제 #24
0
 Site rightRegion(Halfedge he, Site bottomMostSite) {
   Edge edge = he.edge;
   if (edge == null) {
     return bottomMostSite;
   }
   return edge.site(LR.other(he.leftRight));
 }
예제 #25
0
  private Graph condense(Graph mimStructure, Graph mimbuildStructure) {
    //        System.out.println("Uncondensed: " + mimbuildStructure);

    Map<Node, Node> substitutions = new HashMap<Node, Node>();

    for (Node node : mimbuildStructure.getNodes()) {
      for (Node _node : mimStructure.getNodes()) {
        if (node.getName().startsWith(_node.getName())) {
          substitutions.put(node, _node);
          break;
        }

        substitutions.put(node, node);
      }
    }

    HashSet<Node> nodes = new HashSet<Node>(substitutions.values());
    Graph graph = new EdgeListGraph(new ArrayList<Node>(nodes));

    for (Edge edge : mimbuildStructure.getEdges()) {
      Node node1 = substitutions.get(edge.getNode1());
      Node node2 = substitutions.get(edge.getNode2());

      if (node1 == node2) continue;

      if (graph.isAdjacentTo(node1, node2)) continue;

      graph.addEdge(new Edge(node1, node2, edge.getEndpoint1(), edge.getEndpoint2()));
    }

    //        System.out.println("Condensed: " + graph);

    return graph;
  }
예제 #26
0
파일: Lofs.java 프로젝트: jdramsey/tetrad
  public Graph orient() {
    Graph skeleton = GraphUtils.undirectedGraph(getPattern());
    Graph graph = new EdgeListGraph(skeleton.getNodes());

    List<Node> nodes = skeleton.getNodes();
    //        Collections.shuffle(nodes);

    if (isR1Done()) {
      ruleR1(skeleton, graph, nodes);
    }

    for (Edge edge : skeleton.getEdges()) {
      if (!graph.isAdjacentTo(edge.getNode1(), edge.getNode2())) {
        graph.addUndirectedEdge(edge.getNode1(), edge.getNode2());
      }
    }

    if (isR2Done()) {
      ruleR2(skeleton, graph);
    }

    if (isMeekDone()) {
      new MeekRules().orientImplied(graph);
    }

    return graph;
  }
예제 #27
0
  @Override
  public boolean next() {
    /* --- create the next extension */
    Node s, d, p[]; /* to traverse/access the nodes */
    Edge e; /* to traverse/access the edges */

    /* --- continue an old extension --- */
    if (((this.mode & EQVARS) != 0)
        && (this.pos1 >= 0) /* if there is another equivalent */
        && this.variant()) /* variant of the previous ring, */
      return true; /* return "extension successful" */
    if (((this.mode & RING) != 0)
        && (this.all != 0) /* if there is another ring flag */
        && this.ring()) /* and some ring is admissible, */
      return true; /* return "extension successful" */
    if (((this.mode & CHAIN) != 0)
        && (this.size == 0) /* if last extension was an edge and */
        && this.chain()) /* it can be extended into a chain, */
      return true; /* return "extension successful" */

    /* --- find a new extension --- */
    p = this.emb.nodes; /* get the nodes of the embedding */
    s = p[this.src]; /* and the current anchor node */
    while (true) {
        /* find the next unprocessed edge */
      while (++this.idx >= s.deg) {
        if (++this.src >= p.length) {
          this.emb.mark(-1); /* if node's last edge is processed, */
          return false; /* go to the next extendable node */
        } /* and if there is none, abort */
        s = p[this.src]; /* get the new anchor node and */
        this.idx = -1; /* start with the first edge */
      }
      e = s.edges[this.idx]; /* get the next edge of this node */
      if (e.mark != -1) /* if the edge is in the embedding */
        continue; /* or excluded, it cannot be added */
      d = (s != e.src) ? e.src : e.dst;
      if ((d.mark < 0) /* if node is not in the embedding */
          && (p.length + this.frag.chcnt >= this.max))
        continue; /* check whether a new node is ok */
      this.dst = (d.mark < 0) ? p.length : d.mark;
      if (this.dst <= this.src) /* skip edges closing a ring that */
        continue; /* lead "backward" in the fragment */
      this.nodes[0] = s; /* note the anchor node and the */
      this.edges[0] = e; /* (first) edge of the extension */
      this.nodes[1] = d; /* note the destination node */
      if (e.isInRing() /* if a ring extension is possible */ && ((this.mode & RING) != 0)) {
        this.all = e.getRings(); /* note the ring flags and */
        this.curr = 1; /* init. the current ring flag */
        if (this.ring()) return true;
        continue; /* if some ring is admissible, */
      } /* return "extension successful" */
      if ((this.mode & EDGE) == 0) continue; /* check for edge extensions */
      this.nodecnt = (d.mark < 0) ? 1 : 0;
      this.edgecnt = 1; /* zero/one new node, one new edge */
      this.size = 0; /* clear the extension size */
      this.chcnt = this.frag.chcnt;
      return true; /* copy the chain counter and */
    } /* return "extension successful" */
  } /* next() */
예제 #28
0
  private void cornerEdgeCollision(Corner corner, Edge edge) {
    // check for the uphill vector of both edges being too similar (parallel
    // edges)
    // also rejects e == corner.nextL or corner.prevL
    // updated to take into account vertical edges - will always have same
    // uphill! - (so we check edge direction too)
    if ((edge.uphill.angle(corner.prevL.uphill) < 0.0001
            && edge.direction().angle(corner.prevL.uphill) < 0.0001)
        || (edge.uphill.angle(corner.nextL.uphill) < 0.0001
            && edge.direction().angle(corner.nextL.uphill) < 0.0001)) return;

    Tuple3d res = null;
    try {
      // sometimes locks up here if edge.linear form has NaN components.
      if (corner.prevL.linearForm.hasNaN()
          || corner.nextL.linearForm.hasNaN()
          || edge.linearForm.hasNaN()) throw new Error();
      res = edge.linearForm.collide(corner.prevL.linearForm, corner.nextL.linearForm);
    } catch (Throwable f) {
      // trying to collide parallel-ish faces, don't bother
      // System.err.println( "didn't like colliding " + edge + " and " +
      // corner.prevL + " and " + corner.nextL );
      return;
    }

    if (res != null) {
      // cheap reject: if collision is equal or below (not the correct
      // place to check) the corner, don't bother with it
      if (res.z < corner.z || res.z < edge.start.z) return;

      EdgeCollision ec = new EdgeCollision(new Point3d(res), corner.prevL, corner.nextL, edge);

      if (!skel.seen.contains(ec)) faceEvents.offer(ec);
    }
  }
예제 #29
0
  public GraphIndex(Graph graph) {
    LOG.info("Indexing graph...");

    for (String feedId : graph.getFeedIds()) {
      for (Agency agency : graph.getAgencies(feedId)) {
        Map<String, Agency> agencyForId = agenciesForFeedId.getOrDefault(feedId, new HashMap<>());
        agencyForId.put(agency.getId(), agency);
        this.agenciesForFeedId.put(feedId, agencyForId);
      }
    }

    Collection<Edge> edges = graph.getEdges();
    /* We will keep a separate set of all vertices in case some have the same label.
     * Maybe we should just guarantee unique labels. */
    Set<Vertex> vertices = Sets.newHashSet();
    for (Edge edge : edges) {
      vertices.add(edge.getFromVertex());
      vertices.add(edge.getToVertex());
      if (edge instanceof TablePatternEdge) {
        TablePatternEdge patternEdge = (TablePatternEdge) edge;
        TripPattern pattern = patternEdge.getPattern();
        patternForId.put(pattern.code, pattern);
      }
    }
    for (Vertex vertex : vertices) {
      vertexForId.put(vertex.getLabel(), vertex);
      if (vertex instanceof TransitStop) {
        TransitStop transitStop = (TransitStop) vertex;
        Stop stop = transitStop.getStop();
        stopForId.put(stop.getId(), stop);
        stopVertexForStop.put(stop, transitStop);
        stopsForParentStation.put(stop.getParentStation(), stop);
      }
    }
    for (TransitStop stopVertex : stopVertexForStop.values()) {
      Envelope envelope = new Envelope(stopVertex.getCoordinate());
      stopSpatialIndex.insert(envelope, stopVertex);
    }
    for (TripPattern pattern : patternForId.values()) {
      patternsForFeedId.put(pattern.getFeedId(), pattern);
      patternsForRoute.put(pattern.route, pattern);

      for (Trip trip : pattern.getTrips()) {
        patternForTrip.put(trip, pattern);
        tripForId.put(trip.getId(), trip);
      }
      for (Stop stop : pattern.getStops()) {
        patternsForStop.put(stop, pattern);
      }
    }
    for (Route route : patternsForRoute.asMap().keySet()) {
      routeForId.put(route.getId(), route);
    }

    // Copy these two service indexes from the graph until we have better ones.
    calendarService = graph.getCalendarService();
    serviceCodes = graph.serviceCodes;
    this.graph = graph;
    LOG.info("Done indexing graph.");
  }
예제 #30
0
  /**
   * Sets the coefficient for the a->b edge to the given coefficient, if within range. Otherwise
   * does nothing.
   *
   * @param a a -> b
   * @param b a -> b
   * @param coef The coefficient of a -> b.
   * @return true if the coefficent was set (i.e. was within range), false if not.
   */
  public boolean setEdgeCoefficient(Node a, Node b, final double coef) {
    Edge edge = Edges.directedEdge(a, b);

    if (edgeParameters.get(edge) == null) {
      throw new NullPointerException("Not a coefficient parameter in this model: " + edge);
    }

    if (editingEdge == null || !edge.equals(editingEdge)) {
      range = getParameterRange(edge);
      editingEdge = edge;
    }

    if (coef > range.getLow() && coef < range.getHigh()) {
      edgeParameters.put(edge, coef);
      return true;
    }

    return false;

    //        if (!paramInBounds(edge, coef)) {
    //            edgeParameters.put(edge, d);
    //            return false;
    //        }
    //
    //        edgeParameters.put(edge, coef);
    //        return true;
  }