-
Notifications
You must be signed in to change notification settings - Fork 1
/
Model.cs
109 lines (96 loc) · 3.33 KB
/
Model.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicMau.ProceduralNameGenerator
{
/// <summary>
/// <seealso cref="https://github.com/Tw1ddle/MarkovNameGenerator/blob/master/src/markov/namegen/Model.hx"/>
/// </summary>
class Model
{
private int order;
private double smoothing;
private List<char> alphabet;
private Dictionary<string, List<char>> observations;
private Dictionary<string, List<double>> chains;
public Model(IEnumerable<string> trainingData, int order, double smoothing, List<char> alphabet)
{
this.order = order;
this.smoothing = smoothing;
this.alphabet = alphabet;
observations = new Dictionary<string, List<char>>();
Retrain(trainingData);
}
public char Generate(string context, Random rnd)
{
List<double> chain;
if (chains.TryGetValue(context, out chain))
return alphabet[SelectIndex(chain, rnd)];
return '\0';
}
public void Retrain(IEnumerable<string> trainingData)
{
// mustn't we clear _observations here? Not in original source
Train(trainingData);
BuildChains();
}
private void Train(IEnumerable<string> trainingData)
{
foreach (var d in trainingData)
{
string data = new string('#', order) + d + '#';
for (int i = 0; i < data.Length - order; i++)
{
string key = data.Substring(i, order);
List<char> value;
if (!observations.TryGetValue(key, out value))
{
value = new List<char>();
observations[key] = value;
}
value.Add(data[i + order]);
}
}
}
private void BuildChains()
{
chains = new Dictionary<string, List<double>>();
foreach (string context in observations.Keys)
{
foreach (char prediction in alphabet)
{
List<double> chain;
if (!chains.TryGetValue(context, out chain))
{
chain = new List<double>();
chains[context] = chain;
}
int count = 0;
List<char> observation;
if (observations.TryGetValue(context, out observation))
count = observation.Count(c => c == prediction);
chain.Add(smoothing + count);
}
}
}
private int SelectIndex(List<double> chain, Random rnd)
{
var totals = new List<double>();
double accumulator = 0f;
foreach (var weight in chain)
{
accumulator += weight;
totals.Add(accumulator);
}
var rand = rnd.NextDouble() * accumulator;
for (int i = 0; i < totals.Count; i++)
{
if (rand < totals[i])
return i;
}
return 0;
}
}
}