Package statechum.DeterministicDirectedSparseGraph

Examples of statechum.DeterministicDirectedSparseGraph.CmpVertex


    }

    /** Used to select the best red node based on what the subsequent collection of pairs will be. */
    public static CmpVertex selectRedNodeUsingNumberOfNewRedStates(LearnerGraph coregraph, Collection<CmpVertex> tentativeRedNodes)
    {
      CmpVertex redVertex = null;double bestScore=-1;
     
      // It is not hard to calculate what blue states will directly surround a specific state chosen to become red, however those blue states may in turn immediately become red after evaluation and the same would apply
      // to the newly-discovered red states, so we effectively have to re-implement blue state calculation here. For this reason, it was decided not to do this but instead clone the state machine (possibly in a trimmed form)
      // and ask it for a list of pairs.
      // Assuming that we received red states in the same order as they are encountered by Statechum, it is appropriate to return the first state that has the highest number of reds after mergers,
View Full Code Here


        // (b) checks that deadends are flagged. I could iterate this process for a number of decision rules, looking locally for the one that gives best quality of pairs
        // for a particular pairscore decision procedure.
        @Override
        public CmpVertex selectRedNode(LearnerGraph coregraph, @SuppressWarnings("unused") Collection<CmpVertex> reds, Collection<CmpVertex> tentativeRedNodes)
        {
          CmpVertex redVertex = null;
          if (useClassifierToChooseNextRed)
            redVertex = LearnerThatUsesWekaResults.selectRedNodeUsingNumberOfNewRedStates(coregraph, tentativeRedNodes);
          else
            redVertex = tentativeRedNodes.iterator().next();
         
          return redVertex;
        }

        @Override
        public CmpVertex resolvePotentialDeadEnd(LearnerGraph coregraph, @SuppressWarnings("unused") Collection<CmpVertex> reds, List<PairScore> pairs)
        {
          CmpVertex stateToLabelRed = null;
          List<PairScore> filteredPairs = filterPairsBasedOnMandatoryMerge(pairs,graph);
          if (filteredPairs.isEmpty())
            stateToLabelRed = pairs.get(0).getQ();// if mandatory merge rules out all mergers, return any of the states to be marked red
          else
            if (classifierToChooseWhereNoMergeIsAppropriate)
View Full Code Here

 
  @Test(expected = IllegalArgumentException.class)
  public final void testMerge_fail1a()
  {
    DirectedSparseGraph g=FsmParser.buildGraph(largeGraph1_invalid5,"testMerge_fail1");
    CmpVertex
      a = DeterministicDirectedSparseGraph.findVertexNamed(new VertexID("A"), g),
      b = DeterministicDirectedSparseGraph.findVertexNamed(new VertexID("B"), g);
    StatePair pair = new StatePair(b,a);// A is red
    MergeStates.mergeAndDeterminize(g, pair,testConfig);
  }
View Full Code Here

   
  @Test(expected = IllegalArgumentException.class)
  public final void testMerge_fail2()
  {
    LearnerGraph l=new LearnerGraph(FsmParser.buildGraph(largeGraph1_invalid5,"testMerge_fail1"),testConfig);
    CmpVertex
      a = l.findVertex(new VertexID("A")),
      b = l.findVertex(new VertexID("B"));
    StatePair pair = new StatePair(b,a);// A is red
    MergeStates.mergeAndDeterminize(l, pair);
  }
View Full Code Here

  @Test(expected = IllegalArgumentException.class)
  public final void testMerge_fail3()
  {
    LearnerGraph l=new LearnerGraph(FsmParser.buildGraph(largeGraph1_invalid5,"testMerge_fail1"),testConfig);
    CmpVertex
      a = l.findVertex(new VertexID("A")),
      b = l.findVertex(new VertexID("B"));
    StatePair pair = new StatePair(b,a);// A is red
    MergeStates.mergeAndDeterminize_general(l, pair);
  }
View Full Code Here

  private final void testChooseStatePairsInternal(DirectedSparseGraph g,LearnerGraph l, String [] initialReds, String [][] expectedReds,
      List<PairScore> expectedPairs,InterfaceChooserToTest chooser)
  {
    for(String red:initialReds)
    {
      CmpVertex v = l.findVertex(new VertexID(red));v.setColour(JUConstants.RED);
    }
    Stack<? extends StatePair> pairs = chooser.choosePairs();

    Map<Integer,Set<PairScore>> distribution = new HashMap<Integer,Set<PairScore>>();// maps scores to sets of states which should correspond to them. The aim is to verify the contents of the stack regardless of the order in which elements with the same score are arranged.
View Full Code Here

    public static <TARGET_TYPE,CACHE_TYPE extends CachedData<TARGET_TYPE,CACHE_TYPE>> void setReds(OtpErlangObject obj,AbstractLearnerGraph<TARGET_TYPE,CACHE_TYPE> gr)
    {
      for(OtpErlangObject st:(OtpErlangList)obj)
      {
        String state = ((OtpErlangAtom)st).atomValue();if (state.isEmpty()) throw new IllegalArgumentException("empty state name");
        CmpVertex v=gr.findVertex(VertexID.parseID(state));
        if (v == null) throw new IllegalArgumentException(state+" state not found");
        v.setColour(JUConstants.RED);
      }
    }
View Full Code Here

      gr.initEmpty();
     
      for(OtpErlangObject st:states)
      {
        String state = ((OtpErlangAtom)st).atomValue();if (state.isEmpty()) throw new IllegalArgumentException("empty state name");
        CmpVertex vertex = AbstractLearnerGraph.generateNewCmpVertex(VertexID.parseID( state ), gr.config);
        vertex.setAccept(vertex.getKind() != VertKind.NEGATIVE);
        gr.transitionMatrix.put(vertex,gr.createNewRow());
      }
     
      if (states.arity() != gr.transitionMatrix.size())
        throw new IllegalArgumentException("repeated states in the list of states");
     
      Map<OtpErlangObject,Label> objectToLabel = new HashMap<OtpErlangObject,Label>();
      for(OtpErlangObject l:alphabet)
      {
        String label = ((OtpErlangAtom)l).atomValue();if (label.isEmpty()) throw new IllegalArgumentException("empty label");
        objectToLabel.put(l,AbstractLearnerGraph.generateNewLabel( label,gr.config,converter));
      }
      for(OtpErlangObject transitionObj:transitions)
      {
        OtpErlangTuple transition = (OtpErlangTuple) transitionObj;
        if (transition.arity() != 3)
          throw new IllegalArgumentException("expected 3 components in transition "+transition);
        OtpErlangAtom from = (OtpErlangAtom)transition.elementAt(0),label = (OtpErlangAtom)transition.elementAt(1),to = (OtpErlangAtom)transition.elementAt(2);
        CmpVertex fromState = gr.findVertex(VertexID.parseID(from.atomValue())), toState = gr.findVertex(VertexID.parseID(to.atomValue()));
        if (fromState == null)
          if (!checkStates)
          {
            String state = from.atomValue();if (state.isEmpty()) throw new IllegalArgumentException("empty source state");
            fromState = AbstractLearnerGraph.generateNewCmpVertex(VertexID.parseID( state), gr.config );
            gr.transitionMatrix.put(fromState,gr.createNewRow());
          }
          else
              throw new IllegalArgumentException("invalid source state "+from.atomValue());
       
        if (toState == null)
          if (!checkStates)
          {
            String state = to.atomValue();if (state.isEmpty()) throw new IllegalArgumentException("empty target state");
            toState = AbstractLearnerGraph.generateNewCmpVertex(VertexID.parseID( state), gr.config );
            gr.transitionMatrix.put(toState,gr.createNewRow());
          }
          else
            throw new IllegalArgumentException("invalid target state"+to.atomValue());
       
        if (!objectToLabel.containsKey(label))
        {
          if (!checkStates)
          {
            String l = label.atomValue();if (l.isEmpty()) throw new IllegalArgumentException("empty label");
            objectToLabel.put(label,AbstractLearnerGraph.generateNewLabel( l,gr.config,converter));
          }
          else
            throw new IllegalArgumentException("unknown label "+label);
        }
        gr.addTransition(gr.transitionMatrix.get(fromState),objectToLabel.get(label),toState);
      }
     
      if (initial_state != null)
      {// do not set the initial state if we are not asked to
        gr.setInit(gr.findVertex(VertexID.parseID(initial_state.atomValue())));
        if (gr.getInit() == null)
        {
          if (!checkStates)
          {
            String state = initial_state.atomValue();if (state.isEmpty()) throw new IllegalArgumentException("empty initial state");
            CmpVertex initState = AbstractLearnerGraph.generateNewCmpVertex(VertexID.parseID( state), gr.config );gr.transitionMatrix.put(initState,gr.createNewRow());
            gr.setInit(initState);
          }
          else
            throw new IllegalArgumentException("missing initial state");
        }
View Full Code Here

          assert scoreComputer.config.getQuestionGenerator() == QuestionGeneratorKind.CONVENTIONAL;
          assert scoreComputer.config.getQuestionPathUnionLimit() < 0;
         
          Collection<List<String>> questionsOrigA = ComputeQuestions.computeQS_orig(pair, scoreComputer,tempOrig);
          //CmpVertex Rnew = tempNew.getVertex(scoreComputer.wmethod.computeShortPathsToAllStates().get(pair.getR()));
          CmpVertex Rnew = tempNew.getStateLearnt();
          assert Rnew == tempNew.getVertex(scoreComputer.wmethod.computeShortPathsToAllStates().get(pair.getR()));
          Collection<List<String>> questionsOrigB = ComputeQuestions.computeQS_orig(new StatePair(Rnew,Rnew), scoreComputer,tempNew);
          PTASequenceSet newQuestions =new PTASequenceSet();newQuestions.addAll(questions);
          assert newQuestions.containsAll(questionsOrigA);
          assert newQuestions.containsAll(questionsOrigB);
        }
       
        if (questions.isEmpty())
          ++counterEmptyQuestions;

      }
      boolean restartLearning = false;// whether we need to rebuild a PTA and restart learning.
     
      //System.out.println(Thread.currentThread()+ " "+pair + " "+questions);
      Iterator<List<String>> questionIt = questions.iterator();
      while(questionIt.hasNext()){
        List<String> question = questionIt.next();
        boolean accepted = pair.getQ().isAccept();
        Pair<Integer,String> answer = topLearner.CheckWithEndUser(scoreComputer, question, null);
        this.questionCounter++;
        if (answer.firstElem == USER_CANCELLED)
        {
          System.out.println("CANCELLED");
          return null;
        }
       
        CmpVertex tempVertex = temp.getVertex(question);
       
        if(answer.firstElem == USER_ACCEPTED)
        {
          ++counterAccepted;
          //sPlus.add(question);
          topLearner.AugmentPTA(newPTA, RestartLearningEnum.restartHARD, question, true, null);
          //newPTA.paths.augmentPTA(question, true, null);
          ++plusSize;
          if (ans != null) System.out.println(howAnswerWasObtained+question.toString()+ " <yes>");
          if (counterRestarted == restartOfInterest) System.out.println(question.toString()+ " <yes>");
          if(!tempVertex.isAccept())
          {
            restartLearning = true;break;
          }
        }
        else
          if(answer.firstElem >= 0)
          {// The sequence has been rejected by a user
            assert answer.firstElem < question.size();
            ++counterRejected;
            LinkedList<String> subAnswer = new LinkedList<String>();subAnswer.addAll(question.subList(0, answer.firstElem+1));
            //sMinus.add(subAnswer);
            topLearner.AugmentPTA(newPTA, RestartLearningEnum.restartHARD, subAnswer, false, null);
            //newPTA.paths.augmentPTA(subAnswer, false, null);
            ++minusSize ;// important: since vertex IDs are
            // only unique for each instance of ComputeStateScores, only once
            // instance should ever receive calls to augmentPTA
            if (ans != null) System.out.println(howAnswerWasObtained+question.toString()+ " <no> at position "+answer.firstElem+", element "+question.get(answer.firstElem));
            if (counterRestarted == restartOfInterest) System.out.println(question.toString()+ " <no> at position "+answer.firstElem+", element "+question.get(answer.firstElem));           
            if( (answer.firstElem < question.size()-1) || tempVertex.isAccept())
            {
              assert accepted == true;
              restartLearning = true;break;
            }
          }
View Full Code Here

      RedStatesFound.clear();coregraph.pairsAndScores.clear();
      currentExplorationBoundary.addAll(reds);
      if (coregraph.additionalExplorationRoot != null) currentExplorationBoundary.addAll(coregraph.additionalExplorationRoot);
      while(!currentExplorationBoundary.isEmpty())
      {
        CmpVertex currentRed = currentExplorationBoundary.remove();
 
        Collection<Entry<Label,CmpVertex>> surrounding = decisionProcedure == null?null:decisionProcedure.getSurroundingTransitions(currentRed);
        if (surrounding == null) surrounding = coregraph.transitionMatrix.get(currentRed).entrySet();
        for(Entry<Label,CmpVertex> BlueEntry:surrounding)
          if (BlueEntry.getValue().getColour() == null ||
              BlueEntry.getValue().getColour() == JUConstants.BLUE)
          {// the next vertex is not marked red, hence it has to become blue
            CmpVertex currentBlueState = BlueEntry.getValue();
           
            int numberOfCompatiblePairs = 0;
            for(CmpVertex oldRed:reds)
            {
              PairScore pair = obtainPair(currentBlueState,oldRed,decisionProcedure);
              if (pair.getScore() >= coregraph.config.getGeneralisationThreshold())
              {
                coregraph.pairsAndScores.add(pair);
                ++numberOfCompatiblePairs;
                if (GlobalConfiguration.getConfiguration().isAssertEnabled() && coregraph.config.getDebugMode()) PathRoutines.checkPTAConsistency(coregraph, currentBlueState);
              }
            }
           
            if (numberOfCompatiblePairs == 0)
              RedStatesFound.add(currentBlueState);
             
            // This node is current a blue node and remains blue until I decide which of the currently potentially red nodes become red.
            currentBlueState.setColour(JUConstants.BLUE);
          }
      }
 
      // Now that we have a collection of all potentially red vertices, pick one to make red and then then check if others can remain blue.
      CmpVertex newRedNode = null;
      if (!RedStatesFound.isEmpty())
      {
        if (RedStatesFound.size() > 1 && decisionProcedure != null)
          newRedNode = decisionProcedure.selectRedNode(coregraph, reds, RedStatesFound);
        else
          newRedNode = RedStatesFound.iterator().next();
        // mark this blue node as red and rebuild a collection of blue and potentially red states.
        newRedNode.setColour(JUConstants.RED);
        reds.add(newRedNode);
      }
      else
        if (!coregraph.pairsAndScores.isEmpty() && decisionProcedure != null)
        {// the pairs chosen so far might all be the wrong ones, hence we could attempt to avoid the disaster if we can do something clever and whoever registered a decision procedure is given a chance to do it. 
          newRedNode = decisionProcedure.resolvePotentialDeadEnd(coregraph, reds, coregraph.pairsAndScores);
          if (newRedNode != null)
          {
            newRedNode.setColour(JUConstants.RED);
            reds.add(newRedNode);RedStatesFound.add(newRedNode);
          }
        }
    }
    while(!RedStatesFound.isEmpty());
View Full Code Here

TOP

Related Classes of statechum.DeterministicDirectedSparseGraph.CmpVertex

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.