Package unbbayes.prs.bn

Examples of unbbayes.prs.bn.ProbabilisticNetwork


   * The main method.
   *
   * @param args the arguments
   */
  public static void main(String[] args) {
    ProbabilisticNetwork net = new ProbabilisticNetwork("");

    try {
      unbbayes.io.xmlbif.version6.XMLBIFIO io = new  unbbayes.io.xmlbif.version6.XMLBIFIO()
      io.loadXML(new File("./examples/SimulationBN-v13.xml"), net);
    } catch (Exception e) {
View Full Code Here


     
      if (!queryList.isEmpty()) {
        // timestamp to calculate time of query
        long milliseconds = System.currentTimeMillis();
       
        ProbabilisticNetwork returnedNet = null// points to the returned SSBN
        if (isToUseMultipleQuery) {
          PrognosController.this.runQuery(queryList)// this.net will contain the result
          returnedNet = net;  // net already contains all nodes
        } else {
          // append nodes of the SSBN to returnedNet
          returnedNet = new ProbabilisticNetwork("SequentialQueryResult");
          for (Query query : queryList) {
            long timestampBeforeSeqQuery = System.currentTimeMillis()// I want to include the KB overhead in the query time of seq query
           
            ShipEntity queriedShipEntity = shipEntitiesInQuery.get(query)// ship to query
           
            // kb must reflect only the current ship
            PrognosController.this.populateRelevantKB(queriedShipEntity, true);
            // query each target one-by-one
            PrognosController.this.runQuery(Collections.singletonList(query));
           
            long timeFor1QueryInSeqQuery = System.currentTimeMillis() - timestampBeforeSeqQuery;
           
            try {
              // its the same time and iteration for all of them (because we did only 1 query to get all the results)
              iterationQuantityMap.put(queriedShipEntity.getID(), textModeRunner.getSSBNgenerator().getLastIterationCount());
              executionTimeMap.put(queriedShipEntity.getID(), timeFor1QueryInSeqQuery);
            } catch (Exception e) {
              e.printStackTrace();
            }
            for (Node node : net.getNodes()) {
              // only add if it is not redundant
              if (returnedNet.getNodeIndex(node.getName()) < 0) {
                // supposedly, we only need the marginals, so we don't have to copy the structure of the net or its details
                returnedNet.addNode(node);
              }
            }
          }
        }
       
//        System.out.println(">> It took " + ((System.currentTimeMillis() - milliseconds)/1000.0) + " seconds to run query " + queryList + ". Area is " + World.This().getDetectingMile()
//                + " nautic miles. The size of the network is " + net.getNodeCount() + ". Reasoning mode was " + (isContinuousCase()?"CONTINUOUS.":"DISCRETE."));
//            System.out.println("[" + new Date() + "] current heap usage is " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
           
        // total time the query took
        timeForQuery = (System.currentTimeMillis() - milliseconds);
           
        if (isToUseMultipleQuery) {
          // fill the iteration quantity and execution time per ship for the multiple query case
          for (ShipEntity ship : shipEntitiesInQuery.values()) {
            try {
              // its the same time and iteration for all of them (because we did only 1 query to get all the results)
              iterationQuantityMap.put(ship.getID(), textModeRunner.getSSBNgenerator().getLastIterationCount());
              executionTimeMap.put(ship.getID(), timeForQuery)// value is not required in mult. query, but we need to fill something, so that the column of CSV is constant
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
       
            // this.net contains the SSBN
            for (Node node : returnedNet.getNodes()) {
              // only consider printing log for SSBN nodes generated from isShipOfInterest (such nodes supposedly have names starting with "isShipOfInterest")
              if (node.getName().toUpperCase().startsWith("ISSHIPOFINTEREST")) {
                try {
                  ShipEntity ship = DataBase.getInstance().getShipByName(node.getName().substring(node.getName().toLowerCase().lastIndexOf("ship"), node.getName().length()));
                  // print log in csv-like format: [timestamp , queried ship , area (nautic miles) , reasoning mode (continuous or discrete) , time for preparation , heap before query , time to query, heap after query, shipofinterest, probability(of true) ]
                    System.out.println(
                        ">> , "
                        + timestampLabel    // timestamp
                        + " , " + DataBase.getInstance().getShips().size()      // quantity of ships
                        + " , " + DataBase.getInstance().getOrganizations().size()  // quantity of organizations
                        + " , " + DataBase.getInstance().getPeople().size()      // quantity of people
                        + " , " + shipName        // name of the ship provided by the user
                        + " , " + World.This().getDetectingMile()           // detecting area, in nautic miles
                        + " , " + reasoningModeLabel  // reasoning mode
                        + " , " + timeForPreparation  // time took to prepare query
                        + " , " + heapBeforeQuery    // memory usage before query
                        + " , " + timeForQuery      // time took to actually perform query
                        + " , " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())  // memory usage afer query
                        + " , " + returnedNet.getNodeCount()  // size of net
                        + " , " + "Ship" + ship.getID()  // ship of interest
                        + " , " + ((TreeVariable)node).getMarginalAt((node.getStateAt(0).equalsIgnoreCase("TRUE")?0:1))      // probability ship of interest
                        + " , " + (ship.getTerroristPlan() != null && ship.getTerroristPlan().getTerroristPlanType() != null// whether it is a terrorist
                        + " , " + queryList.size()  // size of query is supposedly the quantity of ships
                        + " , " + iterationQuantityMap.get(ship.getID())  // how many iterations the reasoner used to get a result for the ship of interest
                        + " , " + executionTimeMap.get(ship.getID())    // time in milliseconds to complete 1 query (only important in sequential query)
                    );
            } catch (Throwable t) {
              // logging should not stop program
              t.printStackTrace();
            }
              }
        }
      } else {
        // there are no ships nearby
//        System.out.println(">> No ships nearby " + myShip.getShipName() + ". Area is " + World.This().getDetectingMile()
//            + " nautic miles. Reasoning mode was " + (isContinuousCase()?"CONTINUOUS.":"DISCRETE."));
//        System.out.println("[" + new Date() + "] current heap usage is " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
       
        // print log [timestamp , queried ship , area (nautic miles) , reasoning mode (continuous or discrete) , time for preparation , heap before query , time to query, heap after query, shipofinterest, probability(of true) ]
        System.out.println(
              ">> , "
              + timestampLabel    // timestamp
              + " , " + DataBase.getInstance().getShips().size()      // quantity of ships
              + " , " + DataBase.getInstance().getOrganizations().size()  // quantity of organizations
              + " , " + DataBase.getInstance().getPeople().size()      // quantity of people
              + " , " + shipName    // ship id of queried ship (ship provided by user as input for this method)
              + " , " + World.This().getDetectingMile()           // detecting area, in nautic miles
              + " , " + reasoningModeLabel  // reasoning mode
              + " , " + timeForPreparation  // time took to prepare query
              + " , " + heapBeforeQuery    // memory usage before query
              + " , " + timeForQuery      // time took to actually perform query
              + " , " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())  // memory usage afer query
              + " , " + 0        // size of net = 0 because nothing was queried
                    + " , " + "null"    // there were no ship to actually query
              + " , " + -1.0f      // invalid probability
              + " , " + false      // it is not a ship of interest
              + " , " + 0        // no ships in the result
              + " , " + 0        // no iteration performed by the reasoner
                + " , " + 0        // if 0 query in total, it's 0 query time sequentially as well
            );
      }
     
      // query ships of interest as well, if asked
      if (isToForceIncludeShipOfInterest) {
       
        // reset KB, because we are going to do a different query
        resetKB();
       
        // reset the maps with test data
        iterationQuantityMap.clear();
        executionTimeMap.clear();
       
        try {
          // try freeing memory now, because we want to collect memory usage again
          System.gc();
          Thread.sleep(500);
        } catch (Exception e) {
          e.printStackTrace();
        }
       
        // calculate new time and heap of preparation phase
        time = System.currentTimeMillis()
        heapBeforeQuery = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
       
        // prepare another multiple query
        queryList.clear();
       
        // look for ships that are terrorists.
        Map<Query, ShipEntity> terroristShips = new HashMap<Query, ShipEntity>()// will record who was added to new query
        for (ShipEntity ship : DataBase.getInstance().getShips()) {
          if (ship.getTerroristPlan() != null && ship.getTerroristPlan().getTerroristPlanType() != null) {
            // this is a ship of interest
            if (!shipEntitiesInQuery.containsValue(ship)) {
              Query query = PrognosController.this.setupQuery(ship);
              queryList.add(query);
              if (isToUseMultipleQuery) {
                PrognosController.this.populateRelevantKB(ship, false);
              } else {
                // register what ship was added to which query
                terroristShips.put(query, ship);
              }
            }
          }
        }
       
        if (!queryList.isEmpty()) {
         
          // get timestamp now, to calculate time for query
          long milliseconds = System.currentTimeMillis();
         
          timeForPreparation = milliseconds - time;  // time we took just to prepare query
         
          ProbabilisticNetwork returnedNet = null// points to the returned SSBN
          if (isToUseMultipleQuery) {
            PrognosController.this.runQuery(queryList)// this.net will contain the result
            returnedNet = net;
          } else {
            // append nodes of the SSBN to returnedNet
            returnedNet = new ProbabilisticNetwork("SequentialTerroristQueryResult");
            for (Query query : queryList) {
              long timestampBefore1Query = System.currentTimeMillis()// I want to include the overhead of KB in the querying time
              ShipEntity queryShipEntity = terroristShips.get(query)// ship to be queried
              // kb must reflect only the current ship
              PrognosController.this.populateRelevantKB(queryShipEntity, true);
              // query each target one-by-one
              PrognosController.this.runQuery(Collections.singletonList(query));
              long timeFor1QueryInSeqQuery = System.currentTimeMillis() - timestampBefore1Query;
             
              try {
                // store iteration quantity and time it took for 1 query in a sequential query
                iterationQuantityMap.put(queryShipEntity.getID(), textModeRunner.getSSBNgenerator().getLastIterationCount());
                executionTimeMap.put(queryShipEntity.getID(), timeFor1QueryInSeqQuery);
              } catch (Exception e) {
                e.printStackTrace();
              }
             
              for (Node node : net.getNodes()) {
                // only add if it is not redundant
                if (returnedNet.getNodeIndex(node.getName()) < 0) {
                  // supposedly, we only need the marginals, so we don't have to copy the structure of the net nor its details
                  returnedNet.addNode(node);
                }
              }
            }
          }
         
          // total time to query
              timeForQuery = (System.currentTimeMillis() - milliseconds);
             
              if (isToUseMultipleQuery) {
                // fill iteration quantity and query time for the multiple query case.
            for (ShipEntity ship : terroristShips.values()) {
              try {
                // its the same time and iteration for all of them (because we did only 1 query to get all the results)
                iterationQuantityMap.put(ship.getID(), textModeRunner.getSSBNgenerator().getLastIterationCount());
                executionTimeMap.put(ship.getID(), timeForQuery);// value is not required in mult. query, but we need to fill something, so that the column of CSV is constant
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          }
             
              // this.net contains the SSBN
              for (Node node : returnedNet.getNodes()) {
                // only consider printing log for SSBN nodes generated from isShipOfInterest (such nodes supposedly have names starting with "isShipOfInterest")
                if (node.getName().toUpperCase().startsWith("ISSHIPOFINTEREST")) {
                  try {
                    ShipEntity ship = DataBase.getInstance().getShipByName(node.getName().substring(node.getName().toLowerCase().lastIndexOf("ship"), node.getName().length()));
                    String nameOfShipOfInterest = "Ship" + ship.getID();
                   
                    // print log in csv-like format: [timestamp , queried ship , area (nautic miles) , reasoning mode (continuous or discrete) , time for preparation , heap before query , time to query, heap after query, shipofinterest, probability(of true) ]
                      System.out.println(
                          ">> , "
                          + timestampLabel    // timestamp
                          + " , " + DataBase.getInstance().getShips().size()      // quantity of ships
                          + " , " + DataBase.getInstance().getOrganizations().size()  // quantity of organizations
                          + " , " + DataBase.getInstance().getPeople().size()      // quantity of people
                          + " , " + nameOfShipOfInterest  // name of the ship automatically queried = ship of interest
                          + " , " + 0           // detecting area = 0, because we are doing ship-per-ship query
                          + " , " + reasoningModeLabel  // reasoning mode
                          + " , " + timeForPreparation  // time took to prepare query
                          + " , " + heapBeforeQuery    // memory usage before query
                          + " , " + timeForQuery      // time took to actually perform query
                          + " , " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())  // memory usage afer query
                          + " , " + returnedNet.getNodeCount()  // size of net
                          + " , " + nameOfShipOfInterest  // ship of interest
                          + " , " + ((TreeVariable)node).getMarginalAt((node.getStateAt(0).equalsIgnoreCase("TRUE")?0:1))      // probability ship of interest
                          + " , " + true          // this is a terrorist
                          + " , " + queryList.size()    // quantity of ships returned is supposed to be the same of the query size
                          + " , " + iterationQuantityMap.get(ship// how many iterations the reasoner used to get a result for the ship of interest
View Full Code Here

   * The main method.
   *
   * @param args the arguments
   */
  public static void main(String[] args) {
    ProbabilisticNetwork pn = new ProbabilisticNetwork("");
/*
     try {
      XMLBIFIO io = new  XMLBIFIO(); 
    //  io.loadXML2(new File("./Example/mk_hybridTest_2d2c_bnet_3.xml"), pn);
      io.loadXML(new File("./Example/test3.xml"), pn);
View Full Code Here

   */
  public void buildLocalDistribution(SSBN ssbn) throws MEBNException,
      SSBNNodeGeneralException {

   
    ProbabilisticNetwork pn;
    SimpleSSBNNode nodeOfQuery;
   
   
    ISSBNLogManager logManager = ssbn.getLogManager();
    try {
      // we do not need to create multiple networks anymore, because disconnected networks are behaving as separate BNs in the new core.
     
//      if (logManager != null) {
//        logManager.printText(level1, false, "[1] Separating the disconnected SSBN networks");
//      }
//      List<SimpleSSBNNode>[] nodesPerNetworkArray = this.getSimpleSSBNNodeTranslator().individualizeDisconnectedNetworks(ssbn.getSimpleSsbnNodeList());
//      int netId = 0;
//      if (logManager != null) {
//        for(List<SimpleSSBNNode> networkNodesList: nodesPerNetworkArray){
//          logManager.printText(level2, false, "Network " + netId + ":"); netId++;
//          for(SimpleSSBNNode node: networkNodesList){
//            logManager.printText(level3, false, " >" + node);
//          }
//        }
//      }
//     
//      nodeOfQuery = ssbn.getQueryList().get(0).getSSBNNode();
//      List<SimpleSSBNNode> listForQuery = null;
//     
//      for(List<SimpleSSBNNode> networkNodesList: nodesPerNetworkArray){
//        for(SimpleSSBNNode node: networkNodesList){
//          if(node.equals(nodeOfQuery)){
//            listForQuery = networkNodesList;
//            break;
//          }
//        }
//      }
//      nodesPerNetworkArray = null;
      if (logManager != null) {
        logManager.skipLine();
      }
     
      // Generating the SSBN network.
      if (logManager != null) {
        logManager.printText(level1, false, "Generating the SSBN network");
      }
      pn =  new ProbabilisticNetwork(this.getHybridResource().getString("DefaultNetworkName"));
//      if(listForQuery!=null){
//        List<SSBNNode> listSSBNNode = this.getSimpleSSBNNodeTranslator().translateSimpleSSBNNodeListToSSBNNodeList(listForQuery, pn);
//          ssbn.setSsbnNodeList(listSSBNNode);
//        ssbn.setProbabilisticNetwork(pn);
//      }else{
View Full Code Here

    Debug.setDebug(false);
    EDB.This().printSet(true);
  }
 
  public ProbabilisticNetwork loadNetworkFile(File file){
    ProbabilisticNetwork pn = new ProbabilisticNetwork("");
      XMLBIFIO netIO = new XMLBIFIO();
     
      try {
      netIO.loadXML(file, pn) ;
    } catch (LoadException e) {
View Full Code Here

      Graph g = dmp.getNetwork()// net to add findings
      if (g == null) {
        throw new SSBNNodeGeneralException(new IllegalStateException(ssbn + " and " + algorithm + " should be compiled before this method."));
      }
      if (g instanceof ProbabilisticNetwork) {
        ProbabilisticNetwork net = (ProbabilisticNetwork) g;
        for(SimpleSSBNNode ssbnFindingNode: ssbn.getFindingList()){
          //Not all findings nodes are at the network.
          if(ssbnFindingNode.getProbNode()!= null){
            // extract node and finding state from the network managed by the algorithm
            TreeVariable node = (TreeVariable)net.getNode(ssbnFindingNode.getProbNode().getName());
            String stateName = ssbnFindingNode.getState().getName();
           
            // TODO avoid usage of instanceof
            // TODO stop using static instance of DMP DB
            if ((node instanceof ContinuousNode)
View Full Code Here

      e.printStackTrace();
    }  
  }
 
  public ProbabilisticNetwork loadNetworkFile(File file){
    ProbabilisticNetwork pn = null;
      XMLBIFIO netIO = new XMLBIFIO();
    
    try
      pn = netIO.load(file);
    } catch (Exception e) {
View Full Code Here

    }
    CPSCompilerMain.This().InitCompiler();
    UDB2SDB uToS = new UDB2SDB();
    SDB2UDB sToU = new SDB2UDB();
   
    ProbabilisticNetwork pn = (ProbabilisticNetwork)this.getNetwork();
   
    //save network to see queried result
    //saveNetworkFile(new File(pn.getName()+".xml"), pn);
   
    uToS.convert(pn);
    //EDB.This().get("ROOT").print("");
    CPSCompilerMain.This().compile("run(DMP);")
    ProbabilisticNetwork newNet = sToU.convert(EDB.This().get("ROOT.ENGINES.DMP.NODES"));
    this.setNetwork(newNet);
    iteration_size = EDB.This().get("ROOT.ENGINES.DMP.ITERATION_SIZE").getDataByDouble();
       
    for (Node node : pn.getNodes()) {
      if (node instanceof TreeVariable) {
View Full Code Here

  /**
   * Test method for {@link unbbayes.prs.mebn.ssbn.laskeyalgorithm.LaskeySSBNGenerator#generateSSBN(java.util.List, unbbayes.prs.mebn.kb.KnowledgeBase)}.
   */
  public final void testQueryResidentNode() {
    ProbabilisticNetwork net = null;
    try {
     
      ResidentNode continuousResidentNode = mebn.getDomainResidentNode("MTI");
      ObjectEntityInstance[] arguments = new ObjectEntityInstance[2];
      arguments[0] = mebn.getObjectEntityContainer().getEntityInstanceByName("Rpt1");
      arguments[1] = mebn.getObjectEntityContainer().getEntityInstanceByName("T0");
      createRandomVariableFinding((ContinuousResidentNode)continuousResidentNode, arguments, 0f);
     
      String[] queryParam = new String[1];
      queryParam[0] = "Obj1";
      net = textModeRunner.callLaskeyAlgorithm(mebn, knowledgeBase, "ObjectType", queryParam);
     
      // do something to net if you want to do so
     
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
    assertNotNull(net);
    assertTrue(net.getNodeCount() > 0);
  }
View Full Code Here

  /**
   * Test method for {@link unbbayes.prs.mebn.ssbn.laskeyalgorithm.LaskeySSBNGenerator#generateSSBN(java.util.List, unbbayes.prs.mebn.kb.KnowledgeBase)}.
   * For a continuous node
   */
  public final void testQueryContinuousNode() {
    ProbabilisticNetwork net = null;
    try {
      String[] queryParam = new String[2];
      queryParam[0] = "Rpt1";
      queryParam[1] = "T0";
      net = textModeRunner.callLaskeyAlgorithm(mebn, knowledgeBase, "MTI", queryParam);
     
      // do something to net if you want to do so
     
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
    assertNotNull(net);
    assertTrue(net.getNodeCount() > 0);
  }
View Full Code Here

TOP

Related Classes of unbbayes.prs.bn.ProbabilisticNetwork

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.