-
Notifications
You must be signed in to change notification settings - Fork 2
/
planner.spec.ts
632 lines (559 loc) · 19.3 KB
/
planner.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
import { expect, log } from '~/test-utils';
import { Planner } from './planner';
import type { Instruction } from './task';
import { Task } from './task';
import { plan, branch, fork, stringify } from './testing';
describe('Planner', () => {
describe('plan', () => {
it('block stacking problem: simple', () => {
type Table = 'table';
type Hand = 'hand';
type Block = 'a' | 'b' | 'c';
type Location = Block | Table | Hand;
type State = {
blocks: { [block in Block]: Location };
};
const isBlock = (x: Location): x is Block =>
x !== 'table' && x !== 'hand';
const isClear = (blocks: State['blocks'], location: Location) => {
if (isBlock(location) || location === 'hand') {
// No block is on top of the location
return Object.values(blocks).every((l) => l !== location);
}
// The table is always clear
return true;
};
const isHolding = (blocks: State['blocks']) => {
// There is some block on the hand
return !isClear(blocks, 'hand');
};
const take = Task.of<State>().from({
lens: '/blocks/:block',
condition: (_, { system, block }) =>
isClear(system.blocks, block) && !isHolding(system.blocks),
effect: (location) => {
// Update the block
location._ = 'hand';
},
description: ({ block }) => `take block ${block}`,
});
const put = Task.of<State>().from({
lens: '/blocks/:block',
condition: (location, { system, target, block }) =>
location === 'hand' &&
target !== block &&
isClear(system.blocks, target),
effect: (location, { target }) => {
// Update the block
location._ = target;
},
description: ({ target, block }) => `put ${block} on ${target}`,
});
const allClearBlocks = (blocks: State['blocks']) => {
return Object.keys(blocks).filter((block) =>
isClear(blocks, block as Block),
) as Block[];
};
/**
* This method implements the following block-stacking algorithm [1]:
*
* - If there's a clear block x that can be moved to a place where it won't
* need to be moved again, then return a todo list that includes goals to
* move it there, followed by mgoal (to achieve the remaining goals).
* Otherwise, if there's a clear block x that needs to be moved out of the
* way to make another block movable, then return a todo list that includes
* goals to move x to the table, followed by mgoal.
* - Otherwise, no blocks need to be moved.
* [1] N. Gupta and D. S. Nau. On the complexity of blocks-world
* planning. Artificial Intelligence 56(2-3):223–254, 1992.
*
* Source: https://github.com/dananau/GTPyhop/blob/main/Examples/blocks_hgn/methods.py
*/
const move = Task.of<State>().from({
lens: '/blocks',
method: (blocks, { target }) => {
for (const b of allClearBlocks(blocks)) {
// The block is free and it can be moved to the final target (another block or the table)
if (isClear(blocks, target[b])) {
return [
// TODO: take doesn't really need a target. The grounding function might
// be able to infer if the target is needed depending on the operation?
take({ block: b, target: target[b] }),
put({ block: b, target: target[b] }),
];
}
}
// If we get here, no blocks can be moved to the final location so
// we move it to the table
for (const b of allClearBlocks(blocks)) {
// The block is free and it can be moved to the final target (another block or the table)
return [
take({ block: b, target: target[b] }),
put({ block: b, target: 'table' }),
];
}
// The method is not applicable here
return [];
},
description:
'find blocks that can be moved to the final location or to the table',
});
const planner = Planner.from<State>({
tasks: [take, put, move],
config: { trace: log },
});
const result = planner.findPlan(
{
blocks: { a: 'table', b: 'a', c: 'b' },
},
{ blocks: { a: 'b', b: 'c', c: 'table' } },
);
expect(stringify(result)).to.deep.equal(
plan()
.action('take block c')
.action('put c on table')
.action('take block b')
.action('put b on c')
.action('take block a')
.action('put a on b')
.end(),
);
});
it('block stacking problem: fancy version', () => {
type Table = 'table';
type Hand = 'hand';
type Block = 'a' | 'b' | 'c';
type Location = Block | Table | Hand;
type State = {
blocks: { [block in Block]: Location };
};
const isBlock = (x: Location): x is Block =>
x !== 'table' && x !== 'hand';
const isClear = (blocks: State['blocks'], location: Location) => {
if (isBlock(location) || location === 'hand') {
// No block is on top of the location
return Object.values(blocks).every((l) => l !== location);
}
// The table is always clear
return true;
};
const isHolding = (blocks: State['blocks']) => {
// There is some block on the hand
return !isClear(blocks, 'hand');
};
const pickup = Task.of<State>().from({
lens: '/blocks/:block',
condition: (location, { system, block }) =>
isClear(system.blocks, block) &&
location === 'table' &&
!isHolding(system.blocks),
effect: (location) => {
// Update the block
location._ = 'hand';
},
description: ({ block }) => `pickup block ${block}`,
});
const unstack = Task.of<State>().from({
lens: '/blocks/:block',
condition: (location, { system, block }) =>
// The block has no other blocks on top
isClear(system.blocks, block) &&
// The block is on top of other block (not in the hand or the table)
!['table', 'hand'].includes(location) &&
// The hand is not holding any other block
!isHolding(system.blocks),
effect: (location) => {
// Update the block
location._ = 'hand';
},
description: ({ block }) => `unstack block ${block}`,
});
const putdown = Task.of<State>().from({
lens: '/blocks/:block',
condition: (location) => location === 'hand',
effect: (location) => {
// Update the block
location._ = 'table';
// Mark the hand as free
},
description: ({ block }) => `put down block ${block}`,
});
const stack = Task.of<State>().from({
lens: '/blocks/:block',
condition: (location, { system, target }) =>
// The target has no other blocks on top
isClear(system.blocks, target) &&
// The hand is holding the block
location === 'hand',
effect: (location, { target }) => {
// Update the block
location._ = target;
},
description: ({ block, target }) =>
`stack block ${block} on top of block ${target}`,
});
const take = Task.of<State>().from({
lens: '/blocks/:block',
method: (location, { system, block, target }) => {
if (isClear(system.blocks, location)) {
if (location === 'table') {
// If the block is on the table we need to run the pickup task
return [pickup({ block, target })];
} else {
// Otherwise we unstack the block from another block
return [unstack({ block, target })];
}
}
return [];
},
description: ({ block }) => `take block ${block}`,
});
// There is really not that much of a difference between putdown and stack
// this is just to test that the planner can work with nested methods
const put = Task.of<State>().from({
lens: '/blocks/:block',
method: (location, { block, target }) => {
if (location === 'hand') {
if (target === 'table') {
return [putdown({ block, target })];
} else {
return [stack({ block, target })];
}
}
return [];
},
description: ({ block, target }) => `put block ${block} on ${target}`,
});
const allClearBlocks = (blocks: State['blocks']) => {
return Object.keys(blocks).filter((block) =>
isClear(blocks, block as Block),
) as Block[];
};
/**
* This method implements the following block-stacking algorithm [1]:
*
* - If there's a clear block x that can be moved to a place where it won't
* need to be moved again, then return a todo list that includes goals to
* move it there, followed by mgoal (to achieve the remaining goals).
* Otherwise, if there's a clear block x that needs to be moved out of the
* way to make another block movable, then return a todo list that includes
* goals to move x to the table, followed by mgoal.
* - Otherwise, no blocks need to be moved.
* [1] N. Gupta and D. S. Nau. On the complexity of blocks-world
* planning. Artificial Intelligence 56(2-3):223–254, 1992.
*
* Source: https://github.com/dananau/GTPyhop/blob/main/Examples/blocks_hgn/methods.py
*/
const move = Task.of<State>().from({
lens: '/blocks',
method: (blocks, { target }) => {
for (const b of allClearBlocks(blocks)) {
// The block is free and it can be moved to the final target (another block or the table)
if (isClear(blocks, target[b])) {
return [
// TODO: take doesn't really need a target. The grounding function might
// be able to infer if the target is needed depending on the operation?
take({ block: b, target: target[b] }),
put({ block: b, target: target[b] }),
];
}
}
// If we get here, no blocks can be moved to the final location so
// we move it to the table
for (const b of allClearBlocks(blocks)) {
// The block is free and it can be moved to the final target (another block or the table)
return [
take({ block: b, target: target[b] }),
take({ block: b, target: 'table' }),
];
}
// The method is not applicable here
return [];
},
description: `find a block that can be moved to the final location or to the table`,
});
const planner = Planner.from<State>({
tasks: [pickup, unstack, putdown, stack, take, put, move],
config: { trace: log },
});
const result = planner.findPlan(
{
blocks: { a: 'table', b: 'a', c: 'b' },
},
{ blocks: { a: 'b', b: 'c', c: 'table' } },
);
expect(stringify(result)).to.deep.equal(
plan()
.action('unstack block c')
.action('put down block c')
.action('unstack block b')
.action('stack block b on top of block c')
.action('pickup block a')
.action('stack block a on top of block b')
.end(),
);
});
it('solves parallel problems', () => {
type Counters = { [k: string]: number };
const byOne = Task.of<Counters>().from({
lens: '/:counter',
condition: (state, { target }) => state < target,
effect: (state) => ++state._,
description: ({ counter }) => `${counter} + 1`,
});
const multiIncrement = Task.from<Counters>({
condition: (state, ctx) =>
Object.keys(state).filter((k) => ctx.target[k] - state[k] > 0)
.length > 1,
method: (state, ctx) =>
Object.keys(state)
.filter((k) => ctx.target[k] - state[k] > 0)
.map((k) => byOne({ counter: k, target: ctx.target[k] })),
description: `increment counters`,
});
const planner = Planner.from({
tasks: [multiIncrement, byOne],
config: { trace: log },
});
const result = planner.findPlan({ a: 0, b: 0 }, { a: 3, b: 2 });
expect(stringify(result)).to.deep.equal(
plan()
.fork(branch('a + 1'), branch('b + 1'))
.fork(branch('a + 1'), branch('b + 1'))
.action('a + 1')
.end(),
);
});
it('solves parallel problems with methods', () => {
type Counters = { [k: string]: number };
const byOne = Task.of<Counters>().from({
lens: '/:counter',
condition: (state, { target }) => state < target,
effect: (state) => ++state._,
description: ({ counter }) => `${counter} + 1`,
});
const byTwo = Task.of<Counters>().from({
lens: '/:counter',
condition: (state, { target }) => target - state > 1,
method: (_, ctx) => [byOne(ctx), byOne(ctx)],
description: ({ counter }) => `increase '${counter}'`,
});
const multiIncrement = Task.from<Counters>({
condition: (counters, ctx) =>
Object.keys(counters).some((k) => ctx.target[k] - counters[k] > 1),
method: (counters, { target }) =>
Object.keys(counters)
.filter((k) => target[k] - counters[k] > 1)
.map((k) => byTwo({ counter: k, target: target[k] })),
description: `increment counters`,
});
const planner = Planner.from({
tasks: [multiIncrement, byTwo, byOne],
config: { trace: log },
});
const result = planner.findPlan({ a: 0, b: 0 }, { a: 3, b: 2 });
expect(stringify(result)).to.deep.equal(
plan()
.fork(branch('a + 1', 'a + 1'), branch('b + 1', 'b + 1'))
.action('a + 1')
.end(),
);
});
it('allows sequential expansion to be forced', () => {
type Counters = { [k: string]: number };
const byOne = Task.of<Counters>().from({
lens: '/:counter',
condition: (state, { target }) => state < target,
effect: (state) => ++state._,
description: ({ counter }) => `${counter} + 1`,
});
const byTwo = Task.of<Counters>().from({
lens: '/:counter',
condition: (state, { target }) => target - state > 1,
method: (_, ctx) => [byOne(ctx), byOne(ctx)],
description: ({ counter }) => `increase '${counter}'`,
});
const multiIncrement = Task.from<Counters>({
expansion: 'sequential',
condition: (counters, ctx) =>
Object.keys(counters).some((k) => ctx.target[k] - counters[k] > 1),
method: (counters, { target }) =>
Object.keys(counters)
.filter((k) => target[k] - counters[k] > 1)
.map((k) => byTwo({ counter: k, target: target[k] })),
description: `increment counters`,
});
const planner = Planner.from({
tasks: [multiIncrement, byTwo, byOne],
config: { trace: log },
});
const result = planner.findPlan({ a: 0, b: 0 }, { a: 3, b: 2 });
expect(stringify(result)).to.deep.equal(
plan()
.actions('a + 1', 'a + 1')
.actions('b + 1', 'b + 1')
.action('a + 1')
.end(),
);
});
it('Finds parallel plans with nested forks', () => {
type Counters = { [k: string]: number };
const byOne = Task.of<Counters>().from({
lens: '/:counter',
condition: (state, { target }) => state < target,
effect: (state) => ++state._,
description: ({ counter }) => `${counter}++`,
});
const byTwo = Task.of<Counters>().from({
lens: '/:counter',
condition: (state, { target }) => target - state > 1,
method: (_, ctx) => [byOne(ctx), byOne(ctx)],
description: ({ counter }) => `${counter} + 2`,
});
const multiIncrement = Task.from<Counters>({
condition: (counters, { target }) =>
Object.keys(counters).some((k) => target[k] - counters[k] > 1),
method: (counters, { target }) =>
Object.keys(counters)
.filter((k) => target[k] - counters[k] > 1)
.map((k) => byTwo({ counter: k, target: target[k] })),
description: `increment multiple`,
});
const chunker = Task.from<Counters>({
condition: (counters, ctx) =>
Object.keys(counters).some((k) => ctx.target[k] - counters[k] > 1),
method: (counters, { target }) => {
const toUpdate = Object.keys(counters).filter(
(k) => target[k] - counters[k] > 1,
);
const chunkSize = 2;
const tasks: Array<Instruction<Counters>> = [];
for (let i = 0; i < toUpdate.length; i += chunkSize) {
const chunk = toUpdate.slice(i, i + chunkSize);
tasks.push(
multiIncrement({
target: {
...counters,
...chunk.reduce((acc, k) => ({ ...acc, [k]: target[k] }), {}),
},
}),
);
}
return tasks;
},
description: 'chunk',
});
const planner = Planner.from({
tasks: [chunker, multiIncrement, byTwo, byOne],
config: { trace: log },
});
const result = planner.findPlan(
{ a: 0, b: 0, c: 0, d: 0 },
{ a: 3, b: 2, c: 2, d: 2 },
);
expect(stringify(result)).to.deep.equal(
plan()
.fork(
branch(fork(branch('a++', 'a++'), branch('b++', 'b++'))),
branch(fork(branch('c++', 'c++'), branch('d++', 'd++'))),
)
.action('a++')
.end(),
);
});
it('reverts to sequential execution if branches have conflicts', () => {
type Counters = { [k: string]: number };
const byOne = Task.of<Counters>().from({
lens: '/:counter',
condition: (state, { target }) => state < target,
effect: (state) => ++state._,
description: ({ counter }) => `${counter} + 1`,
});
const conflictingIncrement = Task.from<Counters>({
condition: (counters, { target }) =>
Object.keys(counters).filter((k) => target[k] - counters[k] > 1)
.length > 1,
method: (counters, { target }) =>
Object.keys(counters)
.filter((k) => target[k] - counters[k] > 1)
.flatMap((k) => [
// We create parallel steps to increase the same element of the state
// concurrently
byOne({ counter: k, target: target[k] }),
byOne({ counter: k, target: target[k] }),
]),
description: `increment counters`,
});
const planner = Planner.from({
tasks: [conflictingIncrement, byOne],
config: { trace: log },
});
const result = planner.findPlan({ a: 0, b: 0 }, { a: 3, b: 2 });
// The resulting plan is just the linear version because the parallel version
// will result in a conflict being detected
expect(stringify(result)).to.deep.equal(
plan()
.action('a + 1')
.action('a + 1')
.action('b + 1')
.action('b + 1')
.action('a + 1')
.end(),
);
});
it('limits maximum search depth', function () {
const dec = Task.of<number>().from({
// There is as bug here
condition: (state, { target }) => state < target,
effect: (state) => --state._,
description: '-1',
});
const inc = Task.of<number>().from({
condition: (state, { target }) => state < target,
// There is as bug here
effect: (state) => --state._,
description: '+1',
});
const inc2 = Task.of<number>().from({
condition: (state, { target }) => state < target,
// There is as bug here
effect: (state) => --state._,
description: '+1 bis',
});
const planner = Planner.from<number>({
tasks: [dec, inc, inc2],
config: { maxSearchDepth: 2 },
});
const result = planner.findPlan(0, 1);
expect(result.success).to.be.false;
expect(result.stats.maxDepth).to.equal(2);
});
it.skip('simple travel problem', () => {
// Alice needs to go to the park and may walk or take a taxi. Depending on the distance to the park and
// the available cash, some actions may be possible
expect(false);
});
});
it('limits maximum search depth while recursing methods', function () {
const inc = Task.of<number>().from({
condition: (state, { target }) => state < target,
// There is as bug here
method: (_, { target }): Instruction<number> => inc({ target }),
description: 'inc1',
});
const planner = Planner.from<number>({
tasks: [inc],
config: { maxSearchDepth: 5 },
});
const result = planner.findPlan(0, 1);
expect(result.success).to.be.false;
// Method recursion does not change stats, which is why the expected value
// is 0
expect(result.stats.maxDepth).to.equal(0);
});
it.skip('simple travel problem', () => {
// TODO: Alice needs to go to the park and may walk or take a taxi. Depending on the distance to the park and
// the available cash, some actions may be possible
expect(false);
});
});