Files
logic-puzzle/tool/analyze_puzzles.dart
T
2026-11-02 10:06:32 +01:00

365 lines
13 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'package:lumen/domain/puzzle.dart';
import 'package:lumen/domain/thinking.dart';
const _help = '''Estimate puzzle reasoning depth using the game's visible clues.
Usage: dart tool/analyze_puzzles.dart [options]
Default: analyse all levels in assets/campaign.json.
--campaign PATH Use another campaign file
--level N Analyse one campaign level (1-based)
--practice DIFFICULTY Generate easy, medium or hard practice
--seed INTEGER Practice seed (default: 1000001)
--daily YYYY-MM-DD Analyse the actual daily puzzle for this date
--input PATH Analyse one picture record or generic constraint JSON
--max-lookahead N Maximum nested assumptions, 0–3 (default: 2)
--node-limit N Per-puzzle search budget (default: 50000)
--json PATH Write machine-readable results; - prints JSON only
--markdown PATH Write a readable report; - prints Markdown
--trace Include explained, spoiler-containing solution rounds
--help Show this help
This measures a defined reasoning model, not a universal human minimum or time.
A deduction chain is not the same as keeping hypothetical moves in your head.
''';
typedef _Board = ({
String id,
String title,
int size,
int cells,
List<Constraint> constraints,
List<int> initial,
});
_Board _picture(Map<String, dynamic> data, String id) {
final picture = (data['picture'] as String).split('').map(int.parse).toList();
final size = math.sqrt(picture.length).toInt();
final puzzle = Puzzle(size, picture);
final clues = data['clues'] as String? ?? '';
for (final c in clues.split(',').where((c) => c.isNotEmpty)) {
puzzle.given[int.parse(c)] = true;
}
final areas = data['areas'] as String? ?? '';
var index = 0;
for (final area in areas.split(';').where((a) => a.isNotEmpty)) {
final v = area.split(',').map(int.parse).toList();
if (v.length != 4) {
throw const FormatException('Areas need top,left,height,width');
}
puzzle.regions.add(
Region(String.fromCharCode(65 + index++), v[0], v[1], v[2], v[3]),
);
}
return _fromPuzzle(puzzle, id, data['title'] as String? ?? id);
}
_Board _fromPuzzle(Puzzle p, String id, String title) => (
id: id,
title: title,
size: p.size,
cells: p.solution.length,
constraints: p.constraints,
initial: p.initial,
);
_Board _input(Map<String, dynamic> data) {
if (data.containsKey('picture')) return _picture(data, 'input');
final count = data['cellCount'] as int;
final size = data['size'] as int? ?? 0;
if (size < 0 || size > 0 && size * size != count) {
throw const FormatException(
'Optional size must describe a square cellCount',
);
}
return (
id: 'input',
title: data['title'] as String? ?? 'Custom constraints',
size: size,
cells: count,
initial: data['initial'] == null
? List.filled(count, -1)
: (data['initial'] as List).cast<int>(),
constraints: [
for (final c in data['constraints'] as List)
Constraint(
(c['cells'] as List).cast<int>(),
c['total'] as int,
c['name'] as String,
),
],
);
}
String _coordinate(int cell, int size) =>
size > 0 ? 'r${cell ~/ size + 1}c${cell % size + 1}' : 'cell $cell';
String _ahead(ThinkingReport report) =>
report.lookaheadDepth?.toString() ?? '?';
String _markdown(
List<({_Board board, ThinkingReport report})> results,
bool trace,
) {
final out = StringBuffer('''# Puzzle thinking-depth report
Model: direct clue totals, cancellation of shared cells in two clues, then bounded contradiction proofs. Every deduction wave reads an unchanged snapshot before writing its marks.
**Lookahead** counts the maximum simultaneous hypothetical assumptions used on this solver's path. **Rounds** count successive waves of deductions that can be written down. Neither is a measured human difficulty score, a time estimate, or a universal minimum. A question mark means the analysis did not establish a complete solution. Comparison steps can involve rows, columns or areas.
| Puzzle | Status | Lookahead | Rounds | Direct cells at start | Comparison steps | Smallest wave | Largest clue span |
| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |
''');
for (final item in results) {
final r = item.report;
out.writeln(
'| ${item.board.id}: ${item.board.title.replaceAll('|', '/')} | ${r.status.name} | ${_ahead(r)} | ${r.rounds.length} | ${r.initialDirectMoves} | ${r.comparisonSteps} | ${r.narrowestRound} | ${r.maxCellsCompared} |',
);
}
out.writeln(
'\nLargest clue span = unmarked cells in the clue(s) used for one deduction. Smallest wave includes the final cleanup; a value of one alone does not prove a hard bottleneck. Search budgets apply separately to each puzzle.\n',
);
for (final item in results) {
final r = item.report;
out.writeln('## ${item.board.id}: ${item.board.title}\n');
out.writeln('${r.message}\n');
out.writeln(
'Resolved ${r.resolvedCells}/${item.board.cells - r.givens} initially unmarked cells. Search nodes: ${r.searchNodes}. Assumption limit: ${r.maxLookahead}.\n',
);
if (!trace) continue;
for (var i = 0; i < r.rounds.length; i++) {
out.writeln('**Round ${i + 1} · ${r.rounds[i].newCells} new cells**\n');
for (final step in r.rounds[i].steps) {
final marks = step.marks.entries
.map(
(m) =>
'${_coordinate(m.key, item.board.size)}=${m.value == 1 ? 'lit' : 'dark'}',
)
.join(', ');
out.writeln('- ${step.rule.name}: ${step.explanation} → $marks');
if (step.proof != null) {
out.writeln(
' Contradiction evidence: `${jsonEncode(step.proof!.toJson())}`',
);
}
}
out.writeln();
}
}
return out.toString();
}
void _write(String path, String contents) {
final file = File(path);
file.parent.createSync(recursive: true);
file.writeAsStringSync(contents);
}
void main(List<String> args) {
try {
final options = <String, String>{};
var trace = false;
const names = {
'--campaign',
'--level',
'--practice',
'--seed',
'--daily',
'--input',
'--max-lookahead',
'--node-limit',
'--json',
'--markdown',
};
for (var i = 0; i < args.length; i++) {
if (args[i] == '--help') {
stdout.write(_help);
return;
}
if (args[i] == '--trace') {
trace = true;
continue;
}
if (!names.contains(args[i]) ||
i + 1 == args.length ||
args[i + 1].startsWith('--')) {
throw FormatException('Unknown option or missing value: ${args[i]}');
}
final name = args[i];
if (options.containsKey(name)) {
throw FormatException('Repeated option: $name');
}
options[name] = args[++i];
}
final sources = [
'--campaign',
'--practice',
'--daily',
'--input',
].where(options.containsKey).length;
if (sources > 1 ||
options.containsKey('--level') &&
(options.containsKey('--practice') ||
options.containsKey('--daily') ||
options.containsKey('--input'))) {
throw const FormatException(
'Choose one input source; --level applies only to a campaign',
);
}
if (options.containsKey('--seed') && !options.containsKey('--practice')) {
throw const FormatException('--seed requires --practice');
}
if (options['--json'] == '-' && options['--markdown'] == '-') {
throw const FormatException('Only one output format can use stdout');
}
final maxDepth = int.parse(options['--max-lookahead'] ?? '2');
final nodeLimit = int.parse(options['--node-limit'] ?? '50000');
if (maxDepth < 0 || maxDepth > 3 || nodeLimit < 1) {
throw const FormatException(
'Lookahead must be 0–3 and node limit positive',
);
}
if (options['--json'] != null &&
options['--markdown'] != null &&
File(options['--json']!).absolute.path ==
File(options['--markdown']!).absolute.path) {
throw const FormatException(
'JSON and Markdown need different output paths',
);
}
final boards = <_Board>[];
if (options['--input'] case final path?) {
boards.add(
_input(
jsonDecode(File(path).readAsStringSync()) as Map<String, dynamic>,
),
);
} else if (options['--practice'] case final value?) {
final difficulty = Difficulty.values
.where((d) => d.name == value.toLowerCase())
.firstOrNull;
if (difficulty == null) {
throw const FormatException(
'Practice difficulty must be easy, medium or hard',
);
}
final seed = BigInt.parse(options['--seed'] ?? '1000001');
boards.add(
_fromPuzzle(
Puzzle.generate(seed, difficulty),
'practice',
'${difficulty.label}, seed $seed',
),
);
} else if (options['--daily'] case final value?) {
final date = DateTime.parse(value);
if (!RegExp(r'^\d{4}-\d{2}-\d{2}$').hasMatch(value) ||
date.toIso8601String().substring(0, 10) != value) {
throw const FormatException('Use a valid YYYY-MM-DD date');
}
boards.add(
_fromPuzzle(
Puzzle.seeded(BigInt.from(epochDay(date)) * BigInt.from(7919)),
'daily',
value,
),
);
} else {
final data = jsonDecode(
File(options['--campaign'] ?? 'assets/campaign.json')
.readAsStringSync(),
) as Map;
final levels = data['levels'] as List;
if (levels.isEmpty) {
throw const FormatException('Campaign contains no puzzles');
}
final selected = options['--level'] == null
? null
: int.parse(options['--level']!);
if (selected != null && (selected < 1 || selected > levels.length)) {
throw FormatException('Level must be 1–${levels.length}');
}
for (var i = 0; i < levels.length; i++) {
if (selected == null || selected == i + 1) {
boards.add(_picture(levels[i] as Map<String, dynamic>, '${i + 1}'));
}
}
}
final results = [
for (final board in boards)
(
board: board,
report: ThinkingAnalyzer(board.cells, board.constraints).analyze(
board.initial,
maxLookahead: maxDepth,
nodeLimit: nodeLimit,
),
),
];
final json = const JsonEncoder.withIndent(' ').convert({
'model': 'visible-clue-reasoning-v1',
'interpretation': 'A reproducible solver-path estimate, not a validated human minimum or time. Deduction waves are not hypothetical lookahead. Indices are zero-based; marks use 0=dark and 1=lit.',
'maxLookahead': maxDepth,
'nodeLimitPerPuzzle': nodeLimit,
'puzzles': [
for (final item in results)
{
'id': item.board.id,
'title': item.board.title,
'size': item.board.size,
'constraints': [
for (final c in item.board.constraints)
{'name': c.name, 'cells': c.cells, 'total': c.total},
],
'initial': item.board.initial,
...item.report.toJson(),
},
],
});
final markdown = _markdown(results, trace);
if (options['--json'] case final path?) {
if (path != '-') _write(path, '$json\n');
}
if (options['--markdown'] case final path?) {
if (path != '-') _write(path, markdown);
}
if (options['--json'] == '-') {
stdout.writeln(json);
} else if (options['--markdown'] == '-') {
stdout.write(markdown);
} else {
stdout.writeln(
'Puzzle thinking depth · model estimate, not a human minimum\n',
);
stdout.writeln(
'ID Lookahead Rounds Start Compare Min wave Clue span Status / title',
);
for (final item in results) {
final r = item.report;
stdout.writeln(
'${item.board.id.padRight(3)} ${_ahead(r).padLeft(9)} ${r.rounds.length.toString().padLeft(7)} ${r.initialDirectMoves.toString().padLeft(6)} ${r.comparisonSteps.toString().padLeft(8)} ${r.narrowestRound.toString().padLeft(9)} ${r.maxCellsCompared.toString().padLeft(10)} ${r.status.name}: ${item.board.title}',
);
}
stdout.writeln(
'\nLookahead 0 = deductions can be written down; no hypothetical branching.',
);
stdout.writeln(
'? = no complete depth established; inspect status/message.',
);
if (trace) stdout.write('\n$markdown');
}
if (results.any((r) => r.report.status != ThinkingStatus.solved)) {
exitCode = 1;
}
} on Object catch (error) {
stderr.writeln(
'Cannot analyse puzzles: $error\nUse --help for input options.',
);
exitCode = 2;
}
}