f8c17c513b654036430696c31f3694db28c34f4e
[nit.git] / lib / ai / backtrack.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
9 # another product.
10
11 # Basic framework for active backtrack solver
12 #
13 # This module provides a simple abstract class `BacktrackProblem[S,A]` to be specialized for a specific problem.
14 #
15 # The concrete class `BacktrackSolver` is used to configure, query, and run a solver for a given problem.
16 module backtrack
17
18 # Abstract backtrack problem of states (`S`) and actions (`A`).
19 #
20 # This class serves to model search problems using a backtracking approach.
21 # A state, `S`, is a point in the search problem and fully model a given state of the world.
22 # An action, `A`, is an available mean of transition between two states.
23 # While there is a potential large number of distinct states and actions, there should be only
24 # a small number of possible actions from a specific state (thus, a small, or at least finite, branching factor).
25 #
26 # The point this class is that the state is a mutable object, the roles of the actions is to modify
27 # the state.
28 #
29 # This abstract class is generic and made to work with any kind of states and actions.
30 # Therefore, specific subclasses must be developed to implements the required services:
31 #
32 # * `initial_state`
33 # * `actions`
34 # * `apply_action`
35 # * `backtrack`
36 # * `is_goal`
37 #
38 # # Basic search
39 #
40 # The method `solve` returns a new solver for a backtrack search.
41 class BacktrackProblem[S: Object,A]
42 # The starting state of the problem.
43 # It is this object that will be modified by `apply_action` and `backtrack`.
44 fun initial_state: S is abstract
45
46 # The available and applicable actions for a given state
47 # Because of `backtracking`, actions must also be reversible (see `backtrack`).
48 #
49 # If there is no available actions, null (or an empty collection) must be returned.
50 #
51 # In order to optimise the search time, it is sensible to return `null`
52 # (or an empty collection) as early as possible.
53 #
54 # Node: to help some specific implementations, the current node is also available.
55 # See `BacktrackNode` for details.
56 fun actions(state: S, node: BacktrackNode[A]): nullable Collection[A] is abstract
57
58 # Modify `state` by applying `action`
59 # The `action` comes from an earlier invocation of `actions`.
60 fun apply_action(state: S, action: A) is abstract
61
62 # Modify `state` by undoing `action`
63 # Because of this method, it is important that any action can be undone
64 # knowing only the post-state and the action.
65 fun backtrack(state: S, action: A) is abstract
66
67 # Is the state a goal state?
68 # Once a goal state is found, the solver is automatically stopped.
69 # See `BacktrackSolver.run`.
70 fun is_goal(state: S): Bool is abstract
71
72 # Return a new solver
73 fun solve: BacktrackSolver[S,A] do
74 return new BacktrackSolver[S,A](self, initial_state)
75 end
76 end
77
78 # A running solver for a given problem, that can be configured and controlled.
79 #
80 #
81 # # Basic run and results.
82 #
83 # 1. Instantiate it with the method `solve` from `BacktrackProblem`.
84 # 2. Apply the method `run`, that will search and return a solution.
85 # 3. Retrieve information from the solution.
86 #
87 # ~~~~
88 # var p: BacktrackProblem = new MyProblem
89 # var solver = p.solve
90 # var res = solver.run
91 # if res != null then
92 # print "Found solution in {res.depth} actions: {res.plan.join(", ")}"
93 # print "The state of the solution is: {solver.state}"
94 # end
95 # ~~~~
96 #
97 #
98 # # Step-by-step runs and multiple runs
99 #
100 # The `run_steps` method (see also `steps`, and `steps_limit`) can be used to run only a maximum number of steps.
101 # Thus, this method can be used as a *co-routine* and be run periodically for a small amount of time.
102 #
103 # `run` and `run_steps` return the next solution.
104 # A subsequent call to `run` returns the following solution and so on.
105 #
106 # When there is no more solutions available, `null` is returned and `is_running` become false.
107 #
108 # Between run, the state of the current search can be read.
109 #
110 #
111 # # Search-trees
112 #
113 # Internally, solvers use a zipper on the virtual search-tree where nodes are elements in the apply/backtrack graph.
114 # See the class `BacktrackNode` for details
115 #
116 # The `run` and `node` methods return a `BacktrackNode` that can be used to retrieve a lot of useful information,
117 # like the full `path` or the `plan`.
118 # If only the solved state is required, the `state` method from the solver gives it.
119 class BacktrackSolver[S: Object, A]
120 # The problem currently solved
121 var problem: BacktrackProblem[S,A]
122
123 # The current state.
124 # Do not modify it directly: the solver will do that by its own use of
125 # `problem.apply_action` and `problem.backtrack`.
126 var state: S
127
128 # The current `node` in the backtrack-zipper.
129 var node: nullable BacktrackNode[A] = null
130
131 # Is the solver still running?
132 # A running solver has not yet exhausted all the possible solutions.
133 var is_running = true
134
135 # Initialize `node`
136 private fun start: BacktrackNode[A]
137 do
138 assert node == null
139 var node = new BacktrackNode[A](null, null, 0, 0)
140 self.node = node
141 return node
142 end
143
144
145 # The total steps executed since the beginning.
146 var steps = 0
147
148 # Limit in the number of steps for a `run`.
149 #
150 # One can modify this value then `run` or just call `run_steps`.
151 #
152 # Use 0 for no limit.
153 # Default: 0
154 var steps_limit = 0 is writable
155
156 # Update `steps_limit` then just run some additional steps.
157 # Return the `node` corresponding to the found solution, or `null` if no solution is found.
158 fun run_steps(steps: Int): nullable BacktrackNode[A]
159 do
160 steps_limit = self.steps + steps
161 return run
162 end
163
164 # Run the solver and return the next solution found (if any).
165 # Return null is one of these is true:
166 # * `steps_limit` is reached
167 # * no more reachable solution, in this case `is_running` become false.
168 fun run: nullable BacktrackNode[A]
169 do
170 var node = self.node
171 # Not yet started, of finished?
172 if node == null then
173 if steps > 0 then return null
174 node = start
175 var res = problem.is_goal(state)
176 if res then return node
177 end
178
179 loop
180 if steps_limit > 0 and steps > steps_limit then break
181 steps += 1
182
183 var totry = node.totry
184
185 # It is the first visit in this state?
186 if totry == null then
187 var actions = problem.actions(state, node)
188 if actions != null and not actions.is_empty then
189 totry = actions.to_a
190 node.totry = totry
191 end
192 end
193
194 #print state
195 #print node
196
197 # No remaining actions?
198 if totry == null or totry.is_empty then
199 #print "Backtrack"
200 var a = node.action
201 if a == null then
202 #print "no more action"
203 is_running = false
204 self.node = null
205 return null
206 end
207
208 problem.backtrack(state, a)
209 node = node.parent
210 continue
211 end
212
213 var a = totry.pop
214 problem.apply_action(state, a)
215 #print "Play {a or else ""}"
216 node = new BacktrackNode[A](node, a, node.depth+1, steps)
217
218 var res = problem.is_goal(state)
219 if res then
220 self.node = node
221 return node
222 end
223 end
224 self.node = node
225 return null
226 end
227
228 redef fun to_s do return "{node or else "#0"}"
229 end
230
231 # A node in the backtrack-zipper visited by a `BacktrackSolver`.
232 #
233 # The solver visits the virtual search tree with a zipper.
234 #
235 # A node is the zipper (this class) is associated to:
236 # * a state of the problem (indirectly),
237 # * the actions not yet explored from the state (see `totry`)
238 # * the action that yields to the state (see `action`), used to backtrack.
239 # * and the parent node in the zipper (see `parent`).
240 #
241 # There is no direct link between a node and a state; it is unneeded
242 # since the same state is used, and mutated, during the whole execution of the solver.
243 #
244 # This class is exposed to allow queries on the solution provided by the solver.
245 class BacktrackNode[A]
246 # The previous node in the backtrack-zipper
247 var parent: nullable BacktrackNode[A]
248
249 # The last action executed
250 var action: nullable A
251
252 # The remaining actions to try from this node
253 var totry: nullable Array[A] = null
254
255 # The depth of `self` in the search-tree.
256 var depth: Int
257
258 # The number of steps needed by the solver to process `self`.
259 # This is just a useless generation number, but could be used to evaluate
260 # the behavior of search algorithms.
261 var steps: Int
262
263 # Build a sequence of nodes from the initial node to `self`
264 # ensure `result.first.parent == null and result.last == self`
265 fun path: Sequence[BacktrackNode[A]]
266 do
267 var res = new List[BacktrackNode[A]]
268 res.add(self)
269 var node = parent
270 while node != null do
271 res.unshift(node)
272 node = node.parent
273 end
274 return res
275 end
276
277 # Build a sequence of actions from the initial state to `self`
278 # See `path` for a more detailed plan.
279 fun plan: Sequence[A]
280 do
281 var res = new List[A]
282 var node: nullable BacktrackNode[A] = self
283 while node != null do
284 var a = node.action
285 if a != null then res.unshift(a)
286 node = node.parent
287 end
288 return res
289 end
290
291 redef fun to_s do
292 var res = "#{steps} d={depth}"
293 var tt = totry
294 if tt != null then res += " tt={tt.join(" ")}"
295 return res
296 end
297 end