Ejemplo n.º 1
0
 public override IResult SearchKNN(object q, int K, IResult final_result)
 {
     var state = new SearchState ();
     var beam = this.FirstBeam (q, final_result, state);
     var beamsize = beam.Count;
     //Console.WriteLine ("**** beamsize: {0}, repeatsearch: {1}", beamsize, this.RepeatSearch);
     //Console.WriteLine ("**** count: {0}, vertices-count: {1}", this.DB.Count, this.Vertices.Count);
     // expand successors and select the best BeamSize ones among them
     for (int i = 0; i < this.RepeatSearch; ++i) {
         var _beam = new Result (beamsize);
         if (this.Vertices.Count == this.DB.Count)
             Console.WriteLine ("=== Iteration {0}/{1}, res-count: {2}, res-cov: {3}", i, this.RepeatSearch, final_result.Count, final_result.CoveringRadius);
         foreach (var pair in beam) {
             foreach(var neighbor_docID in this.Vertices [pair.docid]) {
                 // Console.WriteLine ("=== B i: {0}, docID: {1}, parent: {2}, beamsize: {3}", i, neighbor_docID, pair, beam.Count);
                 if (state.evaluated.Add(neighbor_docID)) {
                     var d = this.DB.Dist (q, this.DB [neighbor_docID]);
                     final_result.Push (neighbor_docID, d);
                     _beam.Push (neighbor_docID, d);
                 }
             }
         }
         beam = _beam;
     }
     return final_result;
 }
Ejemplo n.º 2
0
 public override IResult SearchKNN(object q, int K, IResult res)
 {
     var state = new SearchState ();
     var sorted = this.GetStartingPoints(q);
     int counter = 0;
     foreach (var p in sorted) {
         int x0 = state.evaluated.Count;
         double y0 = res.CoveringRadius;
         this.GreedySearch (q, res, p.docid, state);
         int x1 = state.evaluated.Count;
         double y1 = res.CoveringRadius;
         // now doing the job
         var x = x1 - x0;
         if (x == 0) {
             continue;
         }
         var y = y1 - y0;
         if (y == 0) {
             ++counter;
         }
         if (counter > this.RepeatSearch) {
             break;
         }
         //++counter;
         //Console.WriteLine ("counter: {0}, y: {1}, x: {1}", counter, y, x);
     }
     return res;
 }
Ejemplo n.º 3
0
 public override IResult SearchKNN(object q, int K, IResult final_result)
 {
     var state = new SearchState ();
     var beam = this.FirstBeam (q, final_result, state);
     var beamsize = beam.Count;
     double prevcov = 0;
     int count_ties = 0;
     for (int i = 0; i < this.RepeatSearch; ++i) {
         prevcov = final_result.CoveringRadius;
         var _beam = new Result (beamsize);
         //if (this.Vertices.Count == this.DB.Count)
         //	Console.WriteLine ("=== Iteration {0}/{1}, res-count: {2}, res-cov: {3}", i, this.RepeatSearch, final_result.Count, final_result.CoveringRadius);
         foreach (var pair in beam) {
             foreach(var neighbor_docID in this.Vertices [pair.docid]) {
                 // Console.WriteLine ("=== B i: {0}, docID: {1}, parent: {2}, beamsize: {3}", i, neighbor_docID, pair, beam.Count);
                 if (state.evaluated.Add(neighbor_docID)) {
                     var d = this.DB.Dist (q, this.DB [neighbor_docID]);
                     final_result.Push (neighbor_docID, d);
                     _beam.Push (neighbor_docID, d);
                 }
             }
         }
         if (final_result.CoveringRadius == prevcov) {
             if (count_ties == 1) {
                 // we stop after two ties
                 break;
             }
             ++count_ties;
         } else {
             count_ties = 0;
         }
         beam = _beam;
     }
     return final_result;
 }
Ejemplo n.º 4
0
 public override IResult SearchKNN(object q, int K, IResult final_result)
 {
     var state = new SearchState ();
     var beam = this.FirstBeam (q, final_result, state);
     var beamsize = beam.Count;
     //Console.WriteLine ("**** beamsize: {0}, repeatsearch: {1}", beamsize, this.RepeatSearch);
     //Console.WriteLine ("**** count: {0}, vertices-count: {1}", this.DB.Count, this.Vertices.Count);
     // expand successors and select the best BeamSize ones among them
     for (int i = 0; i < this.RepeatSearch; ++i) {
         IResult _beam = new Result (beamsize);
         if (this.Vertices.Count == this.DB.Count)
             Console.WriteLine ("=== Iteration {0}/{1}, res-count: {2}, res-cov: {3}", i, this.RepeatSearch, final_result.Count, final_result.CoveringRadius);
         foreach (var pair in beam) {
             foreach(var neighbor_docID in this.Vertices [pair.docid]) {
                 // Console.WriteLine ("=== B i: {0}, docID: {1}, parent: {2}, beamsize: {3}", i, neighbor_docID, pair, beam.Count);
                 if (state.evaluated.Add (neighbor_docID)) {
                     var d = this.DB.Dist (q, this.DB [neighbor_docID]);
                     // THIS IS THE DIFFERENCE between the variants and the original (this)
                     // local beam search. The others become greedy because we use additional
                     // help (not necessary here)
                     final_result.Push (neighbor_docID, d);
                     _beam.Push (neighbor_docID, d);
                 }
             }
         }
         beam = _beam;
     }
     return final_result;
 }
Ejemplo n.º 5
0
 public Settings(SerializationInfo info, StreamingContext context)
 {
     _directories = (List<Directory>) info.GetValue("_directories", typeof(List<Directory>));
     _searchState = (SearchState) info.GetValue("_searchState", typeof (SearchState));
     _sortState = (SortState) info.GetValue("_sortState", typeof(SortState));
     _sortReversed = info.GetBoolean("_sortReversed");
 }
Ejemplo n.º 6
0
 public void SetState(Seed seed, SearchState state)
 {
     lock (_thisLock)
     {
         _seedsDictionary.AddOrUpdate(seed, state, (_, orignalState) => orignalState | state);
     }
 }
        /// <summary>
        /// Create a new search node for BreadFirstSearch.
        /// </summary>
        /// <param name="x">X coordinate of the search node.</param>
        /// <param name="y">Y coordinate of the search node.</param>
        /// <param name="previousNode">Search node preceeding this one.</param>
        public BreadthFirstSearchNode(int x, int y,
			BreadthFirstSearchNode previousNode = null)
        {
            this.x = x;
            this.y = y;
            this.searchStatus = SearchState.Unchecked;
            this.previousNode = previousNode;
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Creates a new search on the item list supplied, with the specified options.
 /// Results on the IEnumberable.
 /// </summary>
 /// <param name="allItems">The list of items to search</param>
 /// <param name="searchTerms">The string to search on</param>
 /// <param name="state">Search options</param>
 public Search(List<Item> allItems, string searchTerms, SearchState state, SortState sort = SortState.Filename, bool sortAscending = true)
 {
     _allItems = allItems;
     _search = searchTerms;
     _state = state;
     _results = new List<Item>();
     _sort = sort;
     _sortAscending = sortAscending;
     doSearch();
 }
Ejemplo n.º 9
0
 public Search(
     //IStore store,
     IHelper helper, IJhDbContext jhDbContext)
 {
     //_store = store;
     _jhDbContext      = jhDbContext;
     _helper           = helper;
     SearchState       = SearchState.Ping;
     Result            = new Dictionary <string, SearchResultEntity>();
     CurrentCachedUrls = new List <CachedUrl>();
 }
Ejemplo n.º 10
0
 internal Token get(SearchState searchState)
 {
     for (int i = 0; i < this.curSize; i++)
     {
         if (Object.instancehelper_equals(this.tokens[i].getSearchState(), searchState))
         {
             return(this.tokens[i]);
         }
     }
     return(null);
 }
Ejemplo n.º 11
0
    protected override void Begin()
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos);

        // l_nos <- faz fila(Estado inicial(problema))
        SearchState start = new SearchState(startNode, 0);

        openQueue = new Queue <SearchState> ();
        openQueue.Enqueue(start);
    }
Ejemplo n.º 12
0
 private int HandleLookForStartMatch(ref int i, byte b, byte[] buffer, ref int endTransformPosition, ref int startTransformPosition)
 {
     if (IsMatch(MatchingEnd.Start, b))
     {
         state = SearchState.MatchingStart;
         transformBuffer.Clear();
         startTransformPosition = i;
         return(HandleMatchingStartMatch(b, ref i, buffer, ref endTransformPosition, ref startTransformPosition));
     }
     return(matchPosition);
 }
Ejemplo n.º 13
0
        private void incrementStateTypeCount(SearchState searchState)
        {
            Integer integer = (Integer)this.stateCountByType.get(Object.instancehelper_getClass(searchState));

            if (integer == null)
            {
                integer = Integer.valueOf(0);
            }
            integer = Integer.valueOf(integer.intValue() + 1);
            this.stateCountByType.put(Object.instancehelper_getClass(searchState), integer);
        }
Ejemplo n.º 14
0
    //1 Começa a fazer a fila com o estado inicial
    //2 Entra no ciclo e caso a fila não esteja vazia retira o elemento no fim da fila (FIFO)
    //Analisa e verifica se é solução
    //Se for solução devolve o elemento
    //Se nao for solução determina os sucessores e adiciona-os ao fim da fila
    //A diferença entre largura e profundidade é que no 2.3.2
    //adicionamos os nós sucessores no fim da fila e por ser FIFO o primeiro a entrar vai ser o primeiro a sair
    //e por isso percorre cada nível de cada vez
    //A função recomeça com a posição do "zombie" para cada elemento a encontrar


    protected override void Begin()                                  //1 Inicia a função
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);  //Verifica o nó inicial e a respectiva posição
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos); //Verifica o nó destino e a respectiva posição

        //Cria a fila e insere o node inicial
        SearchState start = new SearchState(startNode, 0);  //nó inicial

        openQueue = new Queue <SearchState> ();
        openQueue.Enqueue(start);
    }
Ejemplo n.º 15
0
    protected override void Step()
    {
        if (p_queue.Count > 0)
        {
            // retira da lista de nós o primeiro nó e insere-o na lista de visitados
            SearchState currentState = p_queue.PopFirst();
            VisitNode(currentState);

            if (currentState.node == targetNode)               //se o no contem o objetivo
            //devolve a solucao correspondente
            {
                solution  = currentState;
                finished  = true;
                running   = false;
                foundPath = true;
            }
            else
            {
                foreach (Node suc in GetNodeSucessors(currentState.node))
                {
                    if (!nodesVisited.Contains(suc))
                    {
                        // limita-se a manter a fronteira da arvore de procura ordenada pelos valores de h(n),
                        // sendo sempre escolhido o nó de valor mais baixo, isto é, aquele que está mais proximo da solucao
                        int Hn;

                        SearchState new_node = new SearchState(suc, suc.gCost + currentState.g, currentState);

                        if (NrHeuristica == 0)
                        {
                            Hn = GetHeuristic_Euclidean(new_node.node);
                        }
                        else
                        {
                            Hn = GetHeuristic_Manhattan(new_node.node);
                        }

                        p_queue.Add(new_node, Hn);                         // ordenada
                    }
                }
                // for energy
                if ((ulong)p_queue.Count > maxListSize)
                {
                    maxListSize = (ulong)p_queue.Count;
                }
            }
        }
        else         // se nao ha candidatos para expandir
        {
            finished  = true;
            running   = false;
            foundPath = true;
        }
    }
Ejemplo n.º 16
0
    protected override void Begin()
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos);
        //estas duas linhas funcionam para quase ou todos os algoritmos

        SearchState start = new SearchState(startNode, 0);

        openStack = new Stack <SearchState> ();
        openStack.Push(start);
    }
        protected internal virtual void localStart()
        {
            this.currentFrameNumber    = 0;
            this.curTokensScored.value = (double)0f;
            ActiveList  activeList   = this.activeListFactory.newInstance();
            SearchState initialState = this.linguist.getSearchGraph().getInitialState();

            activeList.add(new Token(initialState, -1L));
            this.activeList = activeList;
            this.growBranches();
        }
Ejemplo n.º 18
0
    //1 Começa a fazer uma lista com o estado inicial
    //2 Entra no ciclo e caso a lista não esteja vazia retira o unico elemento da lista
    //Analisa e verifica se é solução
    //Se for solução devolve o elemento
    //O algoritmo aleatório tem apenas um nó guardado em cada momento por isso se o nó não for solução
    //o algoritmo apaga a lista e adiciona um, apenas um, nó aleatório da vizinhança à lista
    //A função recomeça com a posição do "zombie" para cada elemento a encontrar

    protected override void Begin()                                  //1 Inicia a função
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);  //Verifica o nó inicial e a respectiva posição
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos); //Verifica o nó destino e a respectiva posição

        //Cria a lista e insere o node inicial
        SearchState start = new SearchState(startNode, 0); //nó inicial

        openList = new List <SearchState>();
        openList.Add(start); //adiciona o nó à lista
    }
Ejemplo n.º 19
0
    //1 Começa a fazer a fila de prioridade com o estado inicial
    //2 Entra no ciclo e caso a fila de prioridade não esteja vazia retira o elemento à cabeça da fila
    //Analisa e verifica se é solução
    //Se for solução devolve o elemento
    //Se não for solução determina os sucessores e adiciona-os à fila de prioridade de acordo com o seu custo heuristico
    //ordenando por ordem crescente todos os h(n) associados a cada nó
    //A diferença entre pesquisa sôfrega e custo uniforme é que na pesquisa sofrega
    //a fila de prioridade vai estar organizada segundo a heuristica associada ao nó a expandir
    //A função recomeça com a posição do "zombie" para cada elemento a encontrar


    protected override void Begin()                                  //1 Inicia a função
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);  //Verifica o nó inicial e a respectiva posição
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos); //Verifica o nó destino e a respectiva posição

        //Cria a fila de prioridade e insere o node inicial
        SearchState start = new SearchState(startNode, 0);  //nó inicial

        openQueue = new PriorityQueue();
        openQueue.Add(start, 0); //adiciona o nó à fila
    }
Ejemplo n.º 20
0
    public void Init()
    {
        m_CellsSearched       = new List <BaseCell>();
        m_CellsToSearch       = new List <BaseCell>();
        m_Path                = new List <int>();
        m_BeamWidth           = 100;
        m_CellsToSearchBackup = new List <BaseCell>();
        m_SearchState         = SearchState.None;

        m_Requests = new Queue <PathFindReq>();
    }
Ejemplo n.º 21
0
    protected override void Begin()
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos);

        SearchState start = new SearchState(startNode, 0);

        openStack = new Stack <SearchState> ();
        openStack.Push(start);
        depthLimit = 0;
    }
Ejemplo n.º 22
0
    public void Awake()
    {
        searchState = new SearchState(this);
        returnState = new ReturnState(this);
        gatherState = new GatherState(this);

        navMeshAgent = GetComponent<NavMeshAgent>();

        hasFood = false;
        foodStatusChanged = false;
    }
Ejemplo n.º 23
0
        protected List <FindMetadataResult> GetAllMetadataSearchResults(
            string searchToken,
            int?minResults,
            int?maxResults,
            string waitTime,
            out SearchState state)
        {
            List <FindMetadataResult> metadataList = new List <FindMetadataResult>();

            FindMetadataResultList response = null;

            DateTime started      = DateTime.Now;
            DateTime dueTo        = started.AddSeconds(_searchTimeout);
            bool     completed    = true;
            DateTime lastResponse = DateTime.Now;

            LogTestEvent(string.Format("All results should be received by {0}{1}",
                                       dueTo.StdTimeToString(), Environment.NewLine));

            do
            {
                RunStep(() =>
                {
                    response = Client.GetMetadataSearchResults(new GetMetadataSearchResults()
                    {
                        SearchToken         = searchToken,
                        WaitTime            = waitTime,
                        MinResults          = minResults ?? 0,
                        MaxResults          = maxResults ?? 0,
                        MinResultsSpecified = minResults == null ? false : true,
                        MaxResultsSpecified = maxResults == null ? false : true
                    }).ResultList;
                }, "Get Metadata Search results");
                lastResponse = DateTime.Now;

                if (response.Result != null)
                {
                    metadataList.AddRange(response.Result);
                }
                if (lastResponse > dueTo)
                {
                    completed = false;
                    break;
                }
            } while (response.SearchState != SearchState.Completed);

            state = response.SearchState;

            Assert(completed,
                   string.Format("Completed state has not been achieved (last response received at {0}, State: {1})", lastResponse.StdTimeToString(), response.SearchState),
                   "Check that search has been completed in due time");

            return(metadataList);
        }
Ejemplo n.º 24
0
    public void CreateRoom()
    {
        Debug.Log("Create room No." + roomCnt);
        RoomOptions room = new RoomOptions();

        room.MaxPlayers = 2;
        ExitGames.Client.Photon.Hashtable customProp = new ExitGames.Client.Photon.Hashtable();
        customProp.Add("Judge", "Non");
        room.CustomRoomProperties = customProp;
        PhotonNetwork.CreateRoom(searchRoomName + roomCnt, room, TypedLobby.Default);
        searchState = SearchState.CreateRoom;
    }
Ejemplo n.º 25
0
 public virtual void timeLinguist(int numRuns, int numFrames, int maxBeam)
 {
     java.util.Random  random = new java.util.Random((long)((ulong)1000));
     sphinx.util.Timer timer  = TimerPool.getTimer(this, "frameTimer");
     sphinx.util.Timer timer2 = TimerPool.getTimer(this, "totalTimer");
     [email protected](new StringBuilder().append("TestLinguist: runs ").append(numRuns).append(" frames ").append(numFrames).append(" beam ").append(maxBeam).toString());
     timer2.start();
     for (int i = 0; i < numRuns; i++)
     {
         int    num = 0;
         object obj = new ArrayList();
         ((ArrayList)obj).add(this.linguist.getSearchGraph().getInitialState());
         this.linguist.startRecognition();
         for (int j = 0; j < numFrames; j++)
         {
             object obj2 = obj;
             obj = new ArrayList(maxBeam * 10);
             timer.start();
             object obj3 = obj2;
             List   list;
             if (obj3 != null)
             {
                 if ((list = (obj3 as List)) == null)
                 {
                     throw new IncompatibleClassChangeError();
                 }
             }
             else
             {
                 list = null;
             }
             Iterator iterator = list.iterator();
             while (iterator.hasNext())
             {
                 SearchState searchState = (SearchState)iterator.next();
                 this.expandState(num, (ArrayList)obj, searchState);
             }
             timer.stop();
             Collections.shuffle((ArrayList)obj, random);
             if (((ArrayList)obj).size() > maxBeam)
             {
                 obj = ((ArrayList)obj).subList(0, maxBeam);
             }
         }
         this.linguist.stopRecognition();
     }
     timer2.stop();
     [email protected](new StringBuilder().append(" MaxSuccessors : ").append(this.maxSuccessors).toString());
     [email protected](new StringBuilder().append(" TotalStates   : ").append(this.totalStates).toString());
     [email protected](new StringBuilder().append(" TotalEmitting : ").append(this.totalEmittingStates).toString());
     [email protected](new StringBuilder().append("   NonEmitting : ").append(this.totalNonEmittingStates).toString());
     [email protected](new StringBuilder().append("  Final States : ").append(this.totalFinalStates).toString());
 }
            private void Push(Parser <TInput> parser, int inputStart, bool prevWasMissing)
            {
                this.stackPosition++;

                if (this.stackPosition == stack.Count)
                {
                    stack.Add(new SearchState());
                }

                this.state = this.stack[this.stackPosition];
                this.state.Init(parser, inputStart, prevWasMissing);
            }
Ejemplo n.º 27
0
        private void stop_btn_Click(object sender, EventArgs e)
        {
            _searchState = SearchState.Stopped;
            ChangeButtons(_searchState);

            if (backgroundWorker.WorkerSupportsCancellation == true)
            {
                backgroundWorker.CancelAsync();
            }

            toolStripStatusLabel.Text = "";
        }
Ejemplo n.º 28
0
        public void EmptyStateDoesNothingTest()
        {
            var s  = new SearchState();
            var fc = new ForwardChecking();

            var result = fc.Solve(s.Copy());

            foreach (var(x, y) in Sets.All)
            {
                Assert.AreEqual(s.BitDomain(x, y), result.BitDomain(x, y));
            }
        }
    public int maxdepth; //guarda a depth máxima no qual o algoritmo já analizou;

    //1 Começa a fazer a pilha com o estado inicial
    //2 Entra no ciclo e caso a pilha não esteja vazia retira o elemento à cabeça da pilha (LIFO)
    //Analisa e verifica se é solução
    //Se for solução devolve o elemento
    //Se nao for solução determina os sucessores e adiciona-os à cabeça da pilha
    //A diferença entre profundidade e profundidade limitada é que no 2.3.2
    //só expandimos se o node for de um nível inferior ao maximo
    //A função recomeça com a posição do "zombie" para cada elemento a encontrar

    protected override void Begin()                                   //1 Inicia a função
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);   //Verifica o nó inicial e a respectiva posição
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos);  //Verifica o nó destino e a respectiva posição

        //Cria a pilha e insere o node inicial
        SearchState start = new SearchState(startNode, 0);          //nó inicial

        openStack = new Stack <SearchState> ();
        openStack.Push(start); //adiciona o nó à pilha
        maxdepth = 0;          //inicia a maxdepth a 0 pois ainda não verificou nada
    }
Ejemplo n.º 30
0
        /**
         * Gets the initial grammar node from the linguist and creates a
         * GrammarNodeToken
         */
        protected void localStart()
        {
            currentFrameNumber    = 0;
            curTokensScored.value = 0;
            ActiveList  newActiveList = activeListFactory.newInstance();
            SearchState state         = linguist.getSearchGraph().getInitialState();

            newActiveList.add(new Token(state, currentFrameNumber));
            activeList = newActiveList;

            growBranches();
        }
Ejemplo n.º 31
0
    protected override void Begin()
    {
        startNode  = GridMap.instance.NodeFromWorldPoint(startPos);
        targetNode = GridMap.instance.NodeFromWorldPoint(targetPos);
        Random.InitState(System.DateTime.Now.Millisecond);
        //estas duas linhas funcionam para quase ou todos os algoritmos

        SearchState start = new SearchState(startNode, 0);

        openQueue = new List <SearchState> ();
        openQueue.Add(start);
    }
 protected void ExpandNeighborhood(object q, int startID, List<int> neighborhood, SearchState state, int level)
 {
     var nodelist = this.Vertices [startID];
     foreach (var nodeID in nodelist) {
         if (state.evaluated.Add(nodeID)) {
             neighborhood.Add (nodeID);
             if (level > 0) {
                 this.ExpandNeighborhood (q, nodeID, neighborhood, state, level - 1);
             }
         }
     }
 }
Ejemplo n.º 33
0
 protected Result GetStartingPoints(object q, SearchState state)
 {
     int ss = Math.Min (this.SampleSize, this.Vertices.Count);
     var n = this.Vertices.Count;
     Result sorted = new Result (ss);
     for (int i = 0; i < ss; ++i) {
         var objID = this.rand.Next (0, n);
         var d = this.DB.Dist (q, this.DB [objID]);
         sorted.Push (objID, d);
     }
     return sorted;
 }
Ejemplo n.º 34
0
        private void SetStartAndGoalNode(Node startSearchNode, Node goalSearchNode)
        {
            _startNode = startSearchNode;
            _goalNode  = goalSearchNode;

            _searchState = SearchState.Searching;

            _startNode.Cost            = 0;
            _startNode.Distance        = _startNode.CalculateDistance(_goalNode);
            _startNode.DistanceCostSum = _startNode.Cost + _startNode.Distance;
            _openList.Add(_startNode);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="graph">The graph where the search will be performed</param>
        protected GraphSearchAlgorithm(Graph <T, K> graph)
        {
            String message = String.Empty;

            if (ValidateGraph(graph, ref message) == false)
            {
                throw new JValidationException("graph", this.GetType().ToString(), message);
            }

            this.graph = graph;
            this.found = SearchState.NotCompleted;
        }
Ejemplo n.º 36
0
 public Enumerator(FindAllCoreEnumerable ownerEnumerable)
 {
     state = new SearchState(ownerEnumerable.searchRange.Buffer, ownerEnumerable.cancellationToken);
     if ((ownerEnumerable.options & HexFindOptions.SearchReverse) != 0)
     {
         realEnumerator = ownerEnumerable.owner.FindAllCoreReverse(state, ownerEnumerable.searchRange, ownerEnumerable.startingPosition, ownerEnumerable.options, ownerEnumerable.cancellationToken).GetEnumerator();
     }
     else
     {
         realEnumerator = ownerEnumerable.owner.FindAllCore(state, ownerEnumerable.searchRange, ownerEnumerable.startingPosition, ownerEnumerable.options, ownerEnumerable.cancellationToken).GetEnumerator();
     }
 }
    //está sempre a repetir - sempre a ser chamado
    protected override void Step()                                                      //2 Repete
    //se a pilha não está vazia
    {
        if (openStack.Count > 0)
        {
            //tira o node na cabeça
            SearchState currentState = openStack.Pop();         //2.2 Retira o elemento à cabeça da pilha (LIFO)
            VisitNode(currentState);
            //verifica se o node é solução
            if (currentState.node == targetNode)                        //2.3
            //se é solução termina
            {
                solution  = currentState;                                                       //2.3.1
                finished  = true;
                running   = false;
                foundPath = true;
            }
            else                                                        //2.3.2 Insere elementos à cabeca da pilha
            //efeito de procura em profundidade
            //se não é solução vai buscar os sucessores do nó
            {
                nivel = currentState.depth;
                if (nivel < maxdepth)                                         //se o depth do nó for menor que o máximo expande
                {
                    foreach (Node suc in GetNodeSucessors(currentState.node)) //Devolve os nós sucessores pela ordem N-E-S-W
                    //cria um novo estado e um novo nó
                    //volta acima
                    {
                        SearchState new_node = new SearchState(suc, suc.gCost + currentState.g, currentState); //define o nó que vai adicionar
                        openStack.Push(new_node);                                                              //adiciona o nó
                    }
                }
                // for energy
                if ((ulong)openStack.Count > maxListSize)
                {
                    maxListSize = (ulong)openStack.Count;
                }
            }
        }
        else         //Se a pilha estiver vazia termina

        {            //2.1 Testa se a pilha não tem elementos
            finished = false;
            running  = true;

            //foundPath = false;

            maxdepth++;                                        //aumenta o máximo
            SearchState start = new SearchState(startNode, 0); //Recomeça processo com maxdepth+1
            openStack.Push(start);
        }
    }
Ejemplo n.º 38
0
        static void SearchAccountMenu(List <Account> AccountList, List <Customer> CustomerList)
        {
            Console.WriteLine(formattingLine);
            Console.WriteLine("\tSearch An Account\t\t\t\t\t\t\t\t\t\t\t\tDesigned By Corey Henderson");
            Console.WriteLine(formattingLine);
            Console.WriteLine("Please enter one of the following account details:");

            Console.Write("\nEnter Account ID: ");
            string accIDInput = Console.ReadLine();

            Console.Write("Enter Owner ID: ");
            string ownerIDInput = Console.ReadLine();

            Console.WriteLine("\n\nPress \"s\" or \"S\" to search");
            Console.WriteLine("Press any other key to cancel");

            try
            {
                var selection = Console.ReadKey();
                Console.Clear();
                switch (selection.Key)
                {
                case ConsoleKey.S:
                    // Checks whether the user inputs have a value, if so, it displays the search based off the input
                    if (string.IsNullOrEmpty(accIDInput) == false)
                    {
                        searchState = SearchState.accountIDInput;
                        DisplayAccountSearch(AccountList, CustomerList, uint.Parse(accIDInput));
                        break;
                    }
                    if (string.IsNullOrEmpty(ownerIDInput) == false)
                    {
                        searchState = SearchState.ownerIDInput;
                        DisplayAccountSearch(AccountList, CustomerList, uint.Parse(ownerIDInput));
                        break;
                    }

                    throw new Exception("No information was entered!");

                default:
                    menuState = State.MainMenu;
                    break;
                }
            }
            catch (Exception e)
            {
                Console.Clear();
                Console.WriteLine(e.Message);
                Console.WriteLine("\nPlease try again.");
                SearchAccountMenu(AccountList, CustomerList);
            }
        }
Ejemplo n.º 39
0
        void ListenCompleted(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                if (e.LastOperation == SocketAsyncOperation.SendTo)
                {
                    try
                    {
                        //sent multicast, now get ready for unicast
                        e.RemoteEndPoint = listenEndpoint;
                        searchSocket.ReceiveBufferSize = 8000;
                        byte[] receiveBuffer = new byte[8000];
                        e.SetBuffer(receiveBuffer, 0, 8000);
                        searchSocket.ReceiveFromAsync(e);
                        if (SearchStarted != null)
                        {
                            SearchStarted(this, new EventArgs());
                        }
                    }
                    catch { }
                    return;
                }
                else if (e.LastOperation == SocketAsyncOperation.ReceiveFrom)
                {
                    try
                    {
                        //got a response
                        string result           = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
                        var    resultDictionary = ParseResults(result);
                        if (DeviceFound != null)
                        {
                            DeviceFound(this, new DeviceFoundEventArgs(e.RemoteEndPoint, resultDictionary));
                        }

                        searchSocket.ReceiveFromAsync(e);
                    }
                    catch { }
                    return;
                }
            }
            else
            {
                if (e.SocketError != SocketError.OperationAborted)
                {
                    StopSearch(SearchStoppedReason.Error);
                    state = SearchState.NotSearching;
                }
            }

            this.StopSearch(SearchStoppedReason.Error);
            return;
        }
Ejemplo n.º 40
0
        //Meが動くとする。「Meのスコア - Enemyのスコア」の最大値を返す。
        private int NegaMax(int deepness, SearchState state, int alpha, int beta, int count, PointEvaluator.Base evaluator, int greedyDepth)
        {
            if (deepness == 0)
            {
                //深さgreedyDepth分だけ貪欲をしてから、評価関数を呼び出す
                for (int i = 0; i < greedyDepth; i++)
                {
                    Ways moves = state.MakeMoves(WayEnumerator);
                    SortMoves(ScoreBoard, state, moves, dp.Length - 1);
                    state.Move(moves[0].Agent1Way, moves[0].Agent2Way);
                }
                int eval = evaluator.Calculate(ScoreBoard, state.MeBoard, 0) - evaluator.Calculate(ScoreBoard, state.EnemyBoard, 0);
                if (greedyDepth % 2 == 1)
                {
                    return(-eval);
                }
                return(eval);
            }

            Ways ways = state.MakeMoves(WayEnumerator);

            SortMoves(ScoreBoard, state, ways, count);

            for (int i = 0; i < ways.Count; i++)
            {
                if (CancellationToken.IsCancellationRequested == true)
                {
                    return(alpha);
                }                                                                           //何を返しても良いのでとにかく返す
                if (count == 0 && ngMove != null && new Decided(ways[i].Agent1Way, ways[i].Agent2Way).Equals(ngMove) == true)
                {
                    continue;
                }                                                                                                                                               //競合手は指さない

                SearchState backup = state;
                state.Move(ways[i].Agent1Way, ways[i].Agent2Way);
                int res = -NegaMax(deepness - 1, state, -beta, -alpha, count + 1, evaluator, greedyDepth);
                if (alpha < res)
                {
                    alpha = res;
                    dp[count].UpdateScore(alpha, ways[i].Agent1Way, ways[i].Agent2Way);
                    if (alpha >= beta)
                    {
                        return(beta);               //βcut
                    }
                }
                state = backup;
            }
            ways.Erase();
            WaysPool.Return(ways);
            return(alpha);
        }
Ejemplo n.º 41
0
        //遷移順を決める.  「この関数においては」MeBoard…手番プレイヤのボード, Me…手番プレイヤ、とします。
        //引数: stateは手番プレイヤが手を打つ前の探索状態、(way1[i], way2[i])はi番目の合法手(移動量)です。
        //以下のルールで優先順を決めます.
        //ルール1. Killer手(優先したい手)があれば、それを優先する
        //ルール2. 次のmoveで得られる「タイルポイント」の合計値が大きい移動(の組み合わせ)を優先する。
        //ルール2では, タイル除去によっても「タイルポイント」が得られるとして計算する。
        private void SortMoves(sbyte[,] ScoreBoard, SearchState state, Ways way, int deep, Decision ngMove)
        {
            Unsafe8Array <Point> Killer;

            DP[] dp = ngMove is null ? dp1 : dp2;
            if (dp[deep].Score == int.MinValue)
            {
                Killer = Unsafe8Array <Point> .Create(new Point(114, 191), new Point(114, 191), new Point(114, 191), new Point(114, 191), new Point(114, 191), new Point(114, 191), new Point(114, 191), new Point(114, 191));
            }
            else
            {
                Killer = new Unsafe8Array <Point>();
                for (int i = 0; i < AgentsCount; ++i)
                {
                    Killer[i] = state.Me[i] + dp[deep].AgentsWay[i];
                }
            }

            for (int i = 0; i < way.Count; i++)
            {
                int score = 0;
                Unsafe8Array <Point> nexts = new Unsafe8Array <Point>();
                for (int n = 0; n < AgentsCount; ++i)
                {
                    nexts[n] = state.Me[n] + way[i].AgentWays[n];
                }

                if (Killer.Agent1 == next1 && Killer.Agent2 == next2)
                {
                    score = 100;
                }

                if (state.EnemyBoard[next1])
                {
                    score += ScoreBoard[next1.X, next1.Y];
                }                                                                           //タイル除去によって有利になる
                else if (!state.MeBoard[next1])
                {
                    score += ScoreBoard[next1.X, next1.Y];
                }                                                                           //移動でMeの陣地が増えて有利になる
                if (state.EnemyBoard[next2])
                {
                    score += ScoreBoard[next2.X, next2.Y];
                }
                else if (!state.MeBoard[next2])
                {
                    score += ScoreBoard[next2.X, next2.Y];
                }
                way[i].Point = score;
            }
            way.Sort();
        }
Ejemplo n.º 42
0
 public override IResult SearchKNN(object q, int K, IResult res)
 {
     //Console.WriteLine ("******* STARTING SEARCH repeat={0} *******", this.MAX_EXPANSION_LEVEL);
     var near = this.GetNearPoint(q);
     var state = new SearchState ();
     //int I = 0;
     this.GreedySearch (q, res, near.First.ObjID, state);
     // even a small number can expand a very large set of items because
     // it depends on the branching factor
     // the first level is already expanded but they can be trunked by
     // the Result object, then we must expand it too and use state to
     // avoid the duplication of work
     this.ExpandNode (q, res, near.First.ObjID, state, MAX_EXPANSION_LEVEL);
     return res;
 }
Ejemplo n.º 43
0
 protected void ExpandNode(object q, IResult res, int startID, SearchState state, int level)
 {
     var nodeS = this.Vertices [startID];
     foreach (var nodeID in nodeS) {
         if (state.visited.Add(nodeID)) {
             if (level > 0) {
                 this.ExpandNode (q, res, nodeID, state, level - 1);
             }
         }
         if (state.evaluated.Add (nodeID)) {
             var d = this.DB.Dist (q, this.DB [nodeID]);
             res.Push(nodeID, d);
         }
     }
 }
Ejemplo n.º 44
0
 protected override Result FirstBeam(object q, IResult final_result, SearchState state)
 {
     int samplesize = Math.Min (1024, this.Vertices.Count);
     //WARNING fixing the parameter beamsize for construction step for testing purposes
     int beamsize = Math.Min (this.BeamSize, this.Vertices.Count);
     var beam = new Result (beamsize);
     // initializing the first beam
     for (int i = 0; i < samplesize; ++i) {
         var docID = this.rand.Next(this.Vertices.Count);
         if (state.evaluated.Add (docID)) {
             var d = this.DB.Dist (q, this.DB [docID]);
             beam.Push (docID, d);
             final_result.Push(docID, d);
         }
     }
     return beam;
 }
Ejemplo n.º 45
0
 public override IResult SearchKNN(object q, int K, IResult res)
 {
     var state = new SearchState ();
     var sorted = this.GetStartingPoints(q, state);
     int count_startingpoints = 0;
     int count_skipped = 0;
     foreach (var p in sorted) {
         ++count_startingpoints;
         if (state.visited.Contains (p.docid)) {
             ++count_skipped;
         } else {
             this.GreedySearch (q, res, p.docid, state);
         }
         if (count_startingpoints - count_skipped > this.RepeatSearch) {
             break;
         }
     }
     //			Console.WriteLine ("#### count_startingpoints: {0}, count_skipped: {1}, repeat_search: {2}",
     //			                   count_startingpoints, count_skipped, this.RepeatSearch);
     return res;
 }
 public override IResult SearchKNN(object q, int K, IResult final_result)
 {
     var state = new SearchState ();
     var beam = this.FirstBeam (q, final_result, state);
     var beamsize = beam.Count;
     double prevcov = 0;
     int count_ties = 0;
     var neighborhood = new List<int> (32);
     for (int i = 0; i < this.RepeatSearch; ++i) {
         prevcov = final_result.CoveringRadius;
         var _beam = new Result (beamsize);
         foreach (var pair in beam) {
             neighborhood.Clear ();
             // neighborhood.Add (pair.docid);
             foreach (var neighbor_docID in this.Vertices [pair.docid]) {
                 this.ExpandNeighborhood (q, neighbor_docID, neighborhood, state, 8);
             }
             foreach (var neighbor_docID in neighborhood) {
                 var d = this.DB.Dist (q, this.DB [neighbor_docID]);
                 final_result.Push (neighbor_docID, d);
                 _beam.Push (neighbor_docID, d);
             }
         }
         if (final_result.CoveringRadius == prevcov) {
             if (count_ties == 1) {
                 // we stop after two ties
                 break;
             }
             ++count_ties;
         } else {
             count_ties = 0;
         }
         beam = _beam;
     }
     return final_result;
 }
Ejemplo n.º 47
0
 private int HandleMatchingStartCloseMatch(int i, byte b)
 {
     if (StartCloseChar.Contains(b) || (currentStartStringsToSkip.Count == 4 && !currentStartStringsToSkip[3]))
     {
         transformBuffer.Add(b);
         state = SearchState.LookForStop;
         return 0;
     }
     if (i - originalOffset < transformBuffer.Count)
         BaseStream.Write(transformBuffer.ToArray(), 0, (transformBuffer.Count - (i - originalOffset)));
     transformBuffer.Clear();
     state = SearchState.LookForStart;
     return 0;
 }
Ejemplo n.º 48
0
 private int HandleLookForStopMatch(byte b)
 {
     transformBuffer.Add(b);
     if(IsMatch(MatchingEnd.End, b))
     {
         state = SearchState.MatchingStop;
         matchPosition++;
     }
     return matchPosition;
 }
Ejemplo n.º 49
0
 private int HandleLookForStartMatch(ref int i, byte b, byte[] buffer, ref int endTransformPosition, ref int startTransformPosition)
 {
     if(IsMatch(MatchingEnd.Start, b))
     {
         state = SearchState.MatchingStart;
         transformBuffer.Clear();
         startTransformPosition = i;
         return HandleMatchingStartMatch(b, ref i, buffer, ref endTransformPosition, ref startTransformPosition);
     }
     return matchPosition;
 }
Ejemplo n.º 50
0
        private int HandleLookForAdjacentScriptMatch(byte[] buffer, int i, byte b, ref int endTransformPosition, ref int startTransformPosition)
        {
            if (IsMatch(MatchingEnd.Start, b))
            {
                state = SearchState.MatchingStart;
                return HandleMatchingStartMatch(b, ref i, buffer, ref endTransformPosition, ref startTransformPosition);
            }

            if (!WhiteSpaceChar.Contains(b))
            {
                SetAdjacent(false);
                state = SearchState.LookForStart;
                var numToTrim = i - endTransformPosition;
                if(numToTrim > 0)
                    transformBuffer.RemoveRange(transformBuffer.Count - numToTrim, numToTrim);
                DoTransform(buffer, ref endTransformPosition, ref startTransformPosition);
                actualLength = actualLength - (i - actualOffset); actualOffset = i;
                return 0;
            }

            transformBuffer.Add(b);
            return matchPosition;
        }
Ejemplo n.º 51
0
	// Set Start and goal states
	public void SetStartAndGoalStates(MapSearchNode Start, MapSearchNode Goal)
	{
		m_Start = AllocateNode();
		m_Goal = AllocateNode();

		System.Diagnostics.Debug.Assert((m_Start != null && m_Goal != null));

		m_Start.m_UserState = Start;
		m_Goal.m_UserState = Goal;

		m_State = SearchState.Searching;

		// Initialise the AStar specific parts of the Start Node
		// The user only needs fill out the state information
		m_Start.g = 0; 
		m_Start.h = m_Start.m_UserState.GoalDistanceEstimate( m_Goal.m_UserState );
		m_Start.f = m_Start.g + m_Start.h;
		m_Start.parent = null;

		// Push the start node on the Open list
		m_OpenList.Add(m_Start);

		// Initialise counter for search steps
		m_Steps = 0;

#if PATHFIND_DEBUG
		System.Console.WriteLine("Starting pathfind. Start: " + m_Start.m_UserState.position + ", Goal: " + m_Goal.m_UserState.position);
#endif
	}
Ejemplo n.º 52
0
    //Initialize/reset
    public void Reset()
    {
        if (workerThread != null) { workerThread = null; }

        fileSizeList = null;
        fileSizeList = new Dictionary<long, List<SmartFile>>();

        duplicateFiles = null;
        duplicateFiles = new Dictionary<ulong, List<SmartFile>>();

        pathsToSearch = null;
        pathsToSearch = new List<string>();

        State = SearchState.Idle;
    }
Ejemplo n.º 53
0
        /// <summary>
        /// Raises the additional text box completed event and doesn't strip laterality results.
        /// </summary>
        /// <param name="results">The results.</param>
        /// <param name="searchState">User state of search.</param>
        private static void RaiseAdditionalTextBoxCompleted(ObservableCollection<AdditionalTextBoxResult> results, SearchState searchState)
        {
            ObservableCollection<AdditionalTextBoxResult> newResults = new ObservableCollection<AdditionalTextBoxResult>();

            foreach (AdditionalTextBoxResult additionalTextBoxResult in results)
            {
                if (additionalTextBoxResult.IsSide && searchState.LateralityFindingSites.Count > 0)
                {
                    additionalTextBoxResult.FindingSites = searchState.LateralityFindingSites;
                    additionalTextBoxResult.AlternateItems = SnomedConcepts.FindPostCoordinationConcept(additionalTextBoxResult.SelectedItem.Parents[0].SnomedConceptId).Children;
                    newResults.Add(additionalTextBoxResult);
                }
                else if (!additionalTextBoxResult.IsSide)
                {
                    newResults.Add(additionalTextBoxResult);
                    additionalTextBoxResult.AlternateItems = SnomedConcepts.FindPostCoordinationConcept(additionalTextBoxResult.SelectedItem.Parents[0].SnomedConceptId).Children;
                }
            }

            if (TerminologyManager.AdditionalTextBoxParseCompleted != null)
            {
                TerminologyManager.AdditionalTextBoxParseCompleted(null, new AdditionalTextBoxParseCompletedEventArgs(searchState.SearchTextOriginal, newResults, searchState.ConceptDetail.SnomedConceptId));
            }
        }       
Ejemplo n.º 54
0
        private int HandleMatchingStartMatch(byte b, ref int i, byte[] buffer, ref int endTransformPosition, ref int startTransformPosition)
        {
            if(IsMatch(MatchingEnd.Start, b))
            {
                transformBuffer.Add(b);
                matchPosition++;
                for (var idx = 0; idx < currentStartStringsToSkip.Count; idx++)
                {
                    if (!currentStartStringsToSkip[idx] && matchPosition == StartStringUpper[idx].Length)
                    {
                        matchPosition = 0;
                        state = SearchState.MatchingStartClose;
                    }
                    else if (matchPosition == 0)
                        currentStartStringsToSkip[idx] = true;
                }
                return matchPosition;
            }

            if (isAdjacent)
            {
                SetAdjacent(false);
                var numToTrim = i - endTransformPosition;
                if (numToTrim > 0)
                    transformBuffer.RemoveRange(transformBuffer.Count - numToTrim, numToTrim);
                DoTransform(buffer, ref endTransformPosition, ref startTransformPosition);
                i = i - numToTrim - 1;
                actualLength = actualLength - (i - actualOffset) - 1;
                actualOffset = i + 1;
            }
            else
            {
                if(i-originalOffset < transformBuffer.Count)
                    BaseStream.Write(transformBuffer.ToArray(), 0, (transformBuffer.Count - (i - originalOffset)));
                transformBuffer.Clear();
            }
            state = SearchState.LookForStart;
            for (var idx2 = 0; idx2 < currentStartStringsToSkip.Count; idx2++)
                currentStartStringsToSkip[idx2] = false;
            return 0;
        }
Ejemplo n.º 55
0
 private int HandleMatchingStopMatch(int i, byte b, byte[] buffer, ref int endTransformPosition, ref int startTransformPosition)
 {
     transformBuffer.Add(b);
     if (IsMatch(MatchingEnd.End, b))
     {
         matchPosition++;
         for (var idx = 0; idx < currentStartStringsToSkip.Count; idx++)
         {
             if (!currentStartStringsToSkip[idx] && matchPosition == EndStringUpper[idx].Length)
             {
                 endTransformPosition = ++i;
                 if (idx == 0) //head
                 {
                     DoTransform(buffer, ref endTransformPosition, ref startTransformPosition);
                     state = SearchState.LookForStart;
                     actualLength = actualLength - (i - actualOffset); actualOffset = i;
                 }
                 else
                 {
                     state = SearchState.LookForAdjacentScript;
                     SetAdjacent(true);
                     currentStartStringsToSkip[1] = false; //script tag
                 }
                 return 0;
             }
         }
     }
     else
     {
         state = SearchState.LookForStop;
         return 0;
     }
     return matchPosition;
 }
Ejemplo n.º 56
0
    // Iterate through
    public void StartSearch()
    {
        OnStatusChanged("Hi there");
        State = SearchState.Discovering_Files;

        //Initialize master list of files (organized by filesize)
        fileSizeList = new Dictionary<long,List<SmartFile>>();

        //Discover files in each path (adds to master list fileSizeList)
        foreach (string curSearchPath in pathsToSearch)
        {
            DiscoverFiles(curSearchPath);

        }

        //Run through list to find actual duplicates
        State = SearchState.Comparing_Files;

        for ( int i = 0; i < fileSizeList.Count; i++)
        {
            double progressPercent = (double) i / (double) fileSizeList.Count;
            OnProgressChanged(100f * progressPercent, fileSizeList.ElementAt(i).Value[0].fileName, state); //Report Progress

            CompareHashesAndAddDuplicates(fileSizeList.ElementAt(i).Value);
        }

        //Finish
        State = SearchState.Idle;
        OnProgressChanged(100, "FINISHED", state);
        OnScanFinished();
    }
Ejemplo n.º 57
0
	// Advances search one step 
	public SearchState SearchStep()
	{
		// Firstly break if the user has not initialised the search
		System.Diagnostics.Debug.Assert((m_State > SearchState.NotInitialized) && (m_State < SearchState.Invalid));

		// Next I want it to be safe to do a searchstep once the search has succeeded...
		if (m_State == SearchState.Succeeded || m_State == SearchState.Failed)
		{
			return m_State; 
		}

		// Failure is defined as emptying the open list as there is nothing left to 
		// search...
		// New: Allow user abort
		if (m_OpenList.Count == 0 || m_CancelRequest)
		{
			FreeSolutionNodes();
			m_State = SearchState.Failed;
			return m_State;
		}

		// Incremement step count
		m_Steps++;

		// Pop the best node (the one with the lowest f) 
		Node n = m_OpenList[0]; // get pointer to the node
		m_OpenList.RemoveAt(0);

		//System.Console.WriteLine("Checking node at " + n.m_UserState.position + ", f: " + n.f);

		// Check for the goal, once we pop that we're done
		if( n.m_UserState.IsGoal( m_Goal.m_UserState ) )
		{
			// The user is going to use the Goal Node he passed in 
			// so copy the parent pointer of n 
			m_Goal.parent = n.parent;
			m_Goal.g = n.g;

			// A special case is that the goal was passed in as the start state
			// so handle that here
			if( false == n.m_UserState.IsSameState( m_Start.m_UserState ) )
			{
				// set the child pointers in each node (except Goal which has no child)
				Node nodeChild = m_Goal;
				Node nodeParent = m_Goal.parent;

				do 
				{
					nodeParent.child = nodeChild;
					nodeChild = nodeParent;
					nodeParent = nodeParent.parent;
				} 
				while( nodeChild != m_Start ); // Start is always the first node by definition
			}

			// delete nodes that aren't needed for the solution
			//FreeUnusedNodes();

#if PATHFIND_DEBUG
			System.Console.WriteLine("GOAL REACHED! Steps: " + m_Steps + ", allocated nodes: " + m_AllocateNodeCount + ", MapSearchNodes: " + allocatedMapSearchNodes);
			System.Console.WriteLine("High water marks - Open:" + openListHighWaterMark + ", Closed: " + closedListHighWaterMark + ", Successors: " + successorListHighWaterMark);
#endif

			m_State = SearchState.Succeeded;
			return m_State;
		}
		else // not goal
		{
			// We now need to generate the successors of this node
			// The user helps us to do this, and we keep the new nodes in m_Successors ...
			m_Successors.Clear(); // empty vector of successor nodes to n

			// User provides this functions and uses AddSuccessor to add each successor of
			// node 'n' to m_Successors
			bool ret = false;
			if (n.parent != null)
			{
				ret = n.m_UserState.GetSuccessors(this, n.parent.m_UserState);
			}
			else
			{
				ret = n.m_UserState.GetSuccessors(this, null);
			}

			if (!ret)
			{
				m_Successors.Clear(); // empty vector of successor nodes to n

				// free up everything else we allocated
				FreeSolutionNodes();

				m_State = SearchState.OutOfMemory;
				return m_State;
			}

			// Now handle each successor to the current node ...
			Node successor = null;
			int successors_size = m_Successors.Count;
			for (int i = 0; i < successors_size; ++i)
			{
				successor = m_Successors[i];

				// 	The g value for this successor ...
				float newg = n.g + n.m_UserState.GetCost(successor.m_UserState);

				// Now we need to find whether the node is on the open or closed lists
				// If it is but the node that is already on them is better (lower g)
				// then we can forget about this successor

				// First linear search of open list to find node
				Node openlist_result = null;
				int openlist_size = m_OpenList.Count;
				bool foundOpenNode = false;
				for (int j = 0; j < openlist_size; ++j)
				{
					openlist_result = m_OpenList[j];
					if (openlist_result.m_UserState.IsSameState(successor.m_UserState))
					{
						foundOpenNode = true;
						break;					
					}
				}

				if (foundOpenNode)
				{
					// we found this state on open
					if (openlist_result.g <= newg)
					{
						// the one on Open is cheaper than this one
						continue;
					}
				}

				Node closedlist_result = null;
				int closedlist_size = m_ClosedList.Count;
				bool foundClosedNode = false;
				for (int k = 0; k < closedlist_size; ++k)
				{
					closedlist_result = m_ClosedList[k];
					if (closedlist_result.m_UserState.IsSameState(successor.m_UserState))
					{
						foundClosedNode = true;
						break;					
					}
				}

				if (foundClosedNode)
				{
					// we found this state on closed
					if (closedlist_result.g <= newg)
					{
						// the one on Closed is cheaper than this one
						continue;
					}
				}

				// This node is the best node so far with this particular state
				// so lets keep it and set up its AStar specific data ...
				successor.parent = n;
				successor.g = newg;
				successor.h = successor.m_UserState.GoalDistanceEstimate( m_Goal.m_UserState );
				successor.f = successor.g + successor.h;

				// Remove successor from closed if it was on it
				if (foundClosedNode)
				{
					// remove it from Closed
					m_ClosedList.Remove(closedlist_result);
				}

				// Update old version of this node
				if (foundOpenNode)
				{	   
			   		m_OpenList.Remove(openlist_result);
				}

				SortedAddToOpenList(successor);
			}

			// push n onto Closed, as we have expanded it now
			m_ClosedList.Add(n);

			if (m_ClosedList.Count > closedListHighWaterMark)
			{
				closedListHighWaterMark = m_ClosedList.Count;
			}
		} // end else (not goal so expand)

 		return m_State; // 'Succeeded' bool is false at this point. 
	}
Ejemplo n.º 58
0
 private void OnProgressChanged(double progressPercent, string progressDescription, SearchState state)
 {
     if (ProgressChanged != null)
     {
         ProgressChanged(progressPercent, progressDescription, state);
     }
 }
Ejemplo n.º 59
0
        public override IResult SearchKNN(object q, int K, IResult final_result)
        {
            var knr = Math.Min (this.RepeatSearch, this.Vertices.Count);
            var knrseq = new Result (knr);
            var n = this.Vertices.Count;
            int ss = Math.Min (this.SampleSize, this.Vertices.Count);

            // Get the HSP!!!
            bool[] subdb=new bool[this.DB.Count];
            for (int i = 0; i < ss; ++i) {
                var objID = this.rand.Next (0, n);
                subdb[objID]=true;
                //knrseq.Push (objID, d);
            }
            // Get the hsp-neigbors of q
            IList<int> hsp_neighbors= HSP.ComputeEdges(q,this.DB,subdb);
            foreach (int id in hsp_neighbors)
            {
                var d = this.DB.Dist (q, this.DB [id]);
                Console.WriteLine("id:{0} d:{1}",id,d);
                knrseq.Push(id,d);
            }
            Console.WriteLine( knrseq.Count);
            // End getting the HSP

            var res_array = new Result[knrseq.Count];
            int I = 0;
            // on a parallel implementation these two hashsets must be set to null
            var state = new SearchState ();
            // visited = evaluated = null;
            foreach (var p in knrseq) {
                var res = new Result (K);
                //Console.WriteLine ("** starting GreedySearch");
                this.GreedySearch(q, res, p.docid, state);
                res_array [I] = res;
                ++I;
            }
            var inserted = new HashSet<int> ();
            foreach (var res in res_array) {
                if (res == null) {
                    break;
                }
                foreach (var p in res) {
                    if (inserted.Add(p.docid)) {
                        final_result.Push(p.docid, p.dist);
                    }
                }
            }
            return final_result;
        }
Ejemplo n.º 60
0
 private void OnStateChanged(SearchState newState)
 {
     if (StateChanged != null)
     {
         StateChanged(newState);
     }
 }