-
-
Notifications
You must be signed in to change notification settings - Fork 326
/
SudokuSampleController.cs
378 lines (290 loc) · 13.7 KB
/
SudokuSampleController.cs
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
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using GeneticSharp.Extensions;
using Gtk;
namespace GeneticSharp.Runner.GtkApp.Samples
{
/// <summary>
/// This enumeration represents the types of Genetics to represent a Sudoku solutions. There are 2 families: those with genes for Sudoku cells, and those with genes for permutations of a [1..9] row.
/// </summary>
public enum SudokuChromosomeType
{
Cells,
CellsWithoutMask,
RowsPermutations,
RandomRowsPermutations,
RowsWithoutMask,
}
/// <summary>
/// Sample controller for solving Sudokus.
/// Includes 4 default games, and allows for loading additional ones from a file, supporting most file formats.
/// Includes 2 different types of chromosome. One trivial with 81 genes each cell digit, and one with 9 genes for row permutations taking into account the original mask
/// </summary>
[DisplayName("Sudoku")]
public class SudokuSampleController : SampleControllerBase
{
public SudokuSampleController()
{
// Super easy - Population 250 - generation 16 - 0.2s
_sudokuList.Add(SudokuBoard.Parse("9.2..54.31...63.255.84.7.6..263.9..1.57.1.29..9.67.53.24.53.6..7.52..3.4.8..4195."));
//Easy - Population 5000 - generation 24 - 10s
_sudokuList.Add(SudokuBoard.Parse("..48...1767.9.....5.8.3...43..74.1...69...78...1.69..51...8.3.6.....6.9124...15.."));
//Medium - Population 100000 - generation 30 - 10mn
_sudokuList.Add(SudokuBoard.Parse("..6.......8..542...4..9..7...79..3......8.4..6.....1..2.3.67981...5...4.478319562"));
// Hard - Population 300000 - generation 37 - 1h30mn
_sudokuList.Add(SudokuBoard.Parse("....9.4.8.....2.7..1.7....32.4..156...........952..7.19....5.1..3.4.....1.2.7...."));
}
private string _ChromosomeType = nameof(SudokuChromosomeType.RowsPermutations); // The selected type of chromosome
private int _nbPermutations = 2; //The number of genes per permutation for random permutations
private int _nbSudokus = 5; //The number of Sudokus to generate from random permutations
private HBox _nbPermsHBox;
private bool _multipleChromosome = false; // Do we evolve several sudokus/sub-chromosomes per individual solution
private int _nbChromosomes = 2; //Nb of sudokus per individual if multiple
private HBox _nbChromosomesHBox;
private IList<SudokuBoard> _sudokuList = new List<SudokuBoard>();
private int _sudokuIndex;
private SudokuBoard GetTargetSudoku()
{
return _sudokuList[_sudokuIndex];
}
public override IChromosome CreateChromosome()
{
return CreateChromosome(_multipleChromosome, _nbChromosomes);
}
private IChromosome CreateChromosome(bool multi, int nbChromosomes = 5)
{
if (!multi)
{
switch (_ChromosomeType)
{
case nameof(SudokuChromosomeType.RandomRowsPermutations):
return new SudokuRandomPermutationsChromosome(GetTargetSudoku(), _nbPermutations, _nbSudokus);
case nameof(SudokuChromosomeType.RowsPermutations):
return new SudokuPermutationsChromosome(GetTargetSudoku());
case nameof(SudokuChromosomeType.RowsWithoutMask):
return new SudokuPermutationsChromosome();
case nameof(SudokuChromosomeType.Cells):
return new SudokuCellsChromosome(GetTargetSudoku());
case nameof(SudokuChromosomeType.CellsWithoutMask):
return new SudokuCellsChromosome();
}
}
else
{
return new MultipleChromosome(i => CreateChromosome(false), nbChromosomes);
}
return null;
}
public override Widget CreateConfigWidget()
{
var container = new VBox();
var fileHBox = new HBox();
container.Add(fileHBox);
// Sudoku index.
var indexHBox = new HBox();
fileHBox.Add(indexHBox);
var indexLabel = new Label { Text = "Sudoku index" };
indexHBox.Add(indexLabel);
var indexButton = new SpinButton(1, _sudokuList.Count, 1) {Value = 1};
indexButton.ValueChanged += delegate
{
_sudokuIndex = (int)indexButton.Value - 1;
OnReconfigured();
};
indexHBox.Add(indexButton);
// File support
var selectImageButton = new Button { Label = "Load sudoku(s) file" };
selectImageButton.Clicked += delegate
{
Gtk.FileChooserDialog filechooser =
new Gtk.FileChooserDialog(
"Select the sudoku to use",
Context.GtkWindow,
FileChooserAction.Open,
"Cancel",
ResponseType.Cancel,
"Open",
ResponseType.Accept);
if (filechooser.Run() == (int)ResponseType.Accept)
{
_sudokuList = SudokuBoard.ParseFile(filechooser.Filename);
indexButton.SetRange(1, _sudokuList.Count);
}
filechooser.Destroy();
OnReconfigured();
};
fileHBox.Add(selectImageButton);
var helpImageButton = new Button { Label = "?" };
helpImageButton.Clicked += delegate
{
var msg = new MessageDialog(
Context.GtkWindow,
DialogFlags.Modal,
MessageType.Info,
ButtonsType.Ok,
"Accepted formats represent Sudokus on one or several lines," +
"\n with characters '.', '-', or 'X' for empty cells and digits otherwise." +
"\n Lines starting with other characters are ignored such as '#' for comments on the common sdk format.");
msg.Run();
msg.Destroy();
};
fileHBox.Add(helpImageButton);
// Genetics selector.
var geneticsHBox = new HBox();
geneticsHBox.Spacing += 2;
var geneticsLabel = new Label { Text = "Genetics" };
geneticsHBox.Add(geneticsLabel);
var chromosomeTypes = new string[] {
nameof(SudokuChromosomeType.RowsPermutations)
,nameof(SudokuChromosomeType.Cells)
,nameof(SudokuChromosomeType.RandomRowsPermutations)
,nameof(SudokuChromosomeType.RowsWithoutMask)
,nameof(SudokuChromosomeType.CellsWithoutMask)
};
_nbPermsHBox = new HBox
{
Visible = _ChromosomeType == nameof(SudokuChromosomeType.RandomRowsPermutations)
};
var nbPermsLabel = new Label { Text = "Nb Permutations" };
_nbPermsHBox.Add(nbPermsLabel);
var nbPermsButton = new SpinButton(1, 1000, 1);
_nbPermsHBox.Add(nbPermsButton);
nbPermsButton.Value = _nbPermutations;
nbPermsButton.ValueChanged += delegate
{
_nbPermutations = (int)nbPermsButton.Value;
OnReconfigured();
};
var nbSudokusLabel = new Label { Text = "Nb Sudokus" };
_nbPermsHBox.Add(nbSudokusLabel);
var nbSudokusButton = new SpinButton(1, 1000, 1);
_nbPermsHBox.Add(nbSudokusButton);
nbSudokusButton.Value = _nbSudokus;
nbSudokusButton.ValueChanged += delegate
{
_nbSudokus = (int)nbSudokusButton.Value;
OnReconfigured();
};
var selectorCombo = new ComboBox(chromosomeTypes) { Active = 0 };
selectorCombo.Changed += delegate
{
_ChromosomeType = selectorCombo.ActiveText;
_nbPermsHBox.Visible = _ChromosomeType == nameof(SudokuChromosomeType.RandomRowsPermutations);
OnReconfigured();
};
geneticsHBox.Add(selectorCombo);
container.Add(geneticsHBox);
container.Add(_nbPermsHBox);
//Multi check
var multiHBox = new HBox();
var multiCheck = new CheckButton("Multi-Solutions") {Active = _multipleChromosome};
_nbChromosomesHBox = new HBox();
_nbChromosomesHBox.Spacing += 2;
_nbChromosomesHBox.Visible = _multipleChromosome;
var nbChromosomesLabel = new Label { Text = "Nb Chrom." };
_nbChromosomesHBox.Add(nbChromosomesLabel);
var nbChromosomesButton = new SpinButton(1, 1000, 1);
_nbChromosomesHBox.Add(nbChromosomesButton);
nbChromosomesButton.Value = _nbChromosomes;
nbChromosomesButton.ValueChanged += delegate
{
_nbChromosomes = (int)nbChromosomesButton.Value;
OnReconfigured();
};
multiCheck.Toggled += delegate
{
_multipleChromosome = multiCheck.Active;
_nbChromosomesHBox.Visible = _multipleChromosome;
OnReconfigured();
};
multiHBox.Add(multiCheck);
multiHBox.Add(_nbChromosomesHBox);
container.Add(multiHBox);
return container;
}
public override ICrossover CreateCrossover()
{
return new UniformCrossover();
}
public override IFitness CreateFitness()
{
return CreateFitness(_multipleChromosome);
}
private IFitness CreateFitness(bool multi)
{
if (multi)
{
return new MultipleFitness(CreateFitness(false));
}
if (_ChromosomeType == nameof(SudokuChromosomeType.RandomRowsPermutations))
{
return new SudokuFitness(GetTargetSudoku());
}
return new SudokuFitness(GetTargetSudoku());
}
public override IMutation CreateMutation()
{
return new UniformMutation();
}
public override ISelection CreateSelection()
{
return new EliteSelection();
}
public override void Draw()
{
var buffer = Context.Buffer;
var layout = Context.Layout;
var population = Context.Population;
SudokuBoard sudokuBoardToDraw = null;
if (population != null)
{
if ((population.BestChromosome is ISudokuChromosome bestChromosome))
{
if (population.CurrentGeneration != null)
{
var stats = population.CurrentGeneration.Chromosomes.GroupBy(c => c.Fitness).OrderByDescending(g => g.Key).Select(g => new { Fitness = g.Key, Count = g.Count(), First = ((ISudokuChromosome)g.First()).GetSudokus().First(), Last = ((ISudokuChromosome)g.Last()).GetSudokus().First() }).ToList();
Context.WriteText($"Fitness,Count:({stats[0].Fitness},{stats[0].Count})...({stats[stats.Count / 3].Fitness},{stats[stats.Count / 3].Count})...({stats[stats.Count * 2 / 3].Fitness},{stats[stats.Count * 2 / 3].Count})...({stats[stats.Count - 1].Fitness},{stats[stats.Count - 1].Count})");
Context.WriteText($"Top: [{string.Join(",", stats[0].First.Cells.Take(9).Select(i => i.ToString()).ToArray())}] [{string.Join(",", stats[0].Last.Cells.Take(9).Select(i => i.ToString()).ToArray())}]");
if (stats.Count > 1)
{
Context.WriteText($"Next: [{string.Join(",", stats[1].First.Cells.Take(9).Select(i => i.ToString()).ToArray())}] [{string.Join(",", stats[1].Last.Cells.Take(9).Select(i => i.ToString()).ToArray())}]");
}
}
sudokuBoardToDraw = bestChromosome.GetSudokus().First();
}
else
{
if (population.BestChromosome is MultipleChromosome multiChromosome)
{
var orderedSubChromosomes = multiChromosome.Chromosomes.OrderByDescending(c => c.Fitness).ToList();
bestChromosome = (ISudokuChromosome)orderedSubChromosomes.First();
var worstChromosome = (ISudokuChromosome)orderedSubChromosomes.Last();
sudokuBoardToDraw = bestChromosome.GetSudokus().First();
Context.WriteText($"Best Chromosome Best Sub-Fitness: {((IChromosome)bestChromosome).Fitness}");
Context.WriteText($"Best Chromosome Worst Sub-Fitness:: {((IChromosome)worstChromosome).Fitness}");
}
}
}
else
{
sudokuBoardToDraw = GetTargetSudoku();
}
if (sudokuBoardToDraw != null)
{
layout.SetMarkup($"<span color='black'>{sudokuBoardToDraw}</span>");
buffer.DrawLayout(Context.GC, 50, 120, layout);
}
}
public override void Reset()
{
// Quick hack to force visibility not taken into account at creation (GTK#/MainWidow bug?)
_nbPermsHBox.Visible = _ChromosomeType == nameof(SudokuChromosomeType.RandomRowsPermutations);
_nbChromosomesHBox.Visible = _multipleChromosome;
}
public override void Update()
{
//throw new NotImplementedException();
}
}
}