Exemplo n.º 1
0
Arquivo: Main.java Projeto: idcxb/java
  public static void main(String[] args) {
    System.out.println("Test 2");
    Network net3 = new Network();

    net3.addConnection(1, 2);
    net3.addConnection(3, 1);
    net3.addConnection(2, 4);
    System.out.println(net3.addConnection(4, 3));
    System.out.println(net3.addConnection(3, 3));
    System.out.println(net3.addConnection(3, 3));
    net3.addConnection(100, 4);
    net3.addConnection(3, 100);
    net3.addConnection(2, 5);
    net3.addConnection(5, 6);
    net3.addConnection(6, 7);

    net3.findTree();

    Collection switches3 = net3.getSwitches();
    Iterator iter3 = switches3.iterator();
    while (iter3.hasNext()) {
      Switch y = (Switch) iter3.next();
      System.out.println("Switch: Root, Parent, Hops to Root");
      String output = "  " + y.getMAC() + ":      ";
      output = output + y.getRoot().getMAC() + "      ";
      output = output + y.getParent().getMAC() + "         ";
      output = output + y.getDistance();
      System.out.println(output);
    }
  }
  /**
   * create a 1-d String array from a network, for easy transmission to R. triples (source,
   * edgeType, target) are filled in to an array of length 3 * # of interactions
   *
   * @param network a gaggle network
   * @return the edge attributes of the network as a string array
   */
  protected String[] networkEdgeAttributesToStringArray(Network network) {
    Interaction[] interactions = network.getInteractions();
    String source, target, type;
    String[] attributeNames = network.getEdgeAttributeNames();
    ArrayList<String> list = new ArrayList<String>();

    for (Interaction interaction : interactions) {
      source = interaction.getSource();
      type = interaction.getType();
      target = interaction.getTarget();
      String edgeName = source + " (" + type + ") " + target;
      String terseEdgeName = source + "::" + target + "::" + type;
      for (String name : attributeNames) {
        HashMap hash = network.getEdgeAttributes(name);
        if (hash.containsKey(edgeName)) {
          Object value = hash.get(edgeName);
          StringBuffer sb = new StringBuffer();
          sb.append(terseEdgeName);
          sb.append("::");
          sb.append(name);
          sb.append("::");
          sb.append(value.toString());
          list.add(sb.toString());
        } else {
          System.out.println("no " + name + " attribute for " + edgeName);
        }
      } // for a
    } // for r

    return list.toArray(new String[0]);
  } // networkEdgeAttributesToStringArray
  // ----------------------------------------------------------------------------------------
  public void handleNetwork(String source, Network newNetwork) {
    System.out.println(
        "network ready, node count "
            + newNetwork.getNodes().length
            + ", edges: "
            + newNetwork.edgeCount());

    network = newNetwork;
    defaultSpecies = newNetwork.getSpecies();
  }
Exemplo n.º 4
0
 public static double getVertexCount(Network forest, Collection<Long> a0) {
   int count = 0;
   for (Long v : forest.getVertices()) {
     if (!a0.contains(v)) {
       count++;
     }
   }
   return (double) count;
 }
Exemplo n.º 5
0
  @Test
  public void testHighLevelAccess() {
    Link link = nw.getLinkById(3L);

    Double val = 1.23;

    dp.setVehiclesPerMeterOnLink(link, val);

    assertEquals((Double) 1.23, dp.getVehiclesPerMeterOnLink(link));
  }
Exemplo n.º 6
0
  private CompositeData getCompositeData(Network mo, String moName) throws Exception {
    values = new Object[names.length];
    values[0] = moName;
    if (mo.getDiscover()) {
      values[1] = "true"; // No I18N
    } else {
      values[1] = "false"; // No I18N
    }
    values[2] = new Integer(mo.getDiscoveryStatus());
    String oid = agentName.getChildTableOID(mo.getClassname(), this.className);
    values[3] = oid;
    values[4] = agentName.getChildTableName(oid);
    try {
      return new CompositeData(null, names, values);
    } catch (Exception e) {

      return null;
    }
  }
  /**
   * create a 1-d String array from a network's node attributes, for easy transmission to R. use
   * this format for each attribute of each node: nodeName::attributeName::value
   *
   * @param network a gaggle network
   * @return the network's node attributes as a string array
   */
  protected String[] networkNodeAttributesToStringArray(Network network) {
    String[] attributeNames = network.getNodeAttributeNames();
    // System.out.println (" nnatsa, attribute name count: " + attributeNames.length);
    ArrayList<String> list = new ArrayList<String>();

    for (String attributeName : attributeNames) {
      // System.out.println (" nnatsa, attribute name: " + attributeName);
      HashMap attributeHash = network.getNodeAttributes(attributeName);
      // can't remove this warning until Network is genericized in next api release:
      String[] nodeNames = (String[]) attributeHash.keySet().toArray(new String[0]);
      for (String nodeName : nodeNames) {
        // System.out.println (" nnatsa, node name: " + nodeName);
        Object value = attributeHash.get(nodeName);
        String terseForm = nodeName + "::" + attributeName + "::" + value.toString();
        list.add(terseForm);
      } // for n
    } // for i

    return list.toArray(new String[0]);
  } // networkEdgeAttributesToStringArray
 protected void addMetaDataToNetwork(Network network) {
   if (networkMetadata.size() == 0) {
     return;
   }
   Tuple metadata = new Tuple();
   Set<String> keys = networkMetadata.keySet();
   for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
     String key = it.next();
     metadata.addSingle(new Single(key, networkMetadata.get(key)));
   }
   network.setMetadata(metadata);
 }
  // ----------------------------------------------------------------------------------------
  // is this called from anywhere? doesn't look like it
  public void createAndBroadcastNetwork(
      String sourceNode, String[] targetNodes, double[] weights, String[] targetTypes) {
    // System.out.println ("createAndBroadcastNetwork, source: " + sourceNode);
    Network network = new Network();
    addMetaDataToNetwork(network);
    network.setSpecies(defaultSpecies);

    for (int i = 0; i < targetNodes.length; i++) {
      Interaction interaction = new Interaction(sourceNode, targetNodes[i], targetTypes[i]);
      network.add(interaction);
      String edgeName = sourceNode + " (" + targetTypes[i] + ") " + targetNodes[i];
      // System.out.println ("adding weight " + weights [i] + " for edge " + edgeName);
      network.addEdgeAttribute(edgeName, "weight", weights[i]);
    }

    try {
      gaggleBoss.broadcastNetwork(myGaggleName, targetGoose, network);
    } catch (RemoteException rex) {
      System.err.println("error broadcasting network from RShellGoose " + myGaggleName);
      rex.printStackTrace();
    }
  } // createAndBroadcastNetwork
  /**
   * create a 1-d String array from a network, for easy transmission to R. each element in the array
   * is a string, with format sourceNode::targetNode::edgeType
   *
   * @param network the network to convert to a string
   * @return an array of strings representing a network
   */
  protected String[] networkToStringArray(Network network) {
    Interaction[] interactions = network.getInteractions();
    ArrayList<String> list = new ArrayList<String>();

    // System.out.println ("networkToStringArray, interaction ount: " + interactions.length);
    for (Interaction interaction : interactions) {
      String source = interaction.getSource();
      String target = interaction.getTarget();
      String type = interaction.getType();
      String combined = source + "::" + target + "::" + type;
      // System.out.println ("   interaction: " + combined);
      list.add(combined);
    } // for i

    String[] orphanNodes = network.getOrphanNodes();
    // System.out.println ("networkToStringArray, orphanCount: " + orphanNodes.length);
    for (String orphanNode : orphanNodes) {
      // System.out.println ("    orphan: " + orphanNodes [i]);
      list.add(orphanNode);
    }

    return list.toArray(new String[0]);
  } // networkToStringArray
 @Transactional(propagation = Propagation.SUPPORTS)
 public boolean hasAccessToNetwork(AccessKey accessKey, Network targetNetwork) {
   Set<AccessKeyPermission> permissions = accessKey.getPermissions();
   User user = accessKey.getUser();
   boolean hasNullPermission =
       permissions.stream().anyMatch(perm -> perm.getNetworkIdsAsSet() == null);
   if (hasNullPermission) {
     return userService.hasAccessToNetwork(user, targetNetwork);
   } else {
     Set<Long> allowedNetworks =
         permissions
             .stream()
             .map(AccessKeyPermission::getNetworkIdsAsSet)
             .flatMap(Collection::stream)
             .collect(Collectors.toSet());
     user = userService.findUserWithNetworks(user.getId());
     return allowedNetworks.contains(targetNetwork.getId())
         && (user.isAdmin() || user.getNetworks().contains(targetNetwork));
   }
 }
  public void runTest() {

    BufferedReader in = null;
    /*
     * read input from file
     */
    try {
      in = new BufferedReader(new FileReader(file));

      String read = null;
      while ((read = in.readLine()) != null) {
        list.add(read.trim());
        count++;
      }
      for (int i = 0; i < count; i++) {
        System.out.println(list.get(i));
      }
    } catch (Exception e) {
      System.out.println("There was a problem: " + e);
      e.printStackTrace();
    } finally {
      try {
        in.close();
      } catch (Exception e) {
        System.out.println("There was a problem: " + e);
        e.printStackTrace();
      }
    }

    /*
     * send list of test messages to server
     */
    for (String command : list) {
      try {
        Thread.sleep(1000);
      } catch (Exception e) {
        e.printStackTrace();
      }
      net.sendMessage(new UserMessage(command, serverIp, serverPort, System.nanoTime()));
    }
  }
Exemplo n.º 13
0
  @Before
  public void setup() {
    nw = new Network();
    nw.setName("test network");

    dp = new DensityMap();

    nw.setNodes(new ArrayList<edu.berkeley.path.model_elements_base.Node>());
    nw.setLinks(new ArrayList<edu.berkeley.path.model_elements_base.Link>());

    Node nd1;
    Node nd2;
    Link ln;

    nd1 = new Node();
    nd1.setId(1L);
    nd1.setName("one");
    nd1.setType("Highway");
    nw.getNodes().add(nd1);

    nd2 = new Node();
    nd2.setId(2L);
    nd2.setName("two");
    nd2.setType("Highway");
    nw.getNodes().add(nd2);

    ln = new Link();
    ln.setId(3L);
    ln.setName("three");
    ln.setType("Highway");
    ln.setLaneCount(4.0);
    ln.setLength(1000.0);

    ln.setBegin(nd1);
    ln.setEnd(nd2);

    nw.getLinks().add(ln);
  }
  /**
   * a network is a collection of (possibly degenerate) interactions. the R client should pass 3
   * arrays of strings, having the following structure
   *
   * <p>edges consist of strings like "VNG0723G::VNG1233G::PhylogeneticProfile" node attributes:
   * "VNG1233G::commonName::pepq2" edge attributes:
   * "VNG0723G::VNG1233G::PhylogeneticProfile::confidence::0.533"
   */
  public void createAndBroadcastNetwork(
      String[] interactionStrings,
      String[] nodeAttributeStrings,
      String[] edgeAttributeStrings,
      String name) {

    Network network = new Network();
    addMetaDataToNetwork(network);
    network.setName(name);
    network.setSpecies(defaultSpecies);

    for (String interactionString : interactionStrings) {
      String[] tokens = interactionString.split("::");
      int tokenCount = tokens.length;
      // for (int t=0; t < tokens.length; t++)
      //  System.out.println ("  edge token " + t + ": " + tokens [t]);
      if (tokenCount == 1 && tokens[0].trim().length() > 0) {
        // System.out.println ("adding one orphan node to network: " + tokens [0]);
        network.add(tokens[0]);
      } else if (tokenCount == 3) {
        String sourceNode = tokens[0];
        String targetNode = tokens[1];
        String interactionType = tokens[2];
        network.add(new Interaction(sourceNode, targetNode, interactionType));
      } // else:  good interaction
    } // for i

    // System.out.println ("nodeAttributeStrings count: " + nodeAttributeStrings.length);
    for (String nodeAttributeString : nodeAttributeStrings) {
      // System.out.println ("   " + nodeAttributeStrings [i]);
      String[] tokens = nodeAttributeString.split("::");
      if (tokens.length == 3) {
        String nodeName = tokens[0].trim();
        String attributeName = tokens[1].trim();
        String rawValue = tokens[2].trim();
        Object value = StringToObjectConverter.convert(rawValue);
        network.addNodeAttribute(nodeName, attributeName, value);
      } // if 3 tokens
    } // for i

    // System.out.println ("edgeAttributeStrings count: " + edgeAttributeStrings.length);
    for (String edgeAttributeString : edgeAttributeStrings) {
      // System.out.println ("   " + edgeAttributeStrings [i]);
      String[] tokens = edgeAttributeString.split("::");
      if (tokens.length == 5) {
        String sourceNode = tokens[0].trim();
        String targetNode = tokens[1].trim();
        String edgeType = tokens[2].trim();
        String attributeName = tokens[3].trim();
        String rawValue = tokens[4].trim();
        Object value = StringToObjectConverter.convert(rawValue);
        String edgeName = sourceNode + " (" + edgeType + ") " + targetNode;
        network.addEdgeAttribute(edgeName, attributeName, value);
      } // if 5 tokens
    } // for i

    // System.out.println ("RShellGoose, about to broadcast network");
    // System.out.println ("     node count: " + network.getNodes().length);
    // System.out.println ("      connected: " + network.getConnectedNodes ().size ());
    // System.out.println ("         orphan: " + network.getOrphanNodes().length);

    try {
      gaggleBoss.broadcastNetwork(myGaggleName, targetGoose, network);
    } catch (RemoteException rex) {
      System.err.println("error broadcasting network from RShellGoose " + myGaggleName);
      rex.printStackTrace();
    }
  } // createAndBroadcastNetwork
Exemplo n.º 15
0
 public ChargerReader(Network network, EvData data) {
   this.data = data;
   links = network.getLinks();
 }
Exemplo n.º 16
0
  /** Insert the method's description here. Creation date: (16/01/2002 9.53.37) */
  public static boolean xor_evaluate(Organism organism) {

    Network _net = null;
    boolean success = false;
    double errorsum = 0.0;
    double[] out = new double[4]; // The four outputs

    //   int numnodes = 0;
    int net_depth = 0; // The max depth of the network to be activated
    int count = 0;

    // The four possible input combinations to xor
    // The first number is for biasing

    double in[][] = {{1.0, 0.0, 0.0}, {1.0, 0.0, 1.0}, {1.0, 1.0, 0.0}, {1.0, 1.0, 1.0}};

    _net = organism.net;
    //   numnodes = organism.genome.nodes.size();

    net_depth = _net.max_depth();

    // for each example , 'count', propagate signal .... and compute results
    for (count = 0; count <= 3; count++) {

      // first activation from sensor to first next levelof neurons
      _net.load_sensors(in[count]);
      success = _net.activate();

      // next activation while last level is reached !
      // use depth to ensure relaxation

      for (int relax = 0; relax <= net_depth; relax++) success = _net.activate();

      // ok : the propagation is completed : repeat until all examples are presented
      out[count] = ((NNode) _net.getOutputs().firstElement()).getActivation();
      _net.flush();
    }

    // control the result
    if (success) {
      errorsum =
          (double)
              (Math.abs(out[0])
                  + Math.abs(1.0 - out[1])
                  + Math.abs(1.0 - out[2])
                  + Math.abs(out[3]));
      organism.setFitness(Math.pow((4.0 - errorsum), 2));
      organism.setError(errorsum);
    } else {
      errorsum = 999.0;
      organism.setFitness(0.001);
      organism.setError(errorsum);
    }
    String mask03 = "0.000";
    DecimalFormat fmt03 = new DecimalFormat(mask03);

    if ((out[0] < 0.5) && (out[1] >= 0.5) && (out[2] >= 0.5) && (out[3] < 0.5)) {
      organism.setWinner(true);
      return true;
    } else {
      organism.setWinner(false);
      return false;
    }
  }
  public boolean execute() {
    if (CDState.getCycle() % period != 0) return false;

    MycoCast mycocast = (MycoCast) Network.get(0).getProtocol(mycocastPid);

    int bio = mycocast.countBiomass();
    int ext = mycocast.countExtending();
    int bra = mycocast.countBranching();
    int imm = mycocast.countImmobile();

    // Update vertices
    Set<MycoNode> activeNodes = new HashSet<MycoNode>();
    for (int i = 0; i < Network.size(); i++) {
      MycoNode n = (MycoNode) Network.get(i);
      activeNodes.add(n);
      HyphaData data = n.getHyphaData();
      // if (data.isBiomass()) { continue; }
      if (graph.containsVertex(n)) {
        graph.removeVertex(n);
      }
      if (!graph.containsVertex(n)) {
        graph.addVertex(n);
      }
    }
    Set<MycoNode> jungNodes = new HashSet<MycoNode>(graph.getVertices());
    jungNodes.removeAll(activeNodes);

    for (MycoNode n : jungNodes) {
      graph.removeVertex(n);
    }

    // Update edges
    for (int i = 0; i < Network.size(); i++) {
      MycoNode n = (MycoNode) Network.get(i);
      HyphaData data = n.getHyphaData();
      HyphaLink link = n.getHyphaLink();

      synchronized (graph) {

        // We now add in all links and tune out display in Visualizer
        java.util.List<MycoNode> neighbors = (java.util.List<MycoNode>) link.getNeighbors();

        //// Adding only links to hypha thins out links to biomass
        //    (java.util.List<MycoNode>) link.getHyphae();

        Collection<MycoNode> jungNeighbors = graph.getNeighbors(n);

        // Remove edges from Jung graph that are not in peersim graph
        for (MycoNode o : jungNeighbors) {
          if (!neighbors.contains(o)) {
            MycoEdge edge = graph.findEdge(n, o);
            while (edge != null) {
              graph.removeEdge(edge);
              edge = graph.findEdge(n, o);
            }
          }
        }

        // Add missing edges to Jung graph that are in peersim graph
        for (MycoNode o : neighbors) {
          if (graph.findEdge(n, o) == null) {
            MycoEdge edge = new MycoEdge();
            graph.addEdge(edge, n, o, EdgeType.DIRECTED);
          }
        }
      }

      // log.finest("VERTICES: " + graph.getVertices());
      // log.finest("EDGES: " + graph.getEdges());
    }

    for (ChangeListener cl : changeListeners) {
      cl.stateChanged(new ChangeEvent(graph));
    }
    if (walking) {
      try {
        Thread.sleep(walkDelay);
      } catch (InterruptedException e) {
      }
      stepBlocked = false;
    }

    try {
      while (stepBlocked && !noBlock) {
        synchronized (JungGraphObserver.class) {
          JungGraphObserver.class.wait();
        }
      }
    } catch (InterruptedException e) {
      stepBlocked = true;
    }
    stepBlocked = true;
    // System.out.println(graph.toString());
    return false;
  }
Exemplo n.º 18
0
  /**
   * This is a test for compute depth of genome and trace all debug information for viewing all
   * signal flowing is not necessary for network simulation
   */
  public static void Experiment2(String xFileName) {
    StringTokenizer st;
    String curword;
    String xline;
    String fnamebuf;
    IOseq xFile;
    int id;
    Genome g1 = null;
    Network net = null;

    System.out.println("------ Start experiment 2 -------");

    xFile = new IOseq(xFileName);

    boolean ret = xFile.IOseqOpenR();

    if (ret) {

      try {

        System.out.println(" Start experiment 2");
        System.out.println(" Read start genome..");

        xline = xFile.IOseqRead();

        st = new StringTokenizer(xline);
        // skip
        curword = st.nextToken();
        // id of genome can be readed
        curword = st.nextToken();
        id = Integer.parseInt(curword);
        g1 = new Genome(id, xFile);

        // generate	a link mutation
        g1.mutate_link_weight(Neat.p_weight_mut_power, 1.0, NeatConstant.GAUSSIAN);
        // generate from genome the phenotype
        g1.genesis(id);
        // view genotype
        g1.op_view();

        // assign reference to genotype
        net = g1.phenotype;

        // compute first the 'teorical' depth
        int lx = net.max_depth();

        // compute . after, the 'pratical' depth passing
        // the virtual depth;
        int dx = net.is_stabilized(lx);
        // after reset all value of net
        net.flush();

        System.out.print("\n For genome : " + xFileName + " : max depth virtuale=" + lx);
        System.out.print(", max depth reale=" + dx);

        if (dx != lx) System.out.print("\n  *ALERT*  This net is   NOT   S T A B L E ");

        net.flush();

        double errorsum = 0.0;
        double[] out = new double[4]; // The four outputs

        int numnodes = 0;
        int net_depth = 0; // The max depth of the network to be activated
        int count = 0;
        boolean success = false;

        double in[] = {1.0, 1.0, 1.0};

        count = 0;
        // first activation from sensor to first next level of neurons
        net.load_sensors(in);

        // first activation....
        success = net.activate();

        // next activation while last level is reached !
        // use depth to ensure relaxation

        for (int relax = 1; relax <= dx; relax++) {
          success = net.activate();
          //		  	System.out.print("\n -----TIME <"+relax+"> -----");
        }

        // ok : the propagation is completed
      } catch (Throwable e) {
        System.err.println(e + " : error during open " + xFileName);
      }

      xFile.IOseqCloseR();

    } else System.err.print("\n : error during open " + xFileName);

    System.out.println("\n\n End of experiment");
  }
Exemplo n.º 19
0
 public static double getEdgeCount(Network forest) {
   return (double) forest.getEdgeCount();
 }
Exemplo n.º 20
0
  /**
   * This is a test for compute depth of genome and compute if has a path from two nodes (is a test
   * for new version of method is_recur()) --> has_a_path(..) is not necessary for network
   * simulation
   */
  public static void Experiment5(String xFileName, int potin, int potout) {
    StringTokenizer st;
    String curword;
    String xline;
    String fnamebuf;
    IOseq xFile;
    int id;
    Genome g1 = null;
    Network net = null;

    xFile = new IOseq(xFileName);
    boolean ret = xFile.IOseqOpenR();

    if (ret) {

      try {
        System.out.println("------ Start experiment 5 -------");
        // read genome A

        System.out.println(" Read start genome..");

        xline = xFile.IOseqRead();

        st = new StringTokenizer(xline);
        // skip
        curword = st.nextToken();
        // id of genome can be readed
        curword = st.nextToken();
        id = Integer.parseInt(curword);
        g1 = new Genome(id, xFile);

        // generate	a link mutation
        g1.mutate_link_weight(Neat.p_weight_mut_power, 1.0, NeatConstant.GAUSSIAN);
        // generate from genome the phenotype
        g1.genesis(id);

        // view genotype
        g1.op_view();

        // assign reference to genotype
        net = g1.phenotype;

        // compute first the 'teorical' depth
        int lx = net.max_depth();
        // compute . after, the 'pratical' depth passing
        // the virtual depth;
        int dx = net.is_stabilized(lx);

        System.out.print("\n Max depth virtuale=" + lx);
        System.out.print(", max depth reale=" + dx);

        // search the inode
        NNode inode = null;
        NNode onode = null;
        NNode curnode = null;
        boolean rc = false;
        int cnt = 0;

        for (int ix = 0; (ix < net.allnodes.size()) && (cnt < 2); ix++) {
          curnode = (NNode) net.allnodes.elementAt(ix);
          if (curnode.node_id == potin) {
            inode = curnode;
            cnt++;
          }

          if (curnode.node_id == potout) {
            onode = curnode;
            cnt++;
          }
        }

        // if exist , point to exitsting version
        if (cnt < 2) {

          System.out.print("\n ERROR :nodes in e/o out wrong's : retype!");
        } else {

          net.status = 0;
          rc = net.has_a_path(inode, onode, 0, 30);
          System.out.print("\n Result for  example " + xFileName + " for ipotetic path ");
          System.out.print(
              "\n   inode[" + potin + "] ---> onode[" + potout + "]  is  return code=" + rc);
          System.out.print(", status = " + net.status);
        }

        // after reset all value of net
        net.flush();

        // ok : the propagation is completed
      } catch (Throwable e) {
        System.err.println(e + " : error during read " + xFileName);
      }

      xFile.IOseqCloseR();

    } else System.err.print("\n : error during open " + xFileName);

    System.out.println("\n\n End of experiment");
  }