Examples of ISSBNLogManager


Examples of unbbayes.io.log.ISSBNLogManager

   
    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{
        List<SSBNNode> listSSBNNode = this.getSimpleSSBNNodeTranslator().translateSimpleSSBNNodeListToSSBNNodeList(ssbn.getSimpleSsbnNodeList(), pn);
          ssbn.setSsbnNodeList(listSSBNNode);
        ssbn.setProbabilisticNetwork(pn);
//      }
      if (logManager != null) {
        logManager.skipLine();
      }
     
    } catch (SSBNNodeGeneralException e) {
      e.printStackTrace();
      throw e;
    } catch (ImplementationRestrictionException e) {
      //This exception don't should be throw in a correct algorithm.
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    }
   
    if (logManager != null) {
      logManager.printText(level2, false, "Simple Nodes translated to SSBNNodes");
    }
   
    // clearing simple ssbn nodes
    if (isClearSimpleSSBNNodeListAfterLPD()) {
      ssbn.getSimpleSsbnNodeList().clear();
      // clearing memory before we continue
//      System.gc();
    }

      CPTForSSBNNodeGenerator build = this.getCptForSSBNNodeGeneratorBuilder().buildCPTForSSBNNodeGenerator(logManager);
     
      if(ssbn.getSsbnNodeList().size() > 0){
        if (logManager != null) {
        logManager.printText(level2, false, "Generate CPT for the SSBNNodes");
        }
        build.generateCPTForAllSSBNNodes(ssbn);
      }else{
        throw new SSBNNodeGeneralException(getHybridResource().getString("NotNodeInSSBN"));
      }
View Full Code Here

Examples of unbbayes.io.log.ISSBNLogManager

      ssbn = initialization(queryList, knowledgeBase);
      ssbn.setParameters(parameters);
    }
   
   
    ISSBNLogManager logManager = ssbn.getLogManager();
   
    //Step 2:
    if(Boolean.valueOf(parameters.getParameterValue(LaskeyAlgorithmParameters.DO_BUILDER))){
     
      if (logManager != null) {
        logManager.skipLine();
        logManager.printText(null, false, resourceLog.getString("004_Step2_BuildingGrandBN"));
        logManager.skipLine();
      }
     
      getBuilderStructure().buildStructure(ssbn);
     
      if (logManager != null) {
        logManager.printText(null, false, resourceLog.getString("010_StepFinished"));
        logManager.skipLine();
        logManager.printBox2Bar();
        logManager.printBox2("List of nodes: ");
       
        printSimpleSSBNNodeList(ssbn);
       
        logManager.printBox2Bar();
        logManager.skipLine();
        logManager.printSectionSeparation();
      }
     
    }
   
    //Step 3:
    if(Boolean.valueOf(parameters.getParameterValue(LaskeyAlgorithmParameters.DO_PRUNE))){
     
      if (logManager != null) {
        logManager.skipLine();
        ssbn.getLogManager().printText(null, false, resourceLog.getString("005_Step3_PruneGrandBN"));
        ssbn.getLogManager().skipLine();
      }
     
      getPruneStructure().pruneStructure(ssbn);
     
      if (logManager != null) {
        logManager.printText(null, false, resourceLog.getString("010_StepFinished"));
        logManager.skipLine();
        logManager.printBox2Bar();
        logManager.printBox2("List of nodes: ");
       
        printSimpleSSBNNodeList(ssbn);
       
        logManager.printBox2Bar();
        logManager.skipLine();
        logManager.printSectionSeparation();
      }
    }
   
    //Step 4:
    if(Boolean.valueOf(parameters.getParameterValue(LaskeyAlgorithmParameters.DO_CPT_GENERATION))){
     
      if (logManager != null) {
        logManager.skipLine();
        logManager.printText(null, false, resourceLog.getString("006_Step4_BuildCPT"));
        logManager.skipLine();
      }
     
      getBuildLocalDistribution().buildLocalDistribution(ssbn);
     
      if (logManager != null) {
        logManager.printText(null, false, resourceLog.getString("010_StepFinished"));
        logManager.skipLine();
        logManager.printSectionSeparation();
      }
    }
   
    // adjust position of nodes
    try {
      PositionAdjustmentUtils.adjustPositionProbabilisticNetwork(ssbn.getProbabilisticNetwork());
    } catch (Exception e) {
      Debug.println(getClass(), e.getMessage(), e);
    }
   
   
    if (logManager != null) {
      long time1 = System.currentTimeMillis();
      long deltaTime = time1 - time0;
     
      SSBNDebugInformationUtil.printAndSaveCurrentNetwork(ssbn);
      logManager.printBox1Bar();
      logManager.printBox1(resourceLog.getString("007_ExecutionSucces"));
      logManager.printBox1(resourceLog.getString("009_Time") + ": " + deltaTime + " ms");
      logManager.printBox1Bar();
      logManager.skipLine();
    }
   
    this.cleanUpSSBN(ssbn);
   
    if (ssbn.getNetwork().getNodeCount() != ssbn.getNetwork().getNodeIndexes().keySet().size()) {
View Full Code Here

Examples of unbbayes.io.log.ISSBNLogManager

    }
   
    MultiEntityBayesianNetwork mebn = null;

    //log
    ISSBNLogManager logManager = ssbn.getLogManager();
    if (logManager != null) {
      logManager.printBox1Bar();
      logManager.printBox1(getResourceForHybridAlgorithm().getString("001_Title"));
      logManager.printBox1("Queries:");
      for(int i = 0; i < queryList.size(); i++){
        logManager.printBox1("    (" + i + ") " + queryList.get(i).toString());
      }
      logManager.printBox1(getResourceForHybridAlgorithm().getString("002_Algorithm") + ": " +
          getResourceForHybridAlgorithm().getString("002_001_LaskeyAlgorithm"));
      logManager.printBox1Bar();
     
      logManager.skipLine();
      logManager.printText(null, false, getResourceForHybridAlgorithm().getString("003_Step1_Initialization"));
      logManager.skipLine();
    }
   
    ssbn.setKnowledgeBase(knowledgeBase);
   
    //We assume that all the queries is referent to the same MEBN
    mebn = queryList.get(0).getMebn();
   
    //Parameters:

    IdentationLevel in = new IdentationLevel(null);
   
    //Add queries to the list of nodes
    IdentationLevel in1 = new IdentationLevel(in);
    if (logManager != null) {
      logManager.printText(in1, true,
        getResourceForHybridAlgorithm().getString("011_BuildingSSBNForQueries"));
    }
   
    for(Query query: queryList){
      SimpleSSBNNode ssbnNode = SimpleSSBNNode.getInstance(query.getResidentNode());
      query.setSSBNNode(ssbnNode);
     
      for(OVInstance argument : query.getArguments()){
        ssbnNode.setEntityForOv(argument.getOv(), argument.getEntity());  
      }
     
      ssbnNode.setFinished(false);
      ssbn.addSSBNNodeIfItDontAdded(ssbnNode);
      ssbn.addQueryToTheQueryList(query);
     
      if (logManager != null) {
        logManager.printText(in1, false, " - " + ssbnNode);
      }
                                                                         
    }
   
    if (logManager != null) {
      logManager.skipLine();
    }
   
    //Add findings to the list of nodes
   
    in1 = new IdentationLevel(in);
    if (logManager != null) {
      logManager.printText(in1, true,
        getResourceForHybridAlgorithm().getString("012_BuildingSSBNForFindings"));
    }
   
    for(MFrag mFrag: mebn.getMFragList()){
      for(ResidentNode residentNode: mFrag.getResidentNodeList()){
        for(RandomVariableFinding finding: residentNode.getRandomVariableFindingList()){
         
          if (logManager != null) {
            logManager.printText(in1, false, " - " + finding);
          }
         
          ObjectEntityInstance arguments[] = finding.getArguments();
          List<OVInstance> ovInstanceList = new ArrayList<OVInstance>();
          for(int i = 0; i < arguments.length ; i++){
            OrdinaryVariable ov = residentNode.getArgumentNumber(i + 1).getOVariable();
            LiteralEntityInstance lei = LiteralEntityInstance.getInstance(arguments[i].getName() , ov.getValueType());
            ovInstanceList.add(OVInstance.getInstance(ov, lei));
          }
         
          SimpleSSBNNode ssbnNode = SimpleSSBNNode.getInstance(residentNode);
         
          for(OVInstance argument : ovInstanceList){
            ssbnNode.setEntityForOv(argument.getOv(), argument.getEntity());  
          }
          ssbnNode = ssbn.addSSBNNodeIfItDontAdded(ssbnNode);
         
          ssbnNode.setState(finding.getState());
          ssbnNode.setFinished(false);
         
          ssbn.addFindingToTheFindingList(ssbnNode);
        }
      }
    }
   
    if (logManager != null) {
      logManager.skipLine();
      logManager.printText(null, false, getResourceForHybridAlgorithm().getString("010_StepFinished"));
      logManager.skipLine();
      logManager.printSectionSeparation();
    }
   
    // add continuous nodes to the list of initial nodes
    if (isToAddAllContinuousNodes()) {
      for(MFrag mfrag: mebn.getMFragList()){
        // we are creating one continuous SSBN node per each possible combination of arguments in a continuous resident node
        for (Node node : mfrag.getNodes()) {
          if (node instanceof ContinuousResidentNode) {
           
            ContinuousResidentNode continuousResidentNode = (ContinuousResidentNode) node;
            if (continuousResidentNode.getOrdinaryVariableList() == null
                || continuousResidentNode.getOrdinaryVariableList().isEmpty()) {
              continue// go to next node
            }
           
            // prepare all possible combinations of arguments. The ovs are synchronized by index
            boolean hasAtLeastOneCombination = true// true if all Lists in combinator were filled
            List<List<LiteralEntityInstance>> combinator = new ArrayList<List<LiteralEntityInstance>>();
            for (OrdinaryVariable ov : continuousResidentNode.getOrdinaryVariableList()) {
              List<LiteralEntityInstance> contentOfCombinator = new ArrayList<LiteralEntityInstance>();
              // get all values for ov
              List<String> ovValues = knowledgeBase.getEntityByType(ov.getValueType().getName());
              if (ovValues.isEmpty()) {
                // this iterator cannot be filled, because ov has no possible values
                hasAtLeastOneCombination = false;
                break;
              }
              // add all possible values for ov
              for (String ovValue : ovValues) {
                contentOfCombinator.add(LiteralEntityInstance.getInstance(ovValue, ov.getValueType()));
              }
              combinator.add(contentOfCombinator);
            }
           
            // do not add node if there is some ov with no possible value (that means, no combination can be created)
            if (!hasAtLeastOneCombination) {
              continue// go to next continuous node
            }
           
            // list of indexes of combinator
            List<Integer> indexes = new ArrayList<Integer>(combinator.size());
            for (int i = 0; i < combinator.size(); i++) {
              // Note that at this point, each list in combinator has at least 1 element, because hasAtLeastOneCombination == true (so, 0 is a valid index)
              indexes.add(0);
            }
           
            /*
             * iterate on combinator using indexes.
             * E.g.:  combinator = {{a,b},{1,2}};
             *       then indexes must iterate like:
             *       {0,0}  (means (a,1));
             *       {1,0}  (means (b,1));
             *       {0,1}  (means (a,2));
             *       {1,1}  (means (b,2));
             *  
             */
            while (hasAtLeastOneCombination) {
             
              // create a continuous ssbn node for each possible combination of combinator
              SimpleSSBNNode ssbnNode = SimpleSSBNNode.getInstance(continuousResidentNode);
              ssbnNode.setFinished(false);
             
              // fill arguments of ssbnNode
              for (int i = 0; i < continuousResidentNode.getOrdinaryVariableList().size(); i++) {
                ssbnNode.setEntityForOv(
                    continuousResidentNode.getOrdinaryVariableList().get(i),
                    combinator.get(i).get(indexes.get(i))
                );
              }
             
              if (logManager != null) {
                logManager.printText(in1, false, " - " + ssbnNode);
              }
             
              ssbn.addSSBNNodeIfItDontAdded(ssbnNode);
             
              // update indexes and check condition to end loop (it ends when all possible combinations were visited)
              for (int i = 0; i < combinator.size(); i++) { 
                // OBS. combinator, indexes and continuousResidentNode.getOrdinaryVariableList() have same size and are synchronized.
                Integer newIndex = indexes.get(i) + 1// obtain current step + 1
                // reset index if there is no mode element in this list
                if (newIndex >= combinator.get(i).size()) {
                  // but if this is the last list, there is no more possible combination
                  if (i >= combinator.size() - 1) {
                    // there is no more combination
                    hasAtLeastOneCombination = false;
                    break;
                  } else {
                    newIndex = 0// reset
                  }
                }
                indexes.set(i, newIndex)// update step
                if (newIndex > 0) {
                  // if we did not reset this index, we do not need to update the following indexes
                  break;
                }
              }
             
            }  // while only ends when combinator was completely iterated
           
           
          // if node is a continuous resident node
        // for each node in mfrag
      // for each mfrag
    }
   
    if (logManager != null) {
      logManager.skipLine();
      logManager.printSectionSeparation();
    }
   
    return ssbn;
   
  }
View Full Code Here

Examples of unbbayes.io.log.ISSBNLogManager

   * create a log the ssbn using its related log manager. The content of the log
   * is going to be the information of all nodes in the ssbn
   * @param ssbn
   */
  protected void printSimpleSSBNNodeList(SSBN ssbn) {
    ISSBNLogManager logManager = ssbn.getLogManager();
    if (logManager != null) {
      for(SimpleSSBNNode node: ssbn.getSimpleSsbnNodeList()){
        String parentIdList = " ";
        for(INode nodeParent: node.getParentNodes()){
          parentIdList+= ((SimpleSSBNNode)nodeParent).getId() + " ";
        }
        logManager.printBox2(
            "   - " + node.toString() + " Parents = [" + parentIdList +"]");
      }
      logManager.appendln("");
    }
  }
View Full Code Here

Examples of unbbayes.io.log.ISSBNLogManager

   
    int iteration = 0;
   
      level1 =  new IdentationLevel(null);
   
    ISSBNLogManager logManager = ssbn.getLogManager();
   
    if (logManager != null) {
      logManager.skipLine();
    }
   
    while(!notFinishedNodeList.isEmpty()){
     
      if (logManager != null) {
        logManager.printText(level1, false,
          resourceLog.getString("012_IterationNumber") + " "  + iteration);
      }
     
      for(SimpleSSBNNode node: notFinishedNodeList){
            try {
          evaluateUnfinishedRV(node);
        } catch (ImplementationRestrictionException e) {
          e.printStackTrace();
          throw e;
        } catch (SSBNNodeGeneralException e) {
          e.printStackTrace();
          throw e;
        }
      }
     
      //update the not finished list
      notFinishedNodeList.clear();

      if (logManager != null) {
        logManager.skipLine();
        logManager.printText(level1, false,
          resourceLog.getString("013_NotFinishedNodesList") + ": ");
      }
     
      for(SimpleSSBNNode node: ssbn.getSimpleSsbnNodeList()){
        if(!node.isFinished()){
          if (logManager != null) {
            logManager.printText(level1, false, " - " + node.toString());
          }
          notFinishedNodeList.add(node);
        }
      }
     
      if (logManager != null) {
        logManager.skipLine();
      }
      iteration++;
     
    }
  }
View Full Code Here

Examples of unbbayes.io.log.ISSBNLogManager

   
    IdentationLevel thisLevel2;
    level2 = new IdentationLevel(level1);
    thisLevel2 = level2;
   
    ISSBNLogManager logManager = ssbn.getLogManager();
    if (logManager != null) {
      logManager.printText(level2, false, "Evaluate unfinished node" + ": " + node);
    }
    //Note: In this implementation don't is averiguated if already have a equal MFragInstance.
   
    //Build the MFragInstance related to the node
    MFragInstance mFragInstance = MFragInstance.getInstance(node.getResidentNode().getMFrag());
   
    //Add the arguments
    for(int i = 0; i < node.getOvArray().length; i++){
      try {
        mFragInstance.addOVValue(node.getOvArray()[i], node.getEntityArray()[i].getInstanceName());
      } catch (MFragContextFailException e) {
        //this is a bug... the context can't fail here.
        throw new SSBNNodeGeneralException(e.getMessage());
      }
    }
   
    node.setMFragInstance(mFragInstance);
   
    //Evaluate the mFragInstances and create the nodes of its.
    evaluateMFragInstance(mFragInstance, node);
   
    node.setFinished(true);
   
    if (logManager != null) {
      logManager.printText(thisLevel2, true, "Unfinished node = " + node + " setted true");
      logManager.skipLine();
    }
  }
View Full Code Here

Examples of unbbayes.io.log.ISSBNLogManager

   * @throws SSBNNodeGeneralException
   */
  private void evaluateMFragInstance(MFragInstance mFragInstance, SimpleSSBNNode ssbnNode)
        throws ImplementationRestrictionException, SSBNNodeGeneralException{
   
    ISSBNLogManager logManager = ssbn.getLogManager();
    if (logManager != null) {
      logManager.printText(level2, true, "Evaluate MFragInstance" + mFragInstance);
    }
    // 1) Test if the MFragInstance already was evaluated
    if(mFragInstance.isEvaluated()){
      return; //Be careful here if you change the algorithm for search for
              //mFragInstances equal to the that are evaluated... In this case
              //maybe a new evaluation of the mfrag will be necessary
              //because the enter node should be other.
    }
   
      // 2) Evaluate MFragInstance context
    try {
      level3 = new IdentationLevel(level2);
      if (logManager != null) {
        logManager.printText(level3, true, "Evaluate MFrag Context Nodes");
      }
      evaluateMFragContextNodes(mFragInstance);
     
    } catch (ImplementationRestrictionException e) {
      //Stop the evaluation when the context nodes fail.
      //TODO warning... the evaluation continue, using the default distribution
//      throw e;
//    } catch (OVInstanceFaultException e) {
//      throw new ImplementationRestrictionException(e.getMessage());
    } catch (MFragContextFailException e) {
      //TODO warning... the evaluation continue, using the default distribution
//      throw new SSBNNodeGeneralException(e.getMessage());
    }
   
    // 3) Create the nodes of the MFragInstance
    level3 = new IdentationLevel(level2);
    if (logManager != null) {
      logManager.printText(level3, true, "Create the nodes of MFrag ");
    }
    evaluateNodeInMFragInstance(mFragInstance, ssbnNode)
   
 
View Full Code Here

Examples of unbbayes.io.log.ISSBNLogManager

   */
  private void evaluateNodeInMFragInstance(MFragInstance mFragInstance, SimpleSSBNNode node)
         throws ImplementationRestrictionException, SSBNNodeGeneralException{
   
    level4 = new IdentationLevel(level3);
    ISSBNLogManager logManager = ssbn.getLogManager();
    if (logManager != null) {
      logManager.printText(level4, false, "Create parents of node " + node);
    }
   
    node.setMFragInstance(mFragInstance);
   
    //--- 1) Evaluate if the node is a finding.
   
    IResidentNode resident = node.getResidentNode();
   
    List<OVInstance> argumentList = new ArrayList<OVInstance>();
   
    for(int i = 0; i < node.getOvArray().length; i++){
      argumentList.add(OVInstance.getInstance(node.getOvArray()[i], node.getEntityArray()[i]));
    }
   
    StateLink exactValue = kb.searchFinding(
        node.getResidentNode(), argumentList);
   
    /*
     * Nota: como o algoritmo apenas sobe, é necessário continuar a avaliação
     * acima mesmo quando o nó for setado como um finding, pois acima dele pode
     * ter uma query ou nó que influência a query. (Caso fosse feita a avaliação
     * acima e abaixo, não seria necessária esta subida, mas o algoritmo seria
     * mais complexo). Isto gerará um monte de nós candidados a serem excluidos
     * no próximo passo. 
     */
    if(exactValue!= null){
      //The node is a finding...
      node.setState(exactValue.getState());
      ssbn.addFindingToTheFindingList(node);
     
      if (logManager != null) {
        logManager.printText(level4, false, " -> Node " + node +
          " set as a finding. Exact Value = " + exactValue);
      }
    }
   
   
    //---- 2) Create the parents of node from the resident nodes
   
    //If the context node of the MFrag don't are evaluated, the creation of
    //the parents isn't possible
    if(mFragInstance.isUseDefaultDistribution()){
     
      if (logManager != null) {
        logManager.printText(level4, false, " -> Node can't be evaluated: mfrag using default distribution");
      }
      return;
   
    }
   
    OrdinaryVariable[] ovFilledArray = node.getOvArray();
    LiteralEntityInstance[] entityFilledArray = node.getEntityArray();
 
    if (logManager != null) {
      logManager.printText(level4, false, " 1) Evaluate the resident node parents");
    }
    for(ResidentNode residentNodeParent: resident.getResidentNodeFatherList()){
     
      List<SimpleSSBNNode> createdNodesList = createParents(node,
          ovFilledArray, entityFilledArray, residentNodeParent);
     
      if (logManager != null) {
        logManager.printText(level4, false, "Resident parents generates from the resident node " +
          residentNodeParent);
      }
      int count = 0;
      for(SimpleSSBNNode newNode: createdNodesList){
        if (logManager != null) {
          logManager.printText(level4, false, "Evaluate " + count + " - "+ newNode);
        }
        count= count + 1 ;
        evaluateNodeInMFragInstance(mFragInstance, newNode);
      }
     
    }
   
    //---- 3) Create the parents of node from the input nodes
    if (logManager != null) {
      logManager.printText(level4, false, " 2) Evaluate the input node parents");
    }
    for(InputNode inputNodeParent: resident.getParentInputNodesList()){
     
      if(inputNodeParent.getResidentNodePointer().getResidentNode().equals(resident)){
        //Special case: the recursivity.
        if (logManager != null) {
          logManager.printText(level4, false, " Recursivity treatment: " + resident);
        }
       
        SimpleSSBNNode newNode = createRecursiveParents(node, ovFilledArray,
            entityFilledArray, inputNodeParent);
       
        if(newNode != null){
          evaluateNodeInMFragInstance(mFragInstance, newNode);
        }
       
      }else{
        List<SimpleSSBNNode> createdNodesList = createParents(node, ovFilledArray,
            entityFilledArray, inputNodeParent)
      }
     
    }
   
    node.setFinished(true);
    if (logManager != null) {
      logManager.printText(level4, false, "Node " + node + " setted finished");
    }

    mFragInstance.setEvaluated(true);
  }
View Full Code Here

Examples of unbbayes.io.log.ISSBNLogManager

   
    //Consider that the tree with the know ordinary variables are already mounted.
    //Consider that the only ordinary variables filled are the alread know OV
    List<OVInstance> ovInstances = mFragInstance.getOVInstanceList();
   
    ISSBNLogManager logManager = ssbn.getLogManager();
    if (logManager != null) {
      logManager.printText(level4, false, "1) Loop for evaluate context nodes.");
    }
    for(ContextNode contextNode: mFragInstance.getContextNodeList()){
     
      if (logManager != null) {
        logManager.printText(level4, false, "Context Node: " + contextNode);
      }
     
      //---> 1) Verify if the context node is soluted only with the know arguments.
      List<OrdinaryVariable> ovInstancesFault = contextNode.getOVFaultForOVInstanceSet(ovInstances);
     
      level5 = new IdentationLevel(level4);
      if(ovInstancesFault.size() == 0){
       
        if (logManager != null) {
          logManager.printText(level5, false, "All ov's of the context node are setted");
        }
        boolean result = kb.evaluateContextNodeFormula(contextNode, ovInstances);
        if(result){
          mFragInstance.setStateEvaluationOfContextNode(contextNode,
              ContextNodeEvaluationState.EVALUATION_OK);
          if (logManager != null) {
            logManager.printText(level5, false, "Node evaluated OK");
          }
          continue;
        }else{
          mFragInstance.setStateEvaluationOfContextNode(contextNode,
              ContextNodeEvaluationState.EVALUATION_FAIL);
          mFragInstance.setUseDefaultDistribution(true);
          if (logManager != null) {
            logManager.printText(level5, false, "Node evaluated FALSE");
          }
          continue; //The MFragInstance continue to be evaluated only
                    //to show to the user a network more complete.
        }
      }else{
     
        if (logManager != null) {
          logManager.printText(level5, false, "Some ov's of the context node aren't filled");
          logManager.printText(level5, false, "Try 1: Use the search strategy");
        }
       
       
        //---> 2) Use the Entity Tree Strategy.
        SearchResult searchResult = kb.evaluateSearchContextNodeFormula(contextNode, ovInstances);

        if(searchResult!= null){ 

          if (logManager != null) {
            logManager.printText(level5, false, "Search Result: ");
            for(String[] result: searchResult.getValuesResultList()){
              String resultOv = " > ";
              for(int i = 0; i < result.length; i++){
                resultOv += result[i] + " ";
              }
              logManager.printText(level5, false, resultOv);
            }
          }
         
          //Result valid results: Add the result to the tree of result.
          try {

            mFragInstance.addOVValuesCombination(
                searchResult.getOrdinaryVariableSequence(),
                searchResult.getValuesResultList());

            mFragInstance.setStateEvaluationOfContextNode(contextNode, ContextNodeEvaluationState.EVALUATION_OK);
           
            if (logManager != null) {
              logManager.printText(level5, false, "Node evaluated OK");
            }
           
          } catch (MFragContextFailException e) {
           
            e.printStackTrace();
           
            mFragInstance.setStateEvaluationOfContextNode(contextNode, ContextNodeEvaluationState.EVALUATION_FAIL);
            mFragInstance.setUseDefaultDistribution(true);
            if (logManager != null) {
              logManager.printText(level5, false,"Context Node FAIL: use the default distribution");
            }
           
            //Here, the context node fail adding the values for a ordinary variable
            //fault. This fail impossibilite the evaluation of the rest of the MFragInstance,
            //because, this node, used to recover the possible values, fail.
            throw e;
          }

          continue;

        }else{

//          ssbn.getLogManager().printText(level5, false, "Try 2: Use the iteration strategy");
//          ssbn.getLogManager().printText(level5, false, "...still not implemented.\n");
         
          //---> 3) Use the Interation with user Strategy.
          //TODO To be developed yet...
         
          //Note: if the user add new variables, this should alter the result
          //of previous avaliations... maybe all the algorithm should be
          //evaluated again. A solution is only permit that the user
          //add a entity already at the knowledge base. The entity added
          //should be put again the evaluation tree for verify possible
          //inconsistency.
         
//          notInstanciatedOVList = mFragInstance.getListNotInstanciatedOV();
//          Debug.println("\nOVInstances don't found = " + notInstanciatedOVList.size());
//          for(OrdinaryVariable ov: notInstanciatedOVList){
//            Debug.println(ov.getName());
//          }
//          if (notInstanciatedOVList.size() != 0){
//            Debug.println("Try 2: Use the iteration aproach");
//            for(OrdinaryVariable ov: notInstanciatedOVList){
//              if(interationHelper!=null){
//                OVInstance ovInstance = interationHelper.getInstanceValueForOVFault(ov);
//                if(ovInstance != null){
//                  mFragInstance.addInstanciatedOV(ovInstance.getOv(),  ovInstance.getEntity());
//                }
//              }
//            }
//          }

          //---> 4) Use the uncertainty Strategy.
          if (logManager != null) {
            logManager.printText(level5, false,
              "Try 2: Use the uncertain reference strategy");
          }
         
          //Utilized only in the specific case z = RandomVariable(x),
          //where z is the unknow variable. (Should have only one unknow variable)
         
          SimpleContextNodeFatherSSBNNode simpleContextNodeFather = null;
         
          if(ovInstancesFault.size() == 1){
            try{
              simpleContextNodeFather =
                evaluateUncertaintyReferenceCase(mFragInstance,
                    contextNode, ovInstancesFault.get(0));
              if(simpleContextNodeFather != null){
                continue; //OK!!! Good!!! Yes!!!
              }
            }
            catch(ImplementationRestrictionException e){
              mFragInstance.setUseDefaultDistribution(true);
              if (logManager != null) {
                logManager.printText(level5, false, "Fail: " + e.getMessage());
              }
            }
          }
         
          //--> 5) Nothing more to try... context fail
          if (logManager != null) {
            logManager.printText(level4, false,"Still ov fault... nothing more to do. " +
              "Use default distribution");
          }
          mFragInstance.setStateEvaluationOfContextNode(contextNode,
              ContextNodeEvaluationState.EVALUATION_FAIL);
          mFragInstance.setUseDefaultDistribution(true);
          //TODO Maybe a warning... Not so drastic!
         
        }
      }
     
    }
   
   
    if (logManager != null) {
      logManager.printText(level4, false,"2) Loop for evaluate the IsA nodes");
    }
   
    //Return a list of ordinary variables of the MFrag that don't are evaluated yet.
    List<OrdinaryVariable> ovDontFoundYetList = new ArrayList<OrdinaryVariable>();
    for(OrdinaryVariable ov: mFragInstance.getMFragOrigin().getOrdinaryVariableList()){
      if(mFragInstance.getOVInstanceListForOrdinaryVariable(ov).size() == 0){
        ovDontFoundYetList.add(ov);
      }
    }
   
    //Evaluate this ordinary variables
    for(OrdinaryVariable ov: ovDontFoundYetList){
      //no context node about this ov... the value is unknown, we should
      //consider all the possible values. Note the use of the Closed Word
      //Asspetion.
      if (logManager != null) {
        logManager.printText(level4, false,"Evaluate IsA for OV " + ov.getName());
      }
     
      List<String> possibleValues = kb.getEntityByType(ov.getValueType().getName());
     
      if (logManager != null) {
        for(String possibleValue: possibleValues){
          logManager.printText(level4, false, "  > " + possibleValue);
        }
      }
     
      String possibleValuesArray[] = possibleValues.toArray(new String[possibleValues.size()]);
      List<String[]> entityValuesArray = new ArrayList<String[]>();
     
      for(String possibleValue: possibleValuesArray){
        entityValuesArray.add(new String[]{possibleValue});
      }
                                                                       
      OrdinaryVariable ovArray[] = new OrdinaryVariable[1];
      ovArray[0] = ov;
     
      try {
        mFragInstance.addOVValuesCombination(ovArray, entityValuesArray);
      } catch (MFragContextFailException e) {
//        e.printStackTrace();
        Debug.println(this.getClass(), "", e);
        mFragInstance.setUseDefaultDistribution(true);
      }
    }
   
    if (logManager != null) {
      List<String[]> possibleCombinationsList = mFragInstance.recoverAllCombinationsEntitiesPossibles();
      logManager.printBox3Bar(level4);
      logManager.printBox3(level4, 0, "Result of evalation of the context nodes (Possible combinations): ");
      for(String[] possibleCombination : possibleCombinationsList){
        String ordinaryVariableComb = " > ";
        for(String ordinaryVariableValue: possibleCombination){
          ordinaryVariableComb += " " + ordinaryVariableValue;
        }
        ordinaryVariableComb += " < ";
        logManager.printBox3(level4, 1, ordinaryVariableComb);
      }
      logManager.printBox3Bar(level4);
    }
   
    //Return mFragInstance with the ordinary variables filled.
    return mFragInstance;
  }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.