Example #1
0
  // Helper method for updateM( boolean, Node, Node )
  // Calculates M for Node n, given that M for the two children
  // of n has been calculated.
  // (Last modified: 10/02/01)
  private void calculateMforNode(Node n) {

    if (!n.isExternal()) {

      boolean was_duplication = n.isDuplication();
      Node a = n.getChild1().getLink(), b = n.getChild2().getLink();

      while (a != b) {
        if (a.getID() > b.getID()) {
          a = a.getParent();
        } else {
          b = b.getParent();
        }
      }

      n.setLink(a);

      if (a == n.getChild1().getLink() || a == n.getChild2().getLink()) {
        n.setDuplication(true);
        if (!was_duplication) {
          increaseDuplications();
        }
      } else {
        n.setDuplication(false);
        if (was_duplication) {
          decreaseDuplications();
        }
      }
    }
  } // calculateMforNode( Node )
Example #2
0
  /**
   * Traverses the subtree of Node g in postorder, calculating the mapping function M, and
   * determines which nodes represent speciation events and which ones duplication events.
   *
   * <p>Preconditions: Mapping M for external nodes must have been calculated and the species tree
   * must be labelled in preorder.
   *
   * <p>(Last modified: 01/11/01)
   *
   * @param g starting node of a gene tree - normally the root
   */
  void geneTreePostOrderTraversal(Node g) {

    Node a, b;

    if (!g.isExternal()) {

      geneTreePostOrderTraversal(g.getChild1());
      geneTreePostOrderTraversal(g.getChild2());

      a = g.getChild1().getLink();
      b = g.getChild2().getLink();

      while (a != b) {
        if (a.getID() > b.getID()) {
          a = a.getParent();
        } else {
          b = b.getParent();
        }
      }
      g.setLink(a);

      // Determines whether dup. or spec.
      g.setDuplicationOrSpecAssigned(true);

      if (a == g.getChild1().getLink() || a == g.getChild2().getLink()) {
        g.setDuplication(true);
        increaseDuplications();
      } else {
        g.setDuplication(false);
      }
    }
  } // geneTreePostOrderTraversal( Node )
Example #3
0
 public void resetNodesWithoutReservation() {
   for (Node n : noRes) {
     List<Integer> THS = n.getTHS();
     for (int t : THS) {
       if (t != n.getID()) {
         Node removeFrom = nodes.get(t);
         removeFrom.removeNeighbour(n.getID());
       }
     }
     n.clearReservation();
   }
 }
Example #4
0
  /**
   * Initializes the state of this node system. This includes generating and connecting the nodes in
   * the system.
   */
  public void initialize() {
    // Determine the number of nodes in the network
    int numNodes = rand.nextInt(MAX_NUM_NODES + 1);
    while (numNodes < MIN_NUM_NODES) numNodes = rand.nextInt(MAX_NUM_NODES + 1);

    System.out.println("Number of nodes: " + numNodes);

    // Create the nodes
    for (int i = 0; i < numNodes; i++) {
      Node node = new Node(new EmptyStrategy(), SystemTime.getTime());

      // TODO
      // Determine this node's peer table size
      node.setPeerTableSize(10);
      nodes.add(node);
    }

    // Randomly connect nodes
    for (Node node : nodes) {
      for (int index = 0; index < node.getPeerTableSize(); index++) {
        // Find a random node not in this node's peer table
        int nextNeighbor = rand.nextInt(nodes.size());

        // Peer should not know the neighbor and the neighbor should
        // be this peer
        while (node.knowsPeer(nextNeighbor) || nextNeighbor == node.getID()) {
          nextNeighbor = rand.nextInt(nodes.size());
        }

        node.setPeer(index, nodes.get(nextNeighbor));
      }
    }
  }
Example #5
0
  public void findTHS() {
    int doubleRange = this.range * 2;

    for (int i = 0; i < numNodes; i++) {
      Node active = nodes.get(i);
      for (int j = 0; j < numNodes; j++) {
        Node toCheck = nodes.get(j);
        if (i != j) {
          // System.out.println("active x: " + active.getXLanePosition() + " active y: " +
          // active.getyLanePosition());
          // System.out.println("check  y : " + toCheck.getXLanePosition() + " check y:  " +
          // toCheck.getyLanePosition());
          int activeX = active.getXLanePosition();
          int activeY = active.getyLanePosition();

          int checkX = toCheck.getXLanePosition();
          int checkY = toCheck.getyLanePosition();

          double distance =
              Math.sqrt(Math.pow((activeX - checkX), 2) + Math.pow((activeY - checkY), 2));
          if (distance <= doubleRange) {
            active.addToTHS(toCheck.getID());
          }
        }
      }
    }
  }
 /**
  * Initializes the node <tt>n</tt> associating it with the BitTorrent protocol and setting the
  * reference to the tracker, the status of the file and the bandwidth.
  *
  * @param n The node to initialize
  */
 public void initialize(Node n) {
   Node tracker = Network.get(0);
   BitTorrent p;
   p = (BitTorrent) n.getProtocol(pid);
   p.setTracker(tracker);
   p.setThisNodeID(n.getID());
   setFileStatus(p);
   setBandwidth(p);
 }
Example #7
0
 @Override
 protected void save(DataOutput output) throws IOException {
   output.writeUTF(getName());
   output.writeInt(this.nodes.length);
   for (Node node : this.nodes) {
     output.writeInt(node.getID());
   }
   this.wayInfo.saveToOutput(output);
 }
Example #8
0
  public void reserveTimeSlots() {
    List<Integer> hasSlot = new ArrayList<Integer>();
    while (hasSlot.size() < this.numNodes) {
      int nodeToAttempt = r.nextInt(this.numNodes);
      while (hasSlot.contains(nodeToAttempt)) {
        nodeToAttempt = r.nextInt(this.numNodes);
      }

      Node toAttemptReservation = nodes.get(nodeToAttempt);
      if (toAttemptReservation.getReservation() == -1) // Node doesn't have a slot yet
      {
        boolean canAdd = true;
        int slotToReserve = r.nextInt(this.numSlots);
        List<Integer> THSToCheck = toAttemptReservation.getTHS();

        for (int n : THSToCheck) {
          Node toCheck = nodes.get(n);
          ReservationBean[] toCheckSlots = toCheck.getTimeSlots();
          if (toCheckSlots[slotToReserve].getHolder() != -1) {
            canAdd = false;
            break;
          }
        }
        if (canAdd) {
          toAttemptReservation.setReservation(slotToReserve);

          for (int n : THSToCheck) {
            Node toUpdate = nodes.get(n);
            // set reservation in all nodes in THS
            toUpdate.setTimeSlotReservation(
                slotToReserve,
                toAttemptReservation.getID(),
                toAttemptReservation.getRemainingReservationDuration());
            // Set initial FI in all nodes in THS
            toUpdate.setFI(
                slotToReserve,
                toAttemptReservation.getID(),
                toAttemptReservation.getRemainingReservationDuration());
          }
          hasSlot.add(toAttemptReservation.getID());
        }
      }
    }
  }
Example #9
0
  /**
   * This is the standard method the define periodic activity. The frequency of execution of this
   * method is defined by a {@link peersim.edsim.CDScheduler} component in the configuration.
   */
  public void nextCycle(Node node, int pid) {
    Linkable linkable = (Linkable) node.getProtocol(FastConfig.getLinkable(pid));
    if (linkable.degree() > 0) {
      Node peern = linkable.getNeighbor(CommonState.r.nextInt(linkable.degree()));

      // XXX quick and dirty handling of failures
      // (message would be lost anyway, we save time)
      if (!peern.isUp()) {
        return;
      }

      ((Transport) node.getProtocol(FastConfig.getTransport(pid)))
          .send(
              node,
              peern,
              new FloodMessage(value, ddl, node, node, String.valueOf(node.getID())),
              pid);
      System.out.println("Start " + node.getID() + " ->" + peern.getID());
    }
  }
Example #10
0
  public void sendJamInRange(int senderID, JamMessage m) {
    Node active = nodes.get(senderID);
    int activeLane = active.getLane();
    // int activeLanePosition = active.getLanePosition();
    // System.out.println(field.length+ "   x     " + field[0].length);

    // Left most lane with which communication may occur
    int leftLimit = ((activeLane * this.width) - this.range) / this.width;
    if (leftLimit < 0) leftLimit = 0;

    // Right most lane with which communication may occur
    int rightLimit = ((activeLane * this.width) + this.range) / this.width;
    if (rightLimit > field.length) rightLimit = field.length - 1;

    int upperLimit = active.getyLanePosition() + this.range;
    if (upperLimit >= field[0].length) upperLimit = field[0].length - 1;

    int lowerLimit = active.getyLanePosition() - this.range;
    if (lowerLimit < 0) lowerLimit = 0;

    int activeX = active.getXLanePosition();
    int activeY = active.getyLanePosition();

    for (int j = leftLimit; j <= rightLimit; j++) {
      for (int k = lowerLimit; k <= upperLimit; k++) {
        Node toCheck = field[j][k];
        if (toCheck != null && toCheck.getID() != active.getID()) {

          int toCheckX = toCheck.getXLanePosition() * this.width;
          int toCheckY = toCheck.getyLanePosition();
          double distance =
              Math.sqrt(Math.pow(toCheckX - activeX, 2) + Math.pow(toCheckY - activeY, 2));
          // System.out.println(distance);
          if (distance < this.range) {
            toCheck.recJam(m);
          }
        }
      }
    }
  }
  /** Convert word graph to phoneme graph */
  private Graph buildPhonemeGraph(Graph wordGraph) {
    Graph phonemeGraph = new Graph();
    phonemeGraph.copyGraph(wordGraph);

    for (Node node : phonemeGraph.nodeToArray()) {
      if (node.getType().equals(NodeType.WORD)) {
        String word = node.getID();
        // "false" means graph won't have additional dummy
        // nodes surrounding the word
        Graph pronunciationGraph = dictionary.getWordGraph(word, false);
        phonemeGraph.insertGraph(pronunciationGraph, node);
      }
    }
    return phonemeGraph;
  }
Example #12
0
  /** Returns a string representing the current state of the system. */
  public String getCurrentState() {
    StringBuilder accumulator = new StringBuilder();

    for (Node node : nodes) {
      accumulator.append(node.getID());
      accumulator.append(SPACE);

      int numPeers = node.getPeerTableSize();

      for (int i = 0; i < numPeers; i++) {
        accumulator.append(node.getPeerAt(i).getID());
        accumulator.append(SPACE);
      }
      accumulator.append(NEWLINE);
    }

    return accumulator.toString();
  }
  /**
   * Convert the phoneme graph to an HMM.
   *
   * @param cdGraph a context dependent phoneme graph
   * @return an HMM graph for a context dependent phoneme graph
   */
  public Graph buildHMMGraph(Graph cdGraph) {
    Graph hmmGraph = new Graph();

    hmmGraph.copyGraph(cdGraph);

    for (Node node : hmmGraph.nodeToArray()) {
      Unit unit = null;
      if (node.getType().equals(NodeType.PHONE)) {
        unit = unitManager.getUnit(node.getID());
      } else if (node.getType().equals(NodeType.SILENCE_WITH_LOOPBACK)) {
        unit = unitManager.getUnit("SIL");
      } else {
        // if it's not a phone, and it's not silence, it's a
        // dummy node, and we don't care.
        continue;
      }
      HMM hmm = acousticModel.lookupNearestHMM(unit, HMMPosition.UNDEFINED, false);
      Graph modelGraph = buildModelGraph((SenoneHMM) hmm);
      modelGraph.validate();
      hmmGraph.insertGraph(modelGraph, node);
    }
    return hmmGraph;
  }
  @Override
  public void initStateNodes() throws Exception {

    typeLabel = typeLabelInput.get();
    //        nTypes = nTypesInput.get();

    BeastTreeFromMaster masterTree = masterTreeInput.get();

    TraitSet typeTrait = new TraitSet();
    TraitSet dateTrait = new TraitSet();

    String types = "";
    String dates = "";

    for (Node beastNode : masterTree.getExternalNodes()) {

      dates += beastNode.getID() + "=" + beastNode.getHeight() + ",";
      types += beastNode.getID() + "=" + (int) beastNode.getMetaData("location") + ",";
    }

    dates = dates.substring(0, dates.length() - 1);
    types = types.substring(0, types.length() - 1);

    typeTrait.initByName("value", types, "taxa", m_taxonset.get(), "traitname", "type");
    dateTrait.initByName("value", dates, "taxa", m_taxonset.get(), "traitname", "date-backward");

    SCMigrationModel migModel = new SCMigrationModel();

    Double[] temp = new Double[nTypes.get()];
    Arrays.fill(temp, muInput.get());
    migModel.setInputValue("rateMatrix", new RealParameter(temp));
    Arrays.fill(temp, popSizeInput.get());
    migModel.setInputValue("popSizes", new RealParameter(temp));
    migModel.initAndValidate();

    if (random.get()) {
      tree = new StructuredCoalescentMultiTypeTree();

      tree.setInputValue("migrationModel", migModel);
    } else {
      Node oldRoot = masterTree.getRoot();
      MultiTypeNode newRoot = new MultiTypeNode();

      newRoot.height = oldRoot.height;
      newRoot.nTypeChanges = 0;
      newRoot.changeTimes.addAll(new ArrayList<Double>());
      newRoot.changeTypes.addAll(new ArrayList<Integer>());
      newRoot.nodeType = 0;

      newRoot.labelNr = oldRoot.labelNr;

      newRoot.addChild(copyFromFlatNode(oldRoot.getLeft()));
      newRoot.addChild(copyFromFlatNode(oldRoot.getRight()));

      tree = new MultiTypeTree(newRoot);
    }

    tree.setInputValue("trait", typeTrait);
    tree.setInputValue("trait", dateTrait);
    tree.initAndValidate();

    setInputValue("trait", dateTrait);
    setInputValue("trait", typeTrait);

    assignFromWithoutID(tree);
  }
Example #15
0
 public String toString() {
   return String.format(
       "%d: %4.2fkm from %d to %d", road.getID(), length, startNode.getID(), endNode.getID());
 }
Example #16
0
  public AbrahamGAValue getABGroup(ChemGraph p_chemGraph) {
    // #[ operation getGAGroup(ChemGraph)

    AbramData result_abram = new AbramData();
    Graph g = p_chemGraph.getGraph();
    HashMap oldCentralNode = (HashMap) (p_chemGraph.getCentralNode()).clone();

    // satuate radical site
    int max_radNum_molecule = ChemGraph.getMAX_RADICAL_NUM();
    int max_radNum_atom = Math.min(8, max_radNum_molecule);
    int[] idArray = new int[max_radNum_molecule];
    Atom[] atomArray = new Atom[max_radNum_molecule];
    Node[][] newnode = new Node[max_radNum_molecule][max_radNum_atom];

    int radicalSite = 0;
    Iterator iter = p_chemGraph.getNodeList();
    FreeElectron satuated = FreeElectron.make("0");
    while (iter.hasNext()) {
      Node node = (Node) iter.next();
      Atom atom = (Atom) node.getElement();
      if (atom.isRadical()) {
        radicalSite++;
        // save the old radical atom
        idArray[radicalSite - 1] = node.getID().intValue();
        atomArray[radicalSite - 1] = atom;
        // new a satuated atom and replace the old one
        Atom newAtom = new Atom(atom.getChemElement(), satuated);
        node.setElement(newAtom);
        node.updateFeElement();
      }
    }

    // add H to satuate chem graph
    Atom H = Atom.make(ChemElement.make("H"), satuated);
    Bond S = Bond.make("S");
    for (int i = 0; i < radicalSite; i++) {
      Node node = p_chemGraph.getNodeAt(idArray[i]);
      Atom atom = atomArray[i];
      int HNum = atom.getRadicalNumber();
      for (int j = 0; j < HNum; j++) {
        newnode[i][j] = g.addNode(H);
        g.addArcBetween(node, S, newnode[i][j]);
      }
      node.updateFgElement();
    }

    // find all the thermo groups
    iter = p_chemGraph.getNodeList();
    while (iter.hasNext()) {
      Node node = (Node) iter.next();
      Atom atom = (Atom) node.getElement();
      if (!(atom.getType().equals("H"))) {
        if (!atom.isRadical()) {

          p_chemGraph.resetThermoSite(node);
          AbrahamGAValue thisAbrahamValue = thermoLibrary.findAbrahamGroup(p_chemGraph);

          if (thisAbrahamValue == null) {
            System.err.println("Abraham group not found: " + node.getID());
          } else {
            // System.out.println(node.getID() + " " + thisGAValue.getName()+ "
            // "+thisGAValue.toString());

            result_abram.plus(thisAbrahamValue);
          }
        } else {
          System.err.println("Error: Radical detected after satuation!");
        }
      }
    }

    //        // find the BDE for all radical groups
    //        for (int i=0; i<radicalSite; i++) {
    //          	int id = idArray[i];
    //           	Node node = g.getNodeAt(id);
    //           	Atom old = (Atom)node.getElement();
    //           	node.setElement(atomArray[i]);
    //           	node.updateFeElement();
    //
    //            // get rid of the extra H at ith site
    //          	int HNum = atomArray[i].getRadicalNumber();
    //           	for (int j=0;j<HNum;j++) {
    //           		g.removeNode(newnode[i][j]);
    //           	}
    //           	node.updateFgElement();
    //
    //           	p_chemGraph.resetThermoSite(node);
    //           	ThermoGAValue thisGAValue = thermoLibrary.findRadicalGroup(p_chemGraph);
    //           	if (thisGAValue == null) {
    //           		System.err.println("Radical group not found: " + node.getID());
    //           	}
    //           	else {
    //           		//System.out.println(node.getID() + " radical correction: " +
    // thisGAValue.getName() + "  "+thisGAValue.toString());
    //           		result.plus(thisGAValue);
    //            }
    //
    //            //recover the satuated site for next radical site calculation
    //          	node.setElement(old);
    //          	node.updateFeElement();
    //           	for (int j=0;j<HNum;j++) {
    //           		newnode[i][j] = g.addNode(H);
    //           		g.addArcBetween(node,S,newnode[i][j]);
    //           	}
    //           	node.updateFgElement();
    //
    //         }
    //
    //         // recover the chem graph structure
    //         // recover the radical
    //         for (int i=0; i<radicalSite; i++) {
    //           	int id = idArray[i];
    //           	Node node = g.getNodeAt(id);
    //           	node.setElement(atomArray[i]);
    //           	node.updateFeElement();
    //           	int HNum = atomArray[i].getRadicalNumber();
    //         	//get rid of extra H
    //           	for (int j=0;j<HNum;j++) {
    //          	g.removeNode(newnode[i][j]);
    //           	}
    //           	node.updateFgElement();
    //         }
    //
    //         // substrate the enthalphy of H from the result
    //         int rad_number = p_chemGraph.getRadicalNumber();
    //         ThermoGAValue enthalpy_H = new ThermoGAValue(ENTHALPY_HYDROGEN * rad_number,
    // 0,0,0,0,0,0,0,0,0,0,0,null);
    //         result.minus(enthalpy_H);
    //
    //         // make the symmetric number correction to entropy
    //
    //         if (p_chemGraph.isAcyclic()){
    //			 int sigma = p_chemGraph.getSymmetryNumber();
    //	         ThermoGAValue symmtryNumberCorrection = new
    // ThermoGAValue(0,GasConstant.getCalMolK()*Math.log(sigma),0,0,0,0,0,0,0,0,0,0,null);
    //			 result.minus(symmtryNumberCorrection);
    //         }

    p_chemGraph.setCentralNode(oldCentralNode);

    return result_abram;

    // #]
  }
Example #17
0
  /** This is the standard method to define to process incoming messages. */
  public void processEvent(Node node, int pid, Object event) {

    FloodMessage aem = (FloodMessage) event;

    if (aem.value == this.value) {

      System.out.println(
          "Sucess  at time: "
              + CommonState.getTime()
              + " ddl="
              + aem.ddl
              + ", path is: "
              + aem.path
              + "->"
              + node.getID()
              + "  search value:"
              + aem.value
              + " this node'value is:"
              + value);
    } else {
      aem.ddl++;
      if (aem.ddl <= 8) {
        System.out.println(
            "Forward at time: "
                + CommonState.getTime()
                + " ddl="
                + aem.ddl
                + ", path is: "
                + aem.path
                + "->"
                + node.getID()
                + "  search value:"
                + aem.value
                + " this node'value is:"
                + value);
        Linkable linkable = (Linkable) node.getProtocol(FastConfig.getLinkable(pid));

        if (linkable.degree() > 0) {
          for (int i = 0; i < linkable.degree(); i++) {

            Node peern = linkable.getNeighbor(i);
            if (peern.getID() != aem.sender.getID()
                && peern.getID() != aem.directsender.getID()) // ��ԭʼ��sender����һ��ת���ڵ�
            {
              // XXX quick and dirty handling of failures
              // (message would be lost anyway, we save time)
              if (!peern.isUp()) {
                return;
              }

              ((Transport) node.getProtocol(FastConfig.getTransport(pid)))
                  .send(
                      node,
                      peern,
                      new FloodMessage(
                          aem.value,
                          aem.ddl,
                          aem.sender,
                          node,
                          aem.path + "->" + String.valueOf(node.getID())),
                      pid);
            }
          }
        }
      } else {
        System.out.println(
            "Failed  at time: "
                + CommonState.getTime()
                + " ddl="
                + aem.ddl
                + ", path is: "
                + aem.path
                + "->"
                + node.getID()
                + "  search value:"
                + aem.value
                + " this node'value is:"
                + value);
      }
    }
    /*
    if( aem.sender!=null )
    ((Transport)node.getProtocol(FastConfig.getTransport(pid))).
    send(
    node,
    aem.sender,
    new AverageMessage(value,null),
    pid);

    value = (value + aem.value) / 2;
     */
  }
Example #18
0
 // envoi d'un message (l'envoi se fait via la couche transport)
 public void send(Message msg, Node dest) {
   this.log("Send " + msg.getContent() + " to " + dest.getID());
   this.transport.send(getMyNode(), dest, msg, this.mypid);
 }