/** * Constructs a problem with the specified components, and a default step * cost function (i.e. 1 per step). * * @param initialState * the initial state that the agent starts in. * @param actionsFn * a description of the possible actions available to the agent. * @param resultFn * a description of what each action does; the formal name for * this is the transition model, specified by a function * RESULT(s, a) that returns the state that results from doing * action a in state s. * @param goalTest * test determines whether a given state is a goal state. */ public GeneralProblem(S initialState, IActionsFunction <S, A> actionsFn, IResultFunction <S, A> resultFn, GoalTest <S> goalTest) : this(initialState, actionsFn, resultFn, goalTest, new DefaultStepCostFunction <S, A>()) { }
/** * Constructs an online search problem with the specified action function, * goal test, and a default step cost function. * * @param actionsFunction * ACTIONS(s), which returns a list of actions allowed in state s * @param goalTest * GOAL-TEST(s), which the agent can apply to a single state * description to determine if it is a goal state * @param stepCostFunction * the step-cost function c(s, a, s') - note that this cannot be * used until the agent knows that s' is the outcome */ public OnlineSearchProblem(ActionsFunction actionsFunction, GoalTest goalTest, StepCostFunction stepCostFunction) { this.actionsFunction = actionsFunction; this.goalTest = goalTest; this.stepCostFunction = stepCostFunction; }
public Problem(Object initialState, ActionsFunction actionsFunction, ResultFunction resultFunction, GoalTest goalTest) : this(initialState, actionsFunction, resultFunction, goalTest, new DefaultStepCostFunction()) { }
/** * Starts the genetic algorithm and stops after a specified number of * iterations. */ public virtual Individual <A> geneticAlgorithm(ICollection <Individual <A> > initPopulation, IFitnessFunction <A> fitnessFn, int maxIterations) { GoalTest <Individual <A> > goalTest = (state) => getIterations() >= maxIterations; return(geneticAlgorithm(initPopulation, fitnessFn, goalTest, 0L)); }
public Problem(Object initialState, SuccessorFunction successorFunction, GoalTest goalTest, StepCostFunction stepCostFunction, HeuristicFunction heuristicFunction) : this(initialState, successorFunction, goalTest, stepCostFunction) { this.heuristicFunction = heuristicFunction; }
/** * Constructs an online search problem with the specified action function, * goal test, and a default step cost function. * * @param actionsFunction * ACTIONS(s), which returns a list of actions allowed in state s * @param goalTest * GOAL-TEST(s), which the agent can apply to a single state * description to determine if it is a goal state */ public OnlineSearchProblem(ActionsFunction actionsFunction, GoalTest goalTest) { this.actionsFunction = actionsFunction; this.goalTest = goalTest; this.stepCostFunction = new DefaultStepCostFunction(); }
/** * Returns a composed predicate that represents a short-circuiting logical * OR of this predicate and another. When evaluating the composed * predicate, if this predicate is {@code true}, then the {@code other} * predicate is not evaluated. * * <p>Any exceptions thrown during evaluation of either predicate are relayed * to the caller; if evaluation of this predicate throws an exception, the * {@code other} predicate will not be evaluated. * * @param other a predicate that will be logically-ORed with this * predicate * @return a composed predicate that represents the short-circuiting logical * OR of this predicate and the {@code other} predicate * @throws NullPointerException if other is null */ public static GoalTest <S> or <S>(this GoalTest <S> orig, GoalTest <S> other) { if (other == null) { throw new ArgumentNullException("other cannot be null."); } return((state) => orig(state) || other(state)); }
public Problem(Object initialState, SuccessorFunction successorFunction, GoalTest goalTest) { this.initialState = initialState; this.successorFunction = successorFunction; this.goalTest = goalTest; this.stepCostFunction = new DefaultStepCostFunction(); this.heuristicFunction = new DefaultHeuristicFunction(); }
public Problem(Object initialState, ActionsFunction actionsFunction, ResultFunction resultFunction, GoalTest goalTest, StepCostFunction stepCostFunction) { this.initialState = initialState; this.actionsFunction = actionsFunction; this.resultFunction = resultFunction; this.goalTest = goalTest; this.stepCostFunction = stepCostFunction; }
/** * Constructor */ public NondeterministicProblem(S initialState, IActionsFunction <S, A> actionsFn, IResultsFunction <S, A> resultsFn, GoalTest <S> goalTest, IStepCostFunction <S, A> stepCostFn) { this.initialState = initialState; this.actionsFn = actionsFn; this.resultsFn = resultsFn; this.goalTest = goalTest; this.stepCostFn = stepCostFn; }
/** * Constructs a problem with the specified components, which includes a step * cost function. * * @param initialState * the initial state of the agent. * @param actionsFunction * a description of the possible actions available to the agent. * @param resultFunction * a description of what each action does; the formal name for * this is the transition model, specified by a function * RESULT(s, a) that returns the state that results from doing * action a in state s. * @param goalTest * test determines whether a given state is a goal state. * @param stepCostFunction * a path cost function that assigns a numeric cost to each path. * The problem-solving-agent chooses a cost function that * reflects its own performance measure. */ public Problem(Object initialState, ActionsFunction actionsFunction, ResultFunction resultFunction, GoalTest goalTest, StepCostFunction stepCostFunction) { this.initialState = initialState; this.actionsFunction = actionsFunction; this.resultFunction = resultFunction; this.goalTest = goalTest; this.stepCostFunction = stepCostFunction; }
public Problem(object initialSetup, OperatorsFunction operatorsFunction, ResultFunction resultFunction, GoalTest goalTest, StepCostFunction stepCostFunction) { this.initialSetup = initialSetup; this.operatorsFunction = operatorsFunction; this.resultFunction = resultFunction; this.goalTest = goalTest; this.stepCostFunction = stepCostFunction; }
public void setUp() { oneBoard = new NQueensBoard(1); eightBoard = new NQueensBoard(8); board = new NQueensBoard(8); actionsFn = NQueensFunctions.getIFActionsFunction(); resultFn = NQueensFunctions.getResultFunction(); goalTest = NQueensFunctions.testGoal; }
public Problem( TState initalState, ActionFunction <TState, TAction> actionFunction, ResultFunction <TState, TAction> resultFunction, GoalTest <TState> goalTest, StepCost <TState, TAction> stepCost) { InitalState = initalState; ActionFunction = actionFunction; ResultFunction = resultFunction; GoalTest = goalTest; StepCost = stepCost; }
// Devuelve si es cierto o no que un nodo contenga una solución para el problema // Realmente este método sólo tiene interés para meter comprobaciones adicionales, ahora mismo no hace nada especial public static bool IsGoal(Problem p, Node n) { bool isGoal = false; GoalTest gt = p.GoalTest; if (gt.IsGoal(n.Setup)) { // Si usáramos una interfaz adicional a GoalTest (SolutionChecker se llama la clase) aquí dentro deberíamos comprobar adicionalmente // si es una solución aceptable o no (IsAcceptableSolution se llama el método) isGoal = true; } return(isGoal); }
static void nQueensGeneticAlgorithmSearch() { System.Console.WriteLine("\nNQueensDemo GeneticAlgorithm -->"); try { IFitnessFunction <int> fitnessFunction = NQueensGenAlgoUtil.getFitnessFunction(); GoalTest <Individual <int> > goalTest = NQueensGenAlgoUtil.getGoalTest(); // Generate an initial population ISet <Individual <int> > population = CollectionFactory.CreateSet <Individual <int> >(); for (int i = 0; i < 50; ++i) { population.Add(NQueensGenAlgoUtil.generateRandomIndividual(boardSize)); } GeneticAlgorithm <int> ga = new GeneticAlgorithm <int>(boardSize, NQueensGenAlgoUtil.getFiniteAlphabetForBoardOfSize(boardSize), 0.15); // Run for a set amount of time Individual <int> bestIndividual = ga.geneticAlgorithm(population, fitnessFunction, goalTest, 1000L); System.Console.WriteLine("Max Time (1 second) Best Individual=\n" + NQueensGenAlgoUtil.getBoardForIndividual(bestIndividual)); System.Console.WriteLine("Board Size = " + boardSize); //System.Console.WriteLine("# Board Layouts = " + (new BigDecimal(boardSize)).pow(boardSize)/*);*/ System.Console.WriteLine("Fitness = " + fitnessFunction.apply(bestIndividual)); System.Console.WriteLine("Is Goal = " + goalTest(bestIndividual)); System.Console.WriteLine("Population Size = " + ga.getPopulationSize()); System.Console.WriteLine("Iterations = " + ga.getIterations()); System.Console.WriteLine("Took = " + ga.getTimeInMilliseconds() + "ms."); // Run till goal is achieved bestIndividual = ga.geneticAlgorithm(population, fitnessFunction, goalTest, 0L); System.Console.WriteLine(""); System.Console .WriteLine("Goal Test Best Individual=\n" + NQueensGenAlgoUtil.getBoardForIndividual(bestIndividual)); System.Console.WriteLine("Board Size = " + boardSize); //System.Console.WriteLine("# Board Layouts = " + (new BigDecimal(boardSize)).pow(boardSize)/*);*/ System.Console.WriteLine("Fitness = " + fitnessFunction.apply(bestIndividual)); System.Console.WriteLine("Is Goal = " + goalTest(bestIndividual)); System.Console.WriteLine("Population Size = " + ga.getPopulationSize()); System.Console.WriteLine("Itertions = " + ga.getIterations()); System.Console.WriteLine("Took = " + ga.getTimeInMilliseconds() + "ms."); } catch (Exception e) { throw e; } }
// Construye un resolutor de dimensiones (rows) por (columns), como mínimo debe ser de 1x1 // No necesita el puzle en sí, pues eso lo recibirá después public SlidingPuzzleSolver(uint rows, uint columns) { if (rows == 0) { throw new ArgumentException(string.Format("{0} is not a valid rows value", rows), "rows"); } if (columns == 0) { throw new ArgumentException(string.Format("{0} is not a valid columns value", columns), "columns"); } aoFunction = SlidingPuzzleFunctionFactory.GetApplicableOperatorsFunction(); tModel = SlidingPuzzleFunctionFactory.GetTransitionModel(); gTest = new SlidingPuzzleGoalTest(rows, columns); }
public Problem GetProblem(Object owner, IContextLookup globalVars, Object initialState) { Problem toReturn; var objActionsFunction = ActionsFunction.EvaluateTyped(owner, globalVars); var objResultFunction = ResultFunction.EvaluateTyped(owner, globalVars); var objGoalTest = GoalTest.EvaluateTyped(owner, globalVars); if (StepCostFunction.Enabled) { var objStepCostFunction = StepCostFunction.Entity.EvaluateTyped(owner, globalVars); toReturn = new Problem(initialState, objActionsFunction, objResultFunction, objGoalTest, objStepCostFunction); } else { toReturn = new Problem(initialState, objActionsFunction, objResultFunction, objGoalTest); } return(toReturn); }
/** * Calls the goal test of the problem and - if the goal test is effectively * a {@link SolutionChecker} - additionally checks, whether the solution is * acceptable. Solution checkers can be used to analyze several or all * solutions with only one search run. */ public static bool isGoalState(Problem p, Node n) { bool isGoal = false; GoalTest gt = p.getGoalTest(); if (gt.isGoalState(n.State)) { if (gt is SolutionChecker) { isGoal = ((SolutionChecker)gt).isAcceptableSolution( getSequenceOfActions(n), n.State); } else { isGoal = true; } } return(isGoal); }
// Devuelve si es cierto o no que un nodo contiene una configuración objetivo public static bool IsGoalSetup(Problem p, Node n) { bool isGoal = false; GoalTest gt = p.GetGoalTest(); if (gt.IsGoalSetup(n.GetSetup())) { if (gt is SolutionChecker) { isGoal = ((SolutionChecker)gt).IsAcceptableSolution( SearchUtils.GetOperatorsFromNodes(n.GetPathFromRoot()), n .GetSetup()); } else { isGoal = true; } } return(isGoal); }
public static bool isGoalState(Problem p, Node n) { bool isGoal = false; GoalTest gt = p.getGoalTest(); if (gt.isGoalState(n.getState())) { if (gt is SolutionChecker) { isGoal = ((SolutionChecker)gt).isAcceptableSolution( SearchUtils.actionsFromNodes(n.getPathFromRoot()), n .getState()); } else { isGoal = true; } } return(isGoal); }
/** * Template method controlling search. It returns the best individual in the * specified population, according to the specified FITNESS-FN and goal * test. * * @param initPopulation * a set of individuals * @param fitnessFn * a function that measures the fitness of an individual * @param goalTest * test determines whether a given individual is fit enough to * return. Can be used in subclasses to implement additional * termination criteria, e.g. maximum number of iterations. * @param maxTimeMilliseconds * the maximum time in milliseconds that the algorithm is to run * for (approximate). Only used if > 0L. * @return the best individual in the specified population, according to the * specified FITNESS-FN and goal test. */ // function GENETIC-ALGORITHM(population, FITNESS-FN) returns an individual // inputs: population, a set of individuals // FITNESS-FN, a function that measures the fitness of an individual public virtual Individual <A> geneticAlgorithm(ICollection <Individual <A> > initPopulation, IFitnessFunction <A> fitnessFn, GoalTest <Individual <A> > goalTest, long maxTimeMilliseconds) { Individual <A> bestIndividual = null; // Create a local copy of the population to work with ICollection <Individual <A> > population = CollectionFactory.CreateQueue <Individual <A> >(initPopulation); // Validate the population and setup the instrumentation validatePopulation(population); updateMetrics(population, 0, 0L); IStopWatch sw = CommonFactory.CreateStopWatch(); // repeat int itCount = 0; do { population = nextGeneration(population, fitnessFn); bestIndividual = retrieveBestIndividual(population, fitnessFn); updateMetrics(population, ++itCount, sw.GetElapsedMilliseconds()); // until some individual is fit enough, or enough time has elapsed if (maxTimeMilliseconds > 0L && sw.GetElapsedMilliseconds() > maxTimeMilliseconds) { break; } if (currIsCancelled) { break; } } while (!goalTest(bestIndividual)); notifyProgressTrackers(itCount, population); // return the best individual in population, according to FITNESS-FN return(bestIndividual); }
// function GENETIC-ALGORITHM(population, FITNESS-FN) returns an individual // inputs: population, a set of individuals // FITNESS-FN, a function that measures the fitness of an individual public String geneticAlgorithm(Set<String> population, FitnessFunction fitnessFn, GoalTest goalTest) { String bestIndividual = null; validatePopulation(population); clearInstrumentation(); setPopulationSize(population.Count); // repeat int cnt = 0; do { bestIndividual = ga(population, fitnessFn); cnt++; // until some individual is fit enough, or enough time has elapsed } while (!goalTest.isGoalState(bestIndividual)); setIterations(cnt); // return the best individual in population, according to FITNESS-FN return bestIndividual; }
private static void SolveProblem <TState, TAction>( ActionFunction <TState, TAction> actionFunction, ResultFunction <TState, TAction> resultFunction, GoalTest <TState> goalTest, StepCost <TState, TAction> stepCost, TState initialState, IGraphSearch <TState, TAction> searchAlgorithm) { var problem = new Problem <TState, TAction>( initialState, actionFunction, resultFunction, goalTest, stepCost); var solution = searchAlgorithm.Search(problem); Console.WriteLine("Solution:"); Console.WriteLine("========="); foreach (var node in solution) { Console.WriteLine(node.State); } Console.ReadKey(); }
// function GENETIC-ALGORITHM(population, FITNESS-FN) returns an individual // inputs: population, a set of individuals // FITNESS-FN, a function that measures the fitness of an individual public String geneticAlgorithm(Set <String> population, FitnessFunction fitnessFn, GoalTest goalTest) { String bestIndividual = null; validatePopulation(population); clearInstrumentation(); setPopulationSize(population.Count); // repeat int cnt = 0; do { bestIndividual = ga(population, fitnessFn); cnt++; // until some individual is fit enough, or enough time has elapsed } while (!goalTest.isGoalState(bestIndividual)); setIterations(cnt); // return the best individual in population, according to FITNESS-FN return(bestIndividual); }
private Tile BFS(Tile start, GoalTest test) { HashSet <Tile> closedset = new HashSet <Tile>(); Queue <Tile> openqueue = new Queue <Tile>(); openqueue.Enqueue(start); while (openqueue.Count > 0) { Tile current = openqueue.Dequeue(); closedset.Add(current); if (test(current)) { return(current); } foreach (Tile t in getNeighbors(current)) { if (!closedset.Contains(t)) { openqueue.Enqueue(t); } } } return(null); }
/** * Constructor */ public NondeterministicProblem(S initialState, IActionsFunction <S, A> actionsFn, IResultsFunction <S, A> resultsFn, GoalTest <S> goalTest) : this(initialState, actionsFn, resultsFn, goalTest, new DefaultStepCostFunction <S, A>()) { }
public BidirectionalMapProblem(Map map, string initialState, string goalState, GoalTest <string> goalTest) : base(initialState, MapFunctions.createActionsFunction(map), MapFunctions.createResultFunction(), goalTest, MapFunctions.createDistanceStepCostFunction(map)) { reverseProblem = new GeneralProblem <string, MoveToAction>( goalState, MapFunctions.createReverseActionsFunction(map), MapFunctions.createResultFunction(), initialState.Equals, MapFunctions.createDistanceStepCostFunction(map)); }
// Crea un problema partiendo de todos sus componentes public Problem(object iSetup, ApplicableOperatorsFunction aoFunction, TransitionModel tModel, GoalTest gTest, StepCostFunction scFunction) { this.InitialSetup = iSetup; this.ApplicableOperatorsFunction = aoFunction; this.TransitionModel = tModel; this.GoalTest = gTest; this.StepCostFunction = scFunction; }
private Tile BFS(Tile start, GoalTest test) { HashSet<Tile> closedset = new HashSet<Tile>(); Queue<Tile> openqueue = new Queue<Tile>(); openqueue.Enqueue(start); while(openqueue.Count > 0) { Tile current = openqueue.Dequeue(); closedset.Add(current); if (test(current)) return current; foreach (Tile t in getNeighbors(current)) if (!closedset.Contains(t)) openqueue.Enqueue(t); } return null; }
public Tile FindTileF(Tile start, GoalTest test) { return BFS(start, test); }
public OnlineSearchProblem(ActionsFunction actionsFunction, GoalTest goalTest) { this(actionsFunction, goalTest, new DefaultStepCostFunction()); }
/** * Constructs a problem with the specified components, and a default step * cost function (i.e. 1 per step). * * @param initialState * the initial state that the agent starts in. * @param actionsFunction * a description of the possible actions available to the agent. * @param resultFunction * a description of what each action does; the formal name for * this is the transition model, specified by a function * RESULT(s, a) that returns the state that results from doing * action a in state s. * @param goalTest * test determines whether a given state is a goal state. */ public Problem(Object initialState, ActionsFunction actionsFunction, ResultFunction resultFunction, GoalTest goalTest) : this(initialState, actionsFunction, resultFunction, goalTest, new DefaultStepCostFunction()) { }
// // PUBLIC METHODS // // Construye un resolutor (no necesita el puzle, se le pasará después) public TankPuzzleSolver() { oFunction = TankPuzzleFunctionFactory.getOperatorsFunction(); rFunction = TankPuzzleFunctionFactory.getResultFunction(); goalTest = new TankPuzzleGoalTest(); }
public BidirectionalMapProblem(Map map, String initialState, String goalState, GoalTest goalTest) : base(initialState, MapFunctionFactory.getActionsFunction(map), MapFunctionFactory.getResultFunction(), goalTest, new MapStepCostFunction(map)) { this.map = map; reverseProblem = new Problem(goalState, MapFunctionFactory.getReverseActionsFunction(map), MapFunctionFactory.getResultFunction(), new DefaultGoalTest(initialState), new MapStepCostFunction(map)); }
public Problem(Object initialState, SuccessorFunction successorFunction, GoalTest goalTest, StepCostFunction stepCostFunction) : this(initialState, successorFunction, goalTest) { this.stepCostFunction = stepCostFunction; }
/** * Returns a sequence of actions using A* Search. * * @param current * the agent's current position * @param goals * a set of squares; try to plan a route to one of them * @param allowed * a set of squares that can form part of the route * * @return the best sequence of actions that the agent have to do to reach a * goal from the current position. */ public ICollection <IAction> planRoute(AgentPosition current, ISet <Room> goals, ISet <Room> allowed) { // Every square represent 4 possible positions for the agent, it could // be in different orientations. For every square in allowed and goals // sets we add 4 squares. ISet <AgentPosition> allowedPositions = CollectionFactory.CreateSet <AgentPosition>(); foreach (Room allowedRoom in allowed) { int x = allowedRoom.getX(); int y = allowedRoom.getY(); allowedPositions.Add(new AgentPosition(x, y, AgentPosition.Orientation.FACING_WEST)); allowedPositions.Add(new AgentPosition(x, y, AgentPosition.Orientation.FACING_EAST)); allowedPositions.Add(new AgentPosition(x, y, AgentPosition.Orientation.FACING_NORTH)); allowedPositions.Add(new AgentPosition(x, y, AgentPosition.Orientation.FACING_SOUTH)); } ISet <AgentPosition> goalPositions = CollectionFactory.CreateSet <AgentPosition>(); foreach (Room goalRoom in goals) { int x = goalRoom.getX(); int y = goalRoom.getY(); goalPositions.Add(new AgentPosition(x, y, AgentPosition.Orientation.FACING_WEST)); goalPositions.Add(new AgentPosition(x, y, AgentPosition.Orientation.FACING_EAST)); goalPositions.Add(new AgentPosition(x, y, AgentPosition.Orientation.FACING_NORTH)); goalPositions.Add(new AgentPosition(x, y, AgentPosition.Orientation.FACING_SOUTH)); } WumpusCave cave = new WumpusCave(kb.getCaveXDimension(), kb.getCaveYDimension(), allowedPositions); GoalTest <AgentPosition> goalTest = goalPositions.Contains; IProblem <AgentPosition, IAction> problem = new GeneralProblem <AgentPosition, IAction>(current, WumpusFunctionFunctions.createActionsFunction(cave), WumpusFunctionFunctions.createResultFunction(), goalTest); IToDoubleFunction <Node <AgentPosition, IAction> > h = new ManhattanHeuristicFunction(goals); ISearchForActions <AgentPosition, IAction> search = new AStarSearch <AgentPosition, IAction>( new GraphSearch <AgentPosition, IAction>(), h); SearchAgent <AgentPosition, IAction> agent; ICollection <IAction> actions = null; try { agent = new SearchAgent <AgentPosition, IAction>(problem, search); actions = agent.getActions(); // Search agent can return a NoOp if already at goal, // in the context of this agent we will just return // no actions. if (actions.Size() == 1 && actions.Get(0).IsNoOp()) { actions = CollectionFactory.CreateQueue <IAction>(); } } catch (Exception e) { throw e; } return(actions); }