Example #1
0
 /** Test if errors with expressions also set the error flag on the node. */
 public void testExpressionError() {
   Node n = numberNode.newInstance(testLibrary, "number1");
   n.setExpression("value", "***");
   try {
     n.update();
     fail("Should have caused an exception.");
   } catch (ProcessingError e) {
     assertTrue(e.getCause().toString().toLowerCase().contains("cannot compile expression"));
     assertTrue(n.hasError());
     // As stated in Node#update(ProcessingContext), even if an error occurred the node is still
     // marked as clean
     // and events are fired. It is important to mark the node as clean so that subsequent changes
     // to the node
     // mark it as dirty, triggering an event. This allows you to fix the cause of the error in the
     // node.
     assertFalse(n.isDirty());
     assertNull(n.getOutputValue());
   }
   n.setExpression("value", "10 + 1");
   assertTrue(n.isDirty());
   n.update();
   assertFalse(n.hasError());
   assertFalse(n.isDirty());
   assertEquals(11, n.getOutputValue());
 }
Example #2
0
 /** Test if setting a stamp expressions marks the correct nodes as dirty. */
 public void testStampExpression() {
   Node number1 = numberNode.newInstance(testLibrary, "number1");
   Node stamp1 = Node.ROOT_NODE.newInstance(testLibrary, "stamp1", Integer.class);
   stamp1.addPort("value");
   stamp1.getPort("value").connect(number1);
   // The code prepares upstream dependencies for stamping, processes them and negates the output.
   String stampCode =
       "def cook(self):\n"
           + "  context.put('my_a', 99)\n"
           + "  self.node.stampDirty()\n"
           + "  self.node.updateDependencies(context)\n"
           + "  return -self.value # Negate the output";
   stamp1.setValue("_code", new PythonCode(stampCode));
   Parameter pValue = number1.getParameter("value");
   // Set number1 to a regular value. This should not influence the stamp operation.
   pValue.set(12);
   stamp1.update();
   assertEquals(-12, stamp1.getOutputValue());
   // Set number1 to an expression. Since we're not using stamp, nothing strange should happen to
   // the output.
   pValue.setExpression("2 + 1");
   stamp1.update();
   assertEquals(-3, stamp1.getOutputValue());
   // Set number1 to an unknown stamp expression. The default value will be picked.
   pValue.setExpression("stamp(\"xxx\", 19)");
   stamp1.update();
   assertEquals(-19, stamp1.getOutputValue());
   // Set number1 to the my_a stamp expression. The expression will be picked up.
   pValue.setExpression("stamp(\"my_a\", 33)");
   stamp1.update();
   assertEquals(-99, stamp1.getOutputValue());
 }
Example #3
0
  public void testBasicUsage() {
    Node dotNode = Node.ROOT_NODE.newInstance(testLibrary, "dotNode");
    dotNode.addParameter("x", Parameter.Type.FLOAT);
    dotNode.addParameter("y", Parameter.Type.FLOAT);
    dotNode.setValue("_code", new JavaMethodWrapper(getClass(), "_dot"));
    dotNode.addParameter("_output", Parameter.Type.STRING);

    // Check default values
    assertEquals(0F, dotNode.getValue("x"));
    assertEquals(0F, dotNode.getValue("y"));
    assertEquals("", dotNode.getValue("_output"));

    // Process
    dotNode.update();
    assertEquals("dot(0.0,0.0)", dotNode.getOutputValue());

    // Create instance and change values
    Node dotInstance = dotNode.newInstance(testLibrary, "dotInstance");
    dotInstance.setValue("x", 25F);
    dotInstance.setValue("y", 42F);
    dotInstance.update();
    assertEquals("dot(25.0,42.0)", dotInstance.getOutputValue());

    // Check that original hasn't changed
    assertEquals(0F, dotNode.asFloat("x"));
    assertEquals(0F, dotNode.asFloat("y"));
    assertEquals("dot(0.0,0.0)", dotNode.getOutputValue());

    // Now let the instance use its own code
    dotInstance.setValue("_code", new JavaMethodWrapper(getClass(), "_dot2"));
    dotInstance.update();
    assertEquals("dot2(25.0,42.0)", dotInstance.getOutputValue());
  }
Example #4
0
  private void runSimulation(Node leaf) {
    Board board = (Board) DeepCopy.copy(leaf.board);
    // Keep track of all moves made for RAVE updates
    boolean[][][] moves = new boolean[board.size][board.size][3];
    Move m1, m2;
    Point p1, p2;
    while (true) {
      m1 = simPolicy.getMove(board);
      p1 = (m1 == null ? null : m1.point);
      board.addStone(board.turn, p1);
      if (p1 != null) {
        moves[p1.x][p1.y][board.turn.ordinal()] = true;
        board.prevAtariedChains = m1.simFeatures.prevAtariedChains;
        board.prevTwoLibbedChains = m1.simFeatures.prevTwoLibbedChains;
      }

      //			board.printBoard();
      //			System.out.println();
      //			board.printLiberties();
      //			board.printLegalMoves();
      //			System.out.println(board.turn);

      m2 = simPolicy.getMove(board);
      p2 = (m2 == null ? null : m2.point);
      board.addStone(board.turn, p2);
      if (p2 != null) {
        moves[p2.x][p2.y][board.turn.ordinal()] = true;
        board.prevAtariedChains = m2.simFeatures.prevAtariedChains;
        board.prevTwoLibbedChains = m2.simFeatures.prevTwoLibbedChains;
      }

      //			board.printBoard();
      //			System.out.println();
      //			board.printLiberties();
      //			board.printLegalMoves();
      //			System.out.println(board.turn);

      if (p1 == null && p2 == null) break;
    }

    Score score = new Score(board);
    if (score.whiteScore > score.blackScore) {
      synchronized (lock) {
        leaf.update(Color.WHITE, board, moves);
      }
    } else {
      synchronized (lock) {
        leaf.update(Color.BLACK, board, moves);
      }
    }
  }
Example #5
0
 public void testDirty() {
   Node n = numberNode.newInstance(testLibrary, "number1");
   assertTrue(n.isDirty());
   n.update();
   assertFalse(n.isDirty());
   n.setValue("value", 12);
   assertTrue(n.isDirty());
   n.update();
   assertFalse(n.isDirty());
   n.getParameter("value").set(13);
   assertTrue(n.isDirty());
   n.update();
   assertFalse(n.isDirty());
 }
Example #6
0
 public void testError() {
   Node bad = addDirectNode.newInstance(testLibrary, "bad");
   TestDirtyListener listener = new TestDirtyListener();
   bad.addDirtyListener(listener);
   bad.setValue("v1", 12);
   bad.setValue("v2", 3);
   // Since the node starts out as dirty, setting values doesn't increase the counter.
   assertEquals(0, listener.dirtyCounter);
   // This code inherits the default code, which doesn't throw an error.
   bad.update();
   assertEquals(15, bad.getOutputValue());
   // Updating the code marks it as clean.
   assertFalse(bad.isDirty());
   assertEquals(1, listener.updatedCounter);
   assertEquals(0, listener.dirtyCounter);
   // This code causes a division by zero.
   bad.setValue("_code", new PythonCode("def cook(self):\n  return 1 / 0"));
   assertEquals(1, listener.dirtyCounter);
   // We just changed a parameter value, so the node is dirty.
   assertTrue(bad.isDirty());
   // Processing will fail.
   assertProcessingError(bad, "integer division or modulo by zero");
   // After processing failed, events are still called,
   // and the node is marked clean. Output is set to null.
   assertFalse(bad.isDirty());
   assertNull(bad.getOutputValue());
   assertEquals(2, listener.updatedCounter);
   assertEquals(1, listener.dirtyCounter);
 }
 private void checkNodeValidity(@NotNull DefaultMutableTreeNode node) {
   Enumeration enumeration = node.children();
   while (enumeration.hasMoreElements()) {
     checkNodeValidity((DefaultMutableTreeNode) enumeration.nextElement());
   }
   if (node instanceof Node && node != getModelRoot()) ((Node) node).update(this);
 }
Example #8
0
 public void testBasicClone() {
   Node myNode = Node.ROOT_NODE.newInstance(testLibrary, "myNode");
   myNode.setValue("_code", new JavaMethodWrapper(getClass(), "_addParameter"));
   myNode.update();
   assertTrue(myNode.hasParameter("myparam"));
   assertEquals("myvalue", myNode.getValue("myparam"));
 }
  Node ensureMaster() {
    Node n = getMasterNode();
    if (n != null) {
      n.update();
      if (n._isMaster) return n;
    }

    if (_lastPrimarySignal != null) {
      n = findNode(_lastPrimarySignal);
      n.update();
      if (n._isMaster) return n;
    }

    updateAll();
    return getMasterNode();
  }
Example #10
0
  /**
   * Updates the game state to the next tick. First applies the messages past in as arguments, then
   * updates the nodes, then the lanes, then checks for a winning player.
   *
   * @param messages the messages to apply for this game state tick
   */
  public void update(Message[] messages) {
    this.validateLock();

    for (Message m : messages) m.apply(this);

    this.validateLock();

    for (Node n : map.getNodes()) n.update();

    this.validateLock();

    for (Lane l : map.getLanes()) l.update();

    this.validateLock();

    double energyToAdd = ENERGY_INCREMENT_RATE * this.getLastLoopTime();
    for (Player p : players.values()) {
      p.setPlayerEnergy(p.getPlayerEnergy() + energyToAdd);
      if (p.getPlayerEnergy() > MAX_PLAYER_ENERGY) p.setPlayerEnergy(MAX_PLAYER_ENERGY);
    }

    timerTick++;

    lastLoopTime = this.getTime() - timeAtEndOfLastLoop;
    timeAtEndOfLastLoop = this.getTime();

    this.validateLock();

    // check for win
    Node n1 = map.getNodes()[0];
    for (Node n : map.getNodes())
      if (n1.getOwner() == null || !n1.getOwner().equals(n.getOwner())) return;
    winningPlayer = n1.getOwner();
  }
Example #11
0
  /**
   * Performs a single left rotation: a s / \ / \ T1 s => a T3 / \ / \ T2 T3 T1 T2
   *
   * @param a The rotation anchor.
   * @return The new anchor node.
   */
  private Node rotateLeft(Node a) {

    Node s = a.right;

    System.out.printf(" -> Left single rotation on elements a: %d, s: %d%n", a.value, s.value);

    if (a == root) s.setRoot();
    else a.parent.replace(a, s);

    a.setRight(s.left);
    a.update();

    s.setLeft(a);
    s.update();

    return s;
  }
Example #12
0
 /**
  * Test the behaviour of {@link Node#stampDirty()}.
  *
  * @throws ExpressionError if the expression causes an error. This indicates a regression.
  */
 public void testMarkStampedDirty() throws ExpressionError {
   // Setup a graph where a <- b <- c.
   Node a = Node.ROOT_NODE.newInstance(testLibrary, "a", Integer.class);
   Node b = Node.ROOT_NODE.newInstance(testLibrary, "b", Integer.class);
   Node c = Node.ROOT_NODE.newInstance(testLibrary, "c", Integer.class);
   a.addParameter("a", Parameter.Type.INT);
   b.addParameter("b", Parameter.Type.INT);
   Port bIn = b.addPort("in");
   Port cIn = c.addPort("in");
   bIn.connect(a);
   cIn.connect(b);
   // Update the graph. This will make a, b and c clean.
   c.update();
   assertFalse(a.isDirty());
   assertFalse(b.isDirty());
   assertFalse(c.isDirty());
   // Set b to a stamped expression. This will make node b, and all of its dependencies, dirty.
   b.setExpression("b", "stamp(\"my_b\", 55)");
   assertTrue(b.hasStampExpression());
   assertFalse(a.isDirty());
   assertTrue(b.isDirty());
   assertTrue(c.isDirty());
   // Update the graph, cleaning all of the nodes.
   c.update();
   assertFalse(a.isDirty());
   assertFalse(b.isDirty());
   assertFalse(c.isDirty());
   // Mark only stamped upstream nodes as dirty. This will make b dirty, and all of its
   // dependencies.
   c.stampDirty();
   assertFalse(a.isDirty());
   assertTrue(b.isDirty());
   assertTrue(c.isDirty());
   // Remove the expression and update. This will make all nodes clean again.
   b.clearExpression("b");
   c.update();
   // Node b will not be dirty, since everything was updated.
   assertFalse(b.isDirty());
   // Since there are no nodes with stamp expressions, marking the stamped upstream nodes will have
   // no effect.
   c.stampDirty();
   assertFalse(a.isDirty());
   assertFalse(b.isDirty());
   assertFalse(c.isDirty());
 }
Example #13
0
  /** Test if print messages get output. */
  public void testOutput() {
    ProcessingContext ctx;
    PythonCode helloCode = new PythonCode("def cook(self): print 'hello'");
    Node test = Node.ROOT_NODE.newInstance(testLibrary, "test");
    test.setValue("_code", helloCode);
    ctx = new ProcessingContext();
    test.update(ctx);
    assertEquals("hello\n", ctx.getOutput());

    // Try this in a network. All the output of the nodes should be merged.
    Node parent = Node.ROOT_NODE.newInstance(testLibrary, "parent");
    Node child = parent.create(Node.ROOT_NODE, "child");
    child.setValue("_code", helloCode);
    child.setRendered();
    ctx = new ProcessingContext();
    parent.update(ctx);
    assertEquals("hello\n", ctx.getOutput());
  }
Example #14
0
 /** This is the same test as ParameterTest#testExpressionDependencies, but at the Node level. */
 public void testRemoveExpressionDependency() {
   Node net = testNetworkNode.newInstance(testLibrary, "net");
   Node number1 = net.create(numberNode);
   number1.addParameter("bob", Parameter.Type.INT, 10);
   number1.setExpression("value", "bob");
   number1.setRendered();
   net.update();
   assertEquals(10, net.getOutputValue());
   number1.removeParameter("bob");
   try {
     net.update();
     fail();
   } catch (ProcessingError e) {
     assertTrue(e.getCause().getMessage().toLowerCase().contains("cannot evaluate expression"));
   }
   assertTrue(net.hasError());
   assertTrue(number1.hasError());
   assertNull(net.getOutputValue());
 }
Example #15
0
 public void testBaseNode() {
   Node baseNode = Node.ROOT_NODE;
   Parameter pCode = baseNode.getParameter("_code");
   Parameter pHandle = baseNode.getParameter("_handle");
   assertEquals("_code", pCode.getName());
   assertEquals(Parameter.Type.CODE, pCode.getType());
   assertEquals("_handle", pHandle.getName());
   assertEquals(Parameter.Type.CODE, pHandle.getType());
   baseNode.update();
   assertNull(baseNode.getOutputValue());
 }
Example #16
0
  // rotates edge (x, x.parent)
  //        g            g
  //       /            /
  //      p            x
  //     / \    ->    / \
  //    x  p.r      x.l  p
  //   / \              / \
  // x.l x.r          x.r p.r
  static void rotate(Node x) {
    Node p = x.parent;
    Node g = p.parent;
    boolean isRootP = p.isRoot();
    boolean leftChildX = (x == p.left);

    // create 3 edges: (x.r(l),p), (p,x), (x,g)
    connect(leftChildX ? x.right : x.left, p, leftChildX);
    connect(p, x, !leftChildX);
    connect(x, g, !isRootP ? p == g.left : null);
    p.update();
  }
Example #17
0
 // brings x to the root, balancing tree
 //
 // zig-zig case
 //        g                                  x
 //       / \               p                / \
 //      p  g.r rot(p)    /   \     rot(x) x.l  p
 //     / \      -->    x       g    -->       / \
 //    x  p.r          / \     / \           x.r  g
 //   / \            x.l x.r p.r g.r             / \
 // x.l x.r                                    p.r g.r
 //
 // zig-zag case
 //      g               g
 //     / \             / \               x
 //    p  g.r rot(x)   x  g.r rot(x)    /   \
 //   / \      -->    / \      -->    p       g
 // p.l  x           p  x.r          / \     / \
 //     / \         / \            p.l x.l x.r g.r
 //   x.l x.r     p.l x.l
 static void splay(Node x) {
   while (!x.isRoot()) {
     Node p = x.parent;
     Node g = p.parent;
     if (!p.isRoot()) g.push();
     p.push();
     x.push();
     if (!p.isRoot()) rotate((x == p.left) == (p == g.left) ? p /*zig-zig*/ : x /*zig-zag*/);
     rotate(x);
   }
   x.push();
   x.update();
 }
Example #18
0
 public void testDisconnect() {
   Node net1 = testNetworkNode.newInstance(testLibrary, "net1");
   Node number1 = net1.create(numberNode);
   Node number2 = net1.create(numberNode);
   Node multiAdd1 = net1.create(multiAddNode);
   number1.setValue("value", 5);
   number2.setValue("value", 8);
   multiAdd1.getPort("values").connect(number1);
   multiAdd1.getPort("values").connect(number2);
   multiAdd1.update();
   assertFalse(multiAdd1.isDirty());
   assertEquals(2, multiAdd1.getPort("values").getValues().size());
   assertEquals(13, multiAdd1.getOutputValue());
   multiAdd1.disconnect();
   assertTrue(multiAdd1.isDirty());
   assertFalse(multiAdd1.isConnected());
   assertFalse(number1.isConnected());
   assertFalse(number2.isConnected());
   multiAdd1.update();
   assertEquals(0, multiAdd1.getPort("values").getValues().size());
   assertEquals(0, multiAdd1.getOutputValue());
 }
Example #19
0
  /**
   * Performs a double right rotation: a b / \ / \ s T4 s a / \ => / \ / \ T1 b T1 T2 T3 T4 / \ T2
   * T3
   *
   * @param a The rotation anchor.
   * @return The new anchor node.
   */
  private Node rotateRightDouble(Node a) {

    Node s = a.left;
    Node b = s.right;

    System.out.printf(
        " -> Double right rotation on elements a: %d, s: %d, b: %d%n", a.value, s.value, b.value);

    if (a == root) b.setRoot();
    else a.parent.replace(a, b);

    a.setLeft(b.right);
    a.update();

    s.setRight(b.left);
    s.update();

    b.setRight(a);
    b.setLeft(s);
    b.update();

    return b;
  }
Example #20
0
 /** Test if errors with dependencies fail fast, and have the correct error behaviour. */
 public void testDependencyError() {
   Node net = testNetworkNode.newInstance(testLibrary, "net");
   Node negate1 = net.create(negateNode);
   Node crash1 = net.create(crashNode);
   negate1.getPort("value").connect(crash1);
   try {
     negate1.update();
   } catch (ProcessingError e) {
     // The error flag is limited to the dependency that caused the error.
     // The crash node caused the error, so it has the error flag,
     // but the dependent node, negate1, doesn't get the error flag.
     assertTrue(crash1.hasError());
     assertFalse(negate1.hasError());
   }
 }
  synchronized void updateAll() {
    HashSet<Node> seenNodes = new HashSet<Node>();
    for (int i = 0; i < _all.size(); i++) {
      Node n = _all.get(i);
      n.update(seenNodes);
    }

    if (!seenNodes.isEmpty()) {
      // not empty, means that at least 1 server gave node list
      // remove unused hosts
      Iterator<Node> it = _all.iterator();
      while (it.hasNext()) {
        if (!seenNodes.contains(it.next())) it.remove();
      }
    }
  }
Example #22
0
  /**
   * Walks up from the most recent deleted item to the tree root in order to inform all entities
   *
   * @param a The current node that has to be revalidated after a tree alteration.
   */
  private void up(Node a) {

    Node next = a.parent;
    int orgHeigth = a.height;

    System.out.printf(
        "Validating element: %d (balance/height: %d, %d =>", a.value, a.balance, a.height);
    a.update();
    System.out.printf(" %d, %d)%n", a.balance, a.height);

    // Check if tree node is out of balance.
    if (Math.abs(a.balance) >= 2) a = rotate(a);

    // Update parent nodes only if the tree root was not yet reached
    // and if the height of the current node was altered.
    if (next != null && orgHeigth != a.height) up(next);
  }
  /** Updates this renderable node */
  @Override
  public void update() {
    if (renderTarget != null) renderTarget.update();

    super.update();
  }
Example #24
0
  /**
   * Removes an element from the tree.
   *
   * @param val The value.
   */
  public void remove(int val) {

    Node k = findNode(root, val);
    if (k == null)
      throw new IllegalArgumentException(
          "Cannot remove " + val + " because such a node does not exist.");
    Node kParent = k.parent;

    System.out.printf("Removing value: %d%n", val);

    // Delete node that is a leaf.
    if (k.isLeaf()) {

      System.out.println(" -> Corresponding node is a leaf : Performing cutoff.");

      if (k == root) root = null;
      else k.parent.removeSon(k);

      // Delete node that us a single son.
    } else if (k.isSingleSon()) {

      System.out.println(
          " -> Corresponding node has only one son. Connecting node's son and parent.");

      if (k == root) k.onlySon().setRoot();
      else k.parent.replace(k, k.onlySon());

      // Delete inner node.
    } else {

      // Check if it is more efficient to exchange node by another left or right side node
      // If uncertain, choose right side (and thus bigger element) for finding a replacement.
      boolean replaceByLeft = k.left != null && (k.right == null || k.left.height > k.right.height);

      Node s;
      if (replaceByLeft) s = findNextSmallerNode(k);
      else s = findNextBiggerNode(k);

      System.out.printf(
          " -> Correspondig node has two sons. Removing next %s element from tree first"
              + " before proceeding. Removing: %d%n",
          replaceByLeft ? "bigger" : "smaller", s.value);

      // Remove node first that is to be used as a replacement.
      remove(s.value);

      System.out.printf(" -> %d is removed. Proceeding with replacing %d%n", s.value, k.value);

      // Set new node in place of the removed node.
      if (k == root) s.setRoot();
      else k.parent.replace(k, s);

      // Fix father - son relationships.
      s.setLeft(k.left);
      s.setRight(k.right);

      s.update();
    }

    if (kParent != null) up(kParent);
  }
Example #25
0
 public MemoNode update(String value) {
   myNode = myNode.update(value);
   return myNode;
 }