forked from nick/genetic-soylent
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathGeneticSoylent.js
254 lines (222 loc) · 10.9 KB
/
GeneticSoylent.js
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
/**
* GeneticSoylent should be initialized with a target nutrient profile and a list of ingredients.
*/
var GeneticSoylent = function(opts) {
opts = opts || {};
this.populationSize = opts.populationSize || 100;
this.mutationProbability = opts.mutationProbability || 0.7;
this.mutationMultiplier = opts.mutationMultiplier || 0.1;
this.deathRate = opts.deathRate || 0.3;
this.ingredients = opts.ingredients;
this.targetNutrients = opts.targetNutrients;
this.ratios = this.defaultRatios();
this.reset();
};
/**
* Randomly generate new recipes. The number of recipes to generate is defined by populationSize
*/
GeneticSoylent.prototype.reset = function() {
this.currentGeneration = 0;
this.recipes = [];
this.recipes.push(new Recipe(this, _.map(this.ingredients, function() { return 1; })));
for (var i = 1; i < this.populationSize; i++){
this.recipes.push(new Recipe(this));
}
};
GeneticSoylent.prototype.nextGeneration = function() {
// Throw out the worst performing recipes. The % thrown out is defined by the deathRate variable.
var recipesToKeep = Math.floor(this.recipes.length * (1 - this.deathRate));
this.recipes = this.recipes.slice(0, recipesToKeep);
// Pick two random recipes from the remaining list and 'mate' them, to produce a child recipe.
for (var popIndex = 0; this.recipes.length < this.populationSize; popIndex++) {
var parentOne = this.recipes[Math.floor(Math.random() * recipesToKeep)];
var parentTwo = this.recipes[Math.floor(Math.random() * recipesToKeep)];
var childRecipe = parentOne.createChildWith(parentTwo);
this.recipes.push(childRecipe);
}
this.sortRecipes();
this.currentGeneration++;
this.render();
if (this.autoGenerate) {
var self = this;
setTimeout(function() {
self.nextGeneration();
}, 100);
}
};
/**
* Sort the recipes from best to worst
*/
GeneticSoylent.prototype.sortRecipes = function(a, b) {
this.recipes.sort(function(a, b) {
if (b.completenessScore < a.completenessScore) {
return -1;
}
else if (a.completenessScore < b.completenessScore) {
return 1;
}
else {
return 0;
}
});
};
GeneticSoylent.prototype.defaultRatios = function() {
return {
'Calcium:Phosphorus': {min: 1, max: 2.5, numerator: "calcium", denominator: "phosphorus", unitCorrection: 1, importanceFactor: 1},
'Calcium:Magnesium': {min: 1, max: 2, numerator: "calcium", denominator: "magnesium", unitCorrection: 1000, importanceFactor: 1},
'Potassium:Sodium': {min: 2, max: 999, numerator: "potassium", denominator: "sodium", unitCorrection: 1, importanceFactor: 1},
'Iron:Copper': {min: 10, max: 17, numerator: "iron", denominator: "copper", unitCorrection: 1, importanceFactor: 1},
'Zinc:Copper': {min: 10, max: 15, numerator: "zinc", denominator: "copper", unitCorrection: 1, importanceFactor: 1},
'Iron:Zinc': {min: 0.01, max: 2, numerator: "iron", denominator: "zinc", unitCorrection: 1, importanceFactor: 1},
'Omega-6:Omega-3': {min: 1, max: 2.3, numerator: "omega_6", denominator: "omega_3", unitCorrection: 1, importanceFactor: 1},
};
};
GeneticSoylent.prototype.render = function() {
var ingredientHtml = _.template([
'<table class="table table-condensed">',
'<tr>',
'<th>Ingredient</th>',
'<th class="text-center">Min</th>',
'<th class="text-center">Amount</th>',
'<th class="text-center">Max</th>',
// '<% _.each(nutrientKeys, function(nutrient, index) { %>',
// '<th class="text-center"><%= nutrient %></th>',
// '<% }); %>',
'</tr>',
'<% _.each(ingredients, function(ingredient, idx) { %>',
'<tr>',
'<td class="text-left"><%= ingredient.name %></td>',
'<td class="text-center"><input name="<%= idx %>_._minAmount" class="ingredientInput" value="<%= ingredient["minAmount"] %>"></input></td>',
// amounts[idx] is rounded to the nearest whole since we assume that inputs are
// given in the smallest measurable units
'<td class="text-center"><%= Math.round(amounts[idx]) %></td>',
'<td class="text-center"><input name="<%= idx %>_._maxAmount" class="ingredientInput" value="<%= ingredient["maxAmount"] %>"></input></td>',
// '<% _.each(nutrientKeys, function(nutrient, index) { %>',
// '<td class="text-center"><%= (ingredient[nutrient] * Math.round(amounts[idx])).toFixed(2) %></td>',
// '<% }); %>',
'</tr>',
'<% }); %>',
'</table>',
'<h3 align="center">Deviation: <%= -completenessScore.toFixed(1) %></h3>',
'<p align="center">Lower deviations are better.</p>',
].join(''));
var nutrientHtml = _.template([
'<table class="table table-condensed">',
'<tr>',
'<th class="text-left">Nutrient</th>',
'<th class="text-center">Min</th>',
'<th class="text-center">Amount</th>',
'<th class="text-center">Max</th>',
'<th class="text-center">% Deviation</th>',
'<th class="text-center">Priority</th>',
'</tr>',
'<% _.each(nutrientKeys, function(nutrient, index) { %>',
'<% if(total[nutrient] != undefined){ %>',
'<% var classCompleteness = ""; %>',
// '<% console.log(nutrient + ": " + classCompleteness) %>',
'<% if(!nutrientCompleteness[nutrient]) { classCompleteness = "success"; } else { classCompleteness = "danger"; } %>',
'<tr class="<%= classCompleteness %>">',
'<th class="text-left"><%= nutrient %></th>',
'<td class="text-center"><input name="<%= nutrient %>_._min" class="nutrientInput" value="<%= targetProfile[nutrient].min %>"></input></td>',
'<% var tooltip = "" %>',
'<% _.each(ingredients, function(ingredient, idx) { %>',
'<% tooltip += (ingredient[nutrient] * Math.round(amounts[idx])).toFixed(2) + "\t" + ingredient["name"] + "\\r" %>',
'<% }); %>',
'<td class="text-center" title="<%= tooltip %>"><%= total[nutrient].toFixed(2) %></td>',
'<td class="text-center"><input name="<%= nutrient %>_._max" class="nutrientInput" value="<%= targetProfile[nutrient].max %>"></input></td>',
'<td class="text-center"><%= nutrientCompleteness[nutrient].toFixed(1) %>%</td>',
'<td class="text-center"><input name="<%= nutrient %>_._importanceFactor" class="nutrientInput" value="<%= targetProfile[nutrient].importanceFactor %>"></input>',
'</tr>',
'<% }; %>',
'<% }); %>',
//ratioCompleteness
'<% if(typeof ratioKeys != "undefined"){ %>',
'<% _.each(ratioKeys, function(theRatio, index) { %>',
'<% var classCompleteness = ""; %>',
// '<% console.log(nutrient + ": " + classCompleteness) %>',
'<% if(!ratioCompleteness[theRatio]) { classCompleteness = "success"; } else { classCompleteness = "danger"; } %>',
'<tr class="<%= classCompleteness %>">',
'<th class="text-left"><%= theRatio %></th>',
'<td class="text-center"><input name="<%= theRatio %>_._min" class="ratioInput" value="<%= targetRatios[theRatio].min %>"></input></td>',
'<td class="text-center"><%= ratioAmounts[theRatio].toFixed(2) %></td>',
'<td class="text-center"><input name="<%= theRatio %>_._max" class="ratioInput" value="<%= targetRatios[theRatio].max %>"></input></td>',
'<td class="text-center"><%= ratioCompleteness[theRatio].toFixed(1) %>%</td>',
'<td class="text-center"><input name="<%= theRatio %>_._importanceFactor" class="ratioInput" value="<%= targetRatios[theRatio].importanceFactor %>"></input>',
'</tr>',
'<% }); %>',
'<% }; %>',
'</table>'
].join(''));
$('#ingredientTable').html(ingredientHtml({
total: this.recipes[0].nutrientTotals,
amounts: this.recipes[0].ingredientAmounts,
ingredients: this.ingredients,
targetProfile: this.targetNutrients,
completenessScore: this.recipes[0].completenessScore,
nutrientCompleteness: this.recipes[0].nutrientCompleteness,
nutrientKeys: _.keys(this.targetNutrients)
}));
// specify the nutrient keys we want in the second column
var nutrientTableKeysForFirstColumn = [
"cost",
"calories",
"carbs",
"protein",
"fat",
"omega_3",
"omega_6",
"fiber",
"vitamin_a",
"vitamin_b6",
"vitamin_b12",
"vitamin_c",
"vitamin_d",
"vitamin_e",
"vitamin_k"
];
// put all other nutrient keys into the third column
var nutrientTableKeysForSecondColumn = _.keys(this.targetNutrients);
nutrientTableKeysForSecondColumn = $.grep(nutrientTableKeysForSecondColumn, function(value){
return $.inArray(value, nutrientTableKeysForFirstColumn) + 1;
}, true);
$('#nutrientTable').html(nutrientHtml({
total: this.recipes[0].nutrientTotals,
amounts: this.recipes[0].ingredientAmounts,
ingredients: this.ingredients,
targetProfile: this.targetNutrients,
nutrientCompleteness: this.recipes[0].nutrientCompleteness,
//nutrientKeys: _.keys(this.targetNutrients)
nutrientKeys: nutrientTableKeysForFirstColumn,
ratioKeys: _.keys(this.recipes[0].ratioCompleteness),
ratioCompleteness: this.recipes[0].ratioCompleteness,
ratioAmounts: this.recipes[0].ratioAmounts,
targetRatios: this.ratios,
}));
$('#nutrientTableRemainder').html(nutrientHtml({
total: this.recipes[0].nutrientTotals,
amounts: this.recipes[0].ingredientAmounts,
ingredients: this.ingredients,
targetProfile: this.targetNutrients,
nutrientCompleteness: this.recipes[0].nutrientCompleteness,
nutrientKeys: nutrientTableKeysForSecondColumn.sort()
}));
$('.nutrientInput').change(function(){
// split the name of the function by separator "_._"
// keyInfo[0] is the nutrient name
// keyInfo[1] is the name of the value for that nutrient
var keyInfo = this.name.split("_._");
testGeneticSoylent.targetNutrients[keyInfo[0]][keyInfo[1]] = this.value;
});
$('.ratioInput').change(function(){
// split the name of the function by separator "_._"
// keyInfo[0] is the nutrient name
// keyInfo[1] is the name of the value for that nutrient
var keyInfo = this.name.split("_._");
testGeneticSoylent.ratios[keyInfo[0]][keyInfo[1]] = this.value;
});
$('.ingredientInput').change(function(){
var keyInfo = this.name.split("_._");
testGeneticSoylent.ingredients[keyInfo[0]][keyInfo[1]] = +this.value;
});
$('.generation').val(this.currentGeneration);
};