Package groundTruthModule.datastructure

Examples of groundTruthModule.datastructure.ShipEntity


      public void actionPerformed(ActionEvent e) {
        try {
          MapFrame.This().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

          if (MapFrame.This().infoPane.tablePane.selUnit != null) {
                ShipEntity ship = DataBase.getInstance().getShipByName(MapFrame.This().infoPane.tablePane.selUnit.getName());
 
                // We're going to do something that takes a long time, so we
                    // spin off a thread and update the display when we're done.
             Worker worker = new Worker();
             worker.setPriority(Thread.MIN_PRIORITY);
                     worker.setShip(ship);
                     worker.start()
          }
          MapFrame.This().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        } catch (Exception exception) {
          exception.printStackTrace();
          JOptionPane.showMessageDialog(prognosFrame, exception.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
         }
      }
    });
   
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Run query action listener for multiple objects
    MapFrame.This().infoPane.tablePane.addQueryButtonMTActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          MapFrame.This().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

          if (MapFrame.This().infoPane.tablePane.selUnit != null) {
            ShipEntity ship = DataBase.getInstance().getShipByName(MapFrame.This().infoPane.tablePane.selUnit.getName());
            String shipName = "Ship" + DataBase.getInstance().getShips().indexOf(ship);
            ship.setShipName(shipName);
            WorkerMT worker = new WorkerMT();
             worker.setPriority(Thread.MIN_PRIORITY);
                     worker.setShip(ship);
                     worker.start()
          }
          MapFrame.This().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        } catch (Exception exception) {
          exception.printStackTrace();
          JOptionPane.showMessageDialog(prognosFrame, exception.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
         }
      }
    });
   
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Run query action listener for web server
    MapFrame.This().infoPane.tablePane.addQueryButtonWSActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          MapFrame.This().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

          if (MapFrame.This().infoPane.tablePane.selUnit != null) {
             ShipEntity ship = DataBase.getInstance().getShipByName(MapFrame.This().infoPane.tablePane.selUnit.getName());
           
            // We're going to do something that takes a long time, so we
                    // spin off a thread and update the display when we're done.
            RunQuery worker = new RunQuery();
View Full Code Here


      Thread.sleep(500);
    } catch (Exception e) {
      e.printStackTrace();
    }
   
    ShipEntity myShip = null// the my own ship to be queried
   
    // find the first naval ship (the ship to be queried in this batch mode query)
    for (ShipEntity ship : DataBase.getInstance().getShips()) {
      if (ship.getShipType() == ShipType.NAVAL) {
        myShip = ship;
        break;
      }
    }
    if (myShip == null) {
      System.err.println("No ship to query");
      return;
    }
   
    // set up log info
    String shipName = "Ship" + DataBase.getInstance().getShips().indexOf(myShip);
   
    // set up query info
    myShip.setShipName(shipName);
    try {
      long heapBeforeQuery = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
     
//      System.out.println("[" + new Date() + "] preparing area query on ship " + myShip.getShipName() + ", area is " + World.This().getDetectingMile() + "nautic miles.");
//      System.out.println("[" + new Date() + "] memory/heap before preparation of query of ship " + myShip.getShipName() + " is " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
     
     
      List<Query> queryList = new ArrayList<Query>();
      Map<Query,ShipEntity> shipEntitiesInQuery = new HashMap<Query,ShipEntity>()// just to store what ship entities were included in query
     
     
      // delete all evidences of previous query.
      // This is needed because we are calling populateRelevantKB(shipNear, false), which does not remove previously entered evidences
      resetKB();
     
      //find all ships which is near to the selected ship.
      //and set evidences up.
      ArrayList<Unit> ships = World.This().getNearShips(myShip.getShipName());
      for(Unit s: ships){
        // find ships nearby
        ShipEntity shipNear = DataBase.getInstance().getShipByName(s.getName());
       
        // never query naval ships, because we are only interested on terrorist ships, and naval ships are assumed to be safe
        // this also guarantees that my own ship is never queried (we assume my own ship has no terrorist crew)
        if (shipNear.getShipType() == ShipType.NAVAL) {
          continue// ignore naval ships
        }
       
        if (isToUseMultipleQuery) {
          // populate knowledge base without removing evidences of previously entered ship
          PrognosController.this.populateRelevantKB(shipNear, false);
        } else {
          // it is supposed to fill KB before each query
        }
       
        // add to query
        Query query = PrognosController.this.setupQuery(shipNear);
        queryList.add(query);
        shipEntitiesInQuery.put(query,shipNear);
      }
     
//      System.out.println("[" + new Date() + "] took " + (System.currentTimeMillis() - time) + " ms to prepare for query on ship " + myShip.getShipName());
      long timeForPreparation = (System.currentTimeMillis() - time);
     
     
//      System.out.println("[" + new Date() + "] heap usage after preparation of query of " + myShip.getShipName() + " is " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));

      // store reasoning mode, for log purpose
      String reasoningModeLabel = isToUseMultipleQuery?(isContinuousCase()?"CONTINUOUS":"DISCRETE"):(isContinuousCase()?"CONTINUOUS_SEQUENTIAL":"DISCRETE_SEQUENTIAL")
     
      long timeForQuery = 0// will store time needed to perform query
     
      // mapping between ship's ID and how many iteration the reasoner used in order to get results
      Map<Integer, Integer> iterationQuantityMap = new HashMap<Integer, Integer>();
      // mapping between ship's ID and how long it took to query that ship. This is only useful if we are doing sequential query
      // (i.e. query each ship one by one instead of querying them altogether)
      Map<Integer, Long> executionTimeMap = new HashMap<Integer, Long>();
     
      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
View Full Code Here

               
              //find all ships which is near to the selected ship.
                //and set evidences up.
                ArrayList<Unit> ships = World.This().getNearShips(ship.getShipName());
                for(Unit s: ships){
                  ShipEntity shipNear = DataBase.getInstance().getShipByName(s.getName());
                  if (isToIgnoreNavalShipsInAreaQuery() && shipNear.getShipType().equals(ShipType.NAVAL)) {
                    continue;
                  }
                  // populate knowledge base without removing evidences of previously entered ship
                  PrognosController.this.populateRelevantKB(shipNear, false);
                  queryList.add(PrognosController.this.setupQuery(shipNear));
View Full Code Here

   *
   * @param per the person
   * @return the person
   */
  private String getPerson(String per) {
    ShipEntity se = DataBase.getInstance().getShipByName(ship);
    for(PersonEntity pe : se.getCrew()){
      String temp = per;
      temp = temp.toUpperCase();
      int personID = Integer.valueOf(temp.replaceAll("PERSON", ""));
      if(pe.getID() == personID){
        return per;
View Full Code Here

   * In a exchange bombing port plan, a ship is going to be a suicide ship to
   * bomb a port, which is different than the original destination port.
   */
  private void generateBombingPortPlan(BombingPortPlan plan) {
    // Choose a random merchant ship as the suicide ship
    ShipEntity ship = getRandomShip(ShipType.MERCHANT);
    ship.setTerroristPlan(plan);
    plan.setShip(ship);
    ship.setShipOfInterest(true);

    // Define the reason for terrorist plan: the ship was hijacked
    // or there is a terrorist crew member
    // Let's assume 50% chance for each
    if (Math.random() <= 1 / 2f) {
      ship.setHijacked(true);
    } else {
      ship.setHijacked(false);
      assignTerroristCrewMember(ship);
    }

    // Define the attributes of the ship based on its normal behavior
    // for this type of plan.
View Full Code Here

    }
  }

  private void generateShips() {
    for (int i = 0; i < nShips; i++) {
      ShipEntity ship = new ShipEntity(i);
      if (i < nNavalShips) {
        ship.setShipType(ShipType.NAVAL);
      } else if (i < nNavalShips + nFishingShips) {
        ship.setShipType(ShipType.FISHING);
      } else {
        ship.setShipType(ShipType.MERCHANT);
      }
      db.addShip(ship);
    }
  }
View Full Code Here

    }
   
    Unit ships = TDB.This().get("TDBROOT.MODEL.WORLD.SHIPS");
    for (Unit ship : ships.list) {
      int id = ships.list.indexOf(ship);
      ShipEntity shipEntity = db.getShips().get(id);

      String strRoute = ship.get("Route").getData();
      String strMeeting = ship.get("Meeting").getData();
     
      if( strRoute.equalsIgnoreCase("Unusual")){
        shipEntity.setOnUnusualRoute(true);
        shipEntity.setOnUsualRoute(false);
      }else
      if( strRoute.equalsIgnoreCase("Usual")){
        shipEntity.setOnUnusualRoute(false);
        shipEntity.setOnUsualRoute(true);
      }
   
      if( !strMeeting.equalsIgnoreCase("none")){
        //do something with shipEntity
        //EX) strMeeting = ship1 and a current ship is ship0
        ArrayList<ShipEntity> possibleMeeting = shipEntity.getPossibleMeeting();
        int idMeeting = ships.list.indexOf(strMeeting);
        ShipEntity shipEntityMet = db.getShips().get(id);
       
        if(!possibleMeeting.contains(shipEntityMet)){
          possibleMeeting.add(shipEntityMet);
        }
      }
View Full Code Here

   * @param shipType The type of the random ship to get.
   * @return a ship of the given type that does not have a terrorist plan yet.
   */
  private ShipEntity getRandomShip(ShipType shipType) {
    int rand = getRandom(0, nShips - 1);
    ShipEntity ship = db.getShips().get(rand);
    // Keep trying to get a random ship of shipType.
    while (ship.getShipType() != shipType || ship.hasTerroristPlan()) {
      rand = getRandom(0, nShips - 1);
      ship = db.getShips().get(rand);
    }
    return ship;
  }
View Full Code Here

   * either another merchant ship or a fishing ship for exchanging the illicit
   * cargo
   */
  private void generateExchangeIllicitCargoPlan(ExchangeIllicitCargoPlan plan) {
    // Choose a random merchant ship as the main ship
    ShipEntity mainShip = getRandomShip(ShipType.MERCHANT);
    mainShip.setTerroristPlan(plan);
    plan.setMainShip(mainShip);
    mainShip.setShipOfInterest(true);

    // Define the reason for terrorist plan: the ship was hijacked
    // or there is a terrorist crew member
    // Let's assume 50% chance for each
    if (Math.random() <= 1 / 2f) {
      mainShip.setHijacked(true);
    } else {
      mainShip.setHijacked(false);
      assignTerroristCrewMember(mainShip);
    }

    // Define which ship is going to meet the main ship, in other words, the
    // secondary ship. It can be either a fishing or merchant ship. Let's
    // assume 50% chance for each.
    ShipEntity secondaryShip;
    if (Math.random() <= 1 / 2f) {
      secondaryShip = getRandomShip(ShipType.FISHING);
    } else {
      secondaryShip = getRandomShip(ShipType.MERCHANT);
    }
    secondaryShip.setTerroristPlan(plan);
    plan.setSecondaryShip(secondaryShip);
    secondaryShip.setShipOfInterest(true);

    // Define the reason for terrorist plan on secondary ship: the ship was
    // hijacked or there is a terrorist crew member
    // Let's assume 50% chance for each
    if (Math.random() <= 1 / 2f) {
      secondaryShip.setHijacked(true);
    } else {
      secondaryShip.setHijacked(false);
      assignTerroristCrewMember(secondaryShip);
    }

    // Define the attributes of the main ship based on its normal behavior
    // for this type of plan.
View Full Code Here

TOP

Related Classes of groundTruthModule.datastructure.ShipEntity

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.