-
Notifications
You must be signed in to change notification settings - Fork 0
/
renderer.js
445 lines (372 loc) · 15.7 KB
/
renderer.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
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
const { ipcRenderer } = require('electron');
const GLPK = require('glpk.js');
const glpk = GLPK();
let nutritionData = [];
let inputsFilled = {
'age': false,
'weight': false,
'burns': false,
'days-after-trauma': false, // Use 'days-after-trauma'
'temperature': false,
'height': false,
'energy-intake': false
};
let caloricNeed;
let proteinNeed;
let filteredFormulas = [];
const noValidationNeeded = new Set(['illness', 'gender']);
ipcRenderer.on('nutrition-data', (event, data) => {
try {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(data, "application/xml");
const illnessesContainer = document.getElementById("illnesses-container");
// Clear previous options
illnessesContainer.innerHTML = ''; // Clear the illness drop-down
const illnessSet = new Set(); // Using a Set to avoid duplicate illnesses
const nutrients = xmlDoc.getElementsByTagName("nutrition");
if (nutrients.length === 0) {
console.error('No nutrition data found.');
return;
} 0
Array.from(nutrients).forEach(nutrition => {
const name = nutrition.getElementsByTagName("name")[0].textContent;
const caloricDensity = parseFloat(nutrition.getElementsByTagName("caloricDensity")[0].textContent); // kcal per 100 g
const protein = parseFloat(nutrition.getElementsByTagName("protein")[0].textContent); // g per 100 ml
const indication = nutrition.getElementsByTagName("indication")[0].textContent;
const contraindication = nutrition.getElementsByTagName("contraindication")[0].textContent;
const nutritionForm = nutrition.getElementsByTagName("form")[0].textContent; // Changed to nutritionForm
const src = nutrition.getElementsByTagName("src")[0].textContent;
// Get packaging volumes
const volumes = Array.from(nutrition.getElementsByTagName("volume")).map(vol => parseInt(vol.textContent));
// Store nutrition data
nutritionData.push({
name,
caloricDensity,
protein,
indication,
contraindication,
packaging: volumes,
nutritionForm,
src
});
// Add indications to the Set for unique illness options
if (indication !== "none") {
illnessSet.add(indication);
}
});
// Populate illness checkboxes
illnessSet.forEach(indication => {
const checkboxWrapper = document.createElement("div");
checkboxWrapper.className = "checkbox-wrapper"; // Optional: for styling
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = indication;
checkbox.name = "illnesses";
checkbox.value = indication;
const label = document.createElement("label");
label.htmlFor = indication;
label.textContent = indication;
checkboxWrapper.appendChild(checkbox);
checkboxWrapper.appendChild(label);
illnessesContainer.appendChild(checkboxWrapper);
});
addCheckboxListeners();
} catch (error) {
console.error('Error parsing XML:', error);
}
});
document.querySelectorAll('input, select').forEach(element => {
element.addEventListener('input', handleInputChange);
element.addEventListener('change', handleInputChange);
});
function addCheckboxListeners() {
const illnessCheckboxes = document.querySelectorAll('input[name="illnesses"]');
// Attach event listeners to each checkbox
illnessCheckboxes.forEach(checkbox => {
checkbox.addEventListener('change', () => {
handleInputChange();
});
});
}
function handleInputChange() {
const id = this.id;
if (id) {
console.log(`Input changed: ${id}`); // Log input change
if (validateField(id)) {
inputsFilled[id] = true;
} else {
inputsFilled[id] = false;
}
}
let areAllInputsFilled = Object.values(inputsFilled).every(value => value === true);
if (areAllInputsFilled) {
calculate();
}
}
function validateField(id) {
if (noValidationNeeded.has(id)) {
return true; // No validation needed for drop-downs
} else {
const min = getMinValue(id);
const max = getMaxValue(id);
return validateNumber(id, min, max) !== null;
}
}
function validateNumber(id, min, max) {
const inputElement = document.getElementById(id);
const errorSpan = document.getElementById(`${id}-error`);
if (!inputElement || !errorSpan) {
console.error(`Element with id "${id}" or error span "${id}-error" not found.`);
return null;
}
const value = parseFloat(inputElement.value);
if (isNaN(value) || value < min || value > max) {
errorSpan.textContent = `Value must be between ${min} and ${max}`;
emptyNutritionTable();
return null;
} else {
errorSpan.textContent = '';
return value;
}
}
function getMinValue(id) {
switch (id) {
case 'age': return 0;
case 'weight': return 1;
case 'burns': return 1;
case 'days-after-trauma': return 0;
case 'temperature': return 24;
case 'height': return 50;
case 'energy-intake': return 500;
}
}
function getMaxValue(id) {
switch (id) {
case 'age': return 120;
case 'weight': return 300;
case 'burns': return 100;
case 'days-after-trauma': return Infinity;
case 'temperature': return 46;
case 'height': return 300;
case 'energy-intake': return 5000;
}
}
function calculate() {
const age = parseFloat(document.getElementById('age').value);
const weight = parseFloat(document.getElementById('weight').value);
const burns = parseFloat(document.getElementById('burns').value);
const daysAfterTrauma = parseFloat(document.getElementById('days-after-trauma').value);
const temperature = parseFloat(document.getElementById('temperature').value);
const gender = document.getElementById('gender').value;
const height = parseFloat(document.getElementById('height').value);
const energyIntake = parseFloat(document.getElementById('energy-intake').value);
const errorSpan = document.getElementById(`nutrition-table-error`);
errorSpan.textContent = '';
const bmr = calculateBMR(gender, weight, height, age);
document.getElementById('bmr-output').textContent = Math.round(bmr);
caloricNeed = calculateCalories(burns, energyIntake, bmr, temperature, daysAfterTrauma);
document.getElementById('caloric-output').textContent = Math.round(caloricNeed);
proteinNeed = calculateProtein(weight, daysAfterTrauma);
document.getElementById('protein-output').textContent = Math.round(proteinNeed);
filterNutritionFormulas(daysAfterTrauma);
if (!calculateNutritionVolumes(weight)) {
filteredFormulas.push(nutritionData.find(nutrition => nutrition.name === 'Nutridrink'));
if (!calculateNutritionVolumes(weight)) {
filteredFormulas.pop();
filteredFormulas.push(nutritionData.find(nutrition => nutrition.name === 'Protifar'));
if (!calculateNutritionVolumes(weight)) {
filteredFormulas.pop();
filteredFormulas.push(nutritionData.find(nutrition => nutrition.name === 'Nutrison'));
if (!calculateNutritionVolumes(weight)) {
filteredFormulas.push(nutritionData.find(nutrition => nutrition.name === 'Protifar'));
filteredFormulas.push(nutritionData.find(nutrition => nutrition.name === 'Nutridrink'));
if (!calculateNutritionVolumes(weight, true)) {
if (!calculateNutritionVolumes(weight, true, true)) {
emptyNutritionTable();
errorSpan.textContent = `Calculation failed. Take a screenshot and send it to the developer.`;
}
}
}
}
}
}
}
function calculateCalories(burns, energyIntake, bmr, temperature, daysAfterTrauma) {
// following Toronto formula for major burns
return -4343 + (10.5 * burns) + (0.23 * energyIntake) + (0.84 * bmr) + (114 * temperature) - (4.5 * daysAfterTrauma);
}
function calculateBMR(gender, weight, height, age) {
// BMR - Basal Metabolic Rate aka Harris-Benedict
if (gender === 'male') {
return 66.5 + (13.75 * weight) + (5.003 * height) - (6.75 * age);
} else {
return 655.1 + (9.563 * weight) + (1.850 * height) - (4.676 * age);
}
}
function calculateProtein(weight, daysAfterTrauma) {
if (daysAfterTrauma <= 15) {
return weight * 2;
} else {
return weight * 1.5;
}
}
function filterNutritionFormulas(daysAfterTrauma) {
const selectedIllnesses = getSelectedIllnesses();
filteredFormulas = [nutritionData.find(nutrition => nutrition.name === "Nutrison Protein Intense")];
if (daysAfterTrauma <= 15) {
filteredFormulas.push(nutritionData.find(nutrition => nutrition.name === "Glutamine+"));
}
selectedIllnesses.forEach(illness => {
let nutritionName = getNutritionNameByIllness(illness);
if (nutritionName) {
filteredFormulas.push(nutritionData.find(nutrition => nutrition.name === nutritionName));
}
});
}
function getSelectedIllnesses() {
let selectedIllnesses = [];
document.querySelectorAll('input[name="illnesses"]:checked').forEach(checkbox => {
selectedIllnesses.push(checkbox.value);
});
return selectedIllnesses;
}
function getNutritionNameByIllness(illness) {
switch (illness) {
case 'diabetes':
return 'Nutrison Advanced Diason';
case 'constipation':
return 'Nutrison Multi Fibre';
case 'swelling':
return 'Nutrison Energy Multi Fibre';
case 'liver failure':
return 'Nutricomp Hepa';
default:
return null;
}
}
function populateNutritionTableWithResults(results) {
const tableBody = emptyNutritionTable(); // Clear existing rows
let totalCalories = 0;
let totalProtein = 0;
let totalLiquidQuantity = 0;
let totalPowderQuantity = 0;
results.forEach(result => {
if (result.volume > 0) {
const row = document.createElement('tr');
// Nutrition name
const nameCell = document.createElement('td');
nameCell.textContent = result.nutrition;
row.appendChild(nameCell);
// Required volume
const volumeCell = document.createElement('td');
volumeCell.textContent = Math.round(result.volume) + ' ' + result.units;
row.appendChild(volumeCell);
// Provided calories
const caloriesCell = document.createElement('td');
caloriesCell.textContent = Math.round(result.calories) + ' kcal';
row.appendChild(caloriesCell);
// Provided protein
const proteinCell = document.createElement('td');
proteinCell.textContent = Math.round(result.protein) + ' g';
row.appendChild(proteinCell);
// Append row to table
tableBody.appendChild(row);
// Accumulate totals
totalCalories += Math.round(result.calories);
totalProtein += Math.round(result.protein);
if (result.nutritionForm === 'powder') {
totalPowderQuantity += Math.round(result.volume);
} else {
totalLiquidQuantity += Math.round(result.volume);
}
}
});
// Insert totals into the footer row
document.getElementById('totalCalories').textContent = totalCalories + ' kcal';
document.getElementById('totalProtein').textContent = totalProtein + ' g';
document.getElementById('totalQuantity').innerHTML = totalLiquidQuantity + ' ml' + ((totalPowderQuantity > 0) ? '<br>+<br>' + totalPowderQuantity + ' g' : '');
}
function emptyNutritionTable() {
const tableBody = document.querySelector('#nutrition-table tbody');
tableBody.innerHTML = ''; // Clear existing rows
document.getElementById('totalCalories').textContent = '';
document.getElementById('totalProtein').textContent = '';
document.getElementById('totalQuantity').textContent = '';
return tableBody;
}
function calculateNutritionVolumes(weight, ignoreSomeLimits = false, ignoreAllLimits = false) {
const lpProblem = {
name: 'Nutrition Optimization',
objective: {
direction: glpk.GLP_MIN,
name: 'minimize_volume',
vars: filteredFormulas.map((nutrition, index) => ({
name: `x${index}`,
coef: 1
}))
},
subjectTo: [
{
name: 'caloric_constraint',
vars: filteredFormulas.map((nutrition, index) => ({
name: `x${index}`,
coef: nutrition.caloricDensity / 100 // kcal/ml
})),
bnds: { type: glpk.GLP_DB, lb: 0.9 * caloricNeed, ub: 1.1 * caloricNeed }
},
{
name: "protein_constraint",
vars: filteredFormulas.map((nutrition, index) => ({
name: `x${index}`,
coef: nutrition.protein / 100 // grams/ml
})),
bnds: { type: glpk.GLP_DB, lb: 0.9 * proteinNeed, ub: proteinNeed}
}
],
bounds: filteredFormulas.map((nutrition, index) => ({
name: `x${index}`,
type: glpk.GLP_DB,
lb: (nutrition.nutritionForm === 'liquid') ? (((ignoreSomeLimits && (nutrition.indication == 'none')) || ignoreAllLimits) ? 0 : Math.min(...nutrition.packaging) / 2) : 0,
ub: (nutrition.nutritionForm === 'powder') ? 2.5 * 6 : ((nutrition.name === 'Nutridrink') ? 600 : Infinity)
}))
};
console.log("Filtered nutrition formulas for optimization:", filteredFormulas);
console.log("lpProblem", lpProblem);
const options = {
msglev: glpk.GLP_MSG_ERR,
presol: true
};
const result = glpk.solve(lpProblem, options);
console.log(result);
if (result.result.status === glpk.GLP_OPT) {
console.log("Optimal solution found.");
} else {
if (result.result.status === glpk.GLP_FEAS) {
console.log("Feasible solution found, but it might not be optimal.");
} else if (result.result.status === glpk.GLP_INFEAS) {
console.log("The problem is infeasible.");
} else if (result.result.status === glpk.GLP_NOFEAS) {
console.log("No feasible solution exists.");
} else if (result.result.status === glpk.GLP_UNBND) {
console.log("The solution is unbounded.");
} else if (result.result.status === glpk.GLP_UNDEF) {
console.log("The solution is undefined.");
}
return false;
}
const volumes = Object.keys(result.result.vars).map((key, index) => {
const variable = result.result.vars[key]; // Access the variable by key
return {
nutrition: filteredFormulas[index].name,
volume: variable, // variable.value is likely just `variable`
calories: variable * filteredFormulas[index].caloricDensity / 100,
protein: variable * filteredFormulas[index].protein / 100,
units: (filteredFormulas[index].nutritionForm === 'powder') ? 'g' : 'ml',
nutritionForm: filteredFormulas[index].nutritionForm
};
});
console.log(volumes);
// Display the result in the UI
populateNutritionTableWithResults(volumes);
return true;
}