forked from janmichalik/CriticalPathMethod
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpm.js
More file actions
503 lines (451 loc) · 18.2 KB
/
cpm.js
File metadata and controls
503 lines (451 loc) · 18.2 KB
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// estructura de la tarea
function Task() {
this.id = '';
this.task_length = 0;
this.predecessor = [];
this.earliest_start = 0;
this.earliest_finish = 0;
this.latest_start = 0;
this.latest_finish = 0;
this.total_float = 0;
this.num_predecessors = 0;
this.horizontal = 0;
this.vertical = 0;
}
// definiciones de variables globales
var result = "", result2 = "",
num_tasks = 0, max = 0, min = 0,
task_data, max_horizontal = 0, critical_path = [],
context = document.getElementById("cpm"),
canvas = context.getContext("2d");
// Add this function to calculate horizontal positions
function calculateHorizontalPositions() {
for (var i = 0; i < num_tasks; i++) {
if (task_data[i].predecessor.length === 0 || task_data[i].predecessor[0] == '0') {
task_data[i].horizontal = 0;
} else {
let maxPredHorizontal = -1;
for (let predId of task_data[i].predecessor) {
const predTask = task_data.find(task => task.id === predId);
if (predTask && predTask.horizontal > maxPredHorizontal) {
maxPredHorizontal = predTask.horizontal;
}
}
task_data[i].horizontal = maxPredHorizontal + 1;
}
if (task_data[i].horizontal > max_horizontal) {
max_horizontal = task_data[i].horizontal;
}
}
}
// Modify the algorithm function
function algorithm() {
result = "";
result2 = "";
calculateAllTimes();
calculateHorizontalPositions();
// Generate results
for (var i = 0; i < num_tasks; i++) {
var set = new Set(task_data[i].predecessor);
var myArr = Array.from(set);
myArr = myArr.sort();
result += `<table><tr><td>ID de la Tarea</td><td><b>${task_data[i].id}</b></tr>
<tr><td>Duración de la Tarea</td><td><b>${task_data[i].task_length}</b></tr>
<tr><td>Predecesores</td><td><b>${myArr.join(", ")}</b></tr>
<tr><td>Inicio Más Temprano</td><td><b>${task_data[i].earliest_start}</b></tr>
<tr><td>Fin Más Temprano</td><td><b>${task_data[i].earliest_finish}</b></tr>
<tr><td>Inicio Más Tardío</td><td><b>${task_data[i].latest_start}</b></tr>
<tr><td>Fin Más Tardío</td><td><b>${task_data[i].latest_finish}</b></tr>
<tr><td>Holgura Total</td><td><b>${task_data[i].total_float}</b></td></tr></table>`;
}
var a = 0;
for (var i = 0; i < num_tasks; i++) {
if (task_data[i].total_float == 0) {
critical_path[a] = task_data[i].id;
a++;
}
}
// Sort the critical path based on earliest start times
critical_path.sort((a, b) => {
const taskA = task_data.find(task => task.id === a);
const taskB = task_data.find(task => task.id === b);
return taskA.earliest_start - taskB.earliest_start;
});
// Update result2 to reflect the sorted critical path
result2 = critical_path.join(" ");
document.getElementById("result").innerHTML = `<div class="box">Resultados:<br><br>${result}<hr>
<center><font size=4>Camino Crítico: <b>${result2}</b></font>.</center>
<br>
<button onclick="setTimeout(generatePDF, 100)">Generar PDF</button></div>`;
document.getElementById("canvas").className += 'box';
// Adjust canvas size
canvas.canvas.height = (num_tasks + 1) * 90;
canvas.canvas.width = (max_horizontal + 2) * 90;
drawTitle();
// Draw tasks in columns
for (var j = 0; j <= max_horizontal; j++) {
var verticalPosition = 0;
for (var i = 0; i < num_tasks; i++) {
if (task_data[i].horizontal == j) {
drawTask(j * 3 + 1, verticalPosition * 3 + 1, task_data[i].id, i);
task_data[i].vertical = verticalPosition;
verticalPosition++;
}
}
}
// Draw lines between tasks
for (var i = 1; i < num_tasks; i++) {
for (var j = 0; j < task_data[i].num_predecessors; j++) {
var o = 0, p = 0, x = 0;
for (var k = 0; k < i; k++) {
if (task_data[i].predecessor[j] == task_data[k].id) {
o = task_data[k].horizontal;
p = task_data[k].vertical;
}
}
drawLine(task_data[i].horizontal * 3 + 2, task_data[i].vertical * 3 + 3, o * 3 + 4, p * 3 + 3 - 0.25, x);
}
}
// Draw critical path
var o = 0, p = 0, r = 0, s = 0;
for (var i = 0; i < critical_path.length; i++) {
for (var j = 0; j < num_tasks; j++) {
if (critical_path[i] == task_data[j].id) {
o = task_data[j].horizontal;
p = task_data[j].vertical;
}
}
for (var j = 0; j < num_tasks; j++) {
if (critical_path[i + 1] == task_data[j].id) {
r = task_data[j].horizontal;
s = task_data[j].vertical;
}
}
if (i < critical_path.length - 1) {
drawLine(r * 3 + 2, s * 3 + 3 + 0.25, o * 3 + 4, p * 3 + 3 + 0.25, 1);
}
}
}
// Función para actualizar los tiempos de las tareas cuando cambian las dependencias
function updateTaskTimes(index) {
const taskLength = parseInt(document.getElementById(`task_length_${index}`).value) || 0;
const numPredecessors = parseInt(document.getElementById(`num_predecessors_${index}`).value) || 0;
const predecessors = [];
for (var j = 0; j < numPredecessors; j++) {
const predValue = parseInt(document.getElementById(`predecessors_${index}`).children[j].value);
if (predValue && predValue <= num_tasks) predecessors.push(predValue.toString());
}
task_data[index].id = (index + 1).toString();
task_data[index].task_length = taskLength;
task_data[index].num_predecessors = predecessors.length;
task_data[index].predecessor = predecessors;
calculateAllTimes();
}
// Función para calcular los tiempos de inicio y fin más tempranos basados en las dependencias
function calculateEarliestTimes() {
// First pass: Initialize all tasks
for (var j = 0; j < num_tasks; j++) {
task_data[j].earliest_start = 0;
task_data[j].earliest_finish = parseInt(task_data[j].task_length);
}
// Second pass: Update based on predecessors
let changed = true;
while (changed) {
changed = false;
for (var j = 0; j < num_tasks; j++) {
if (task_data[j].predecessor.length === 0 || task_data[j].predecessor[0] == '0') continue;
let max = 0;
for (var i = 0; i < task_data[j].num_predecessors; i++) {
const predId = task_data[j].predecessor[i];
const predTask = task_data.find(task => task.id === predId);
if (predTask && max < predTask.earliest_finish) {
max = predTask.earliest_finish;
}
}
if (task_data[j].earliest_start !== max) {
task_data[j].earliest_start = max;
task_data[j].earliest_finish = max + parseInt(task_data[j].task_length);
changed = true;
}
}
}
}
// Función para calcular los tiempos de inicio y fin más tardíos basados en las dependencias
function calculateLatestTimes() {
let max = Math.max(...task_data.map(task => task.earliest_finish));
// Initialize all tasks with the latest possible finish time
for (var j = 0; j < num_tasks; j++) {
task_data[j].latest_finish = max;
task_data[j].latest_start = max - parseInt(task_data[j].task_length);
}
// Update based on successors
let changed = true;
while (changed) {
changed = false;
for (var i = num_tasks - 1; i >= 0; i--) {
let min = max;
for (var j = 0; j < num_tasks; j++) {
if (task_data[j].predecessor.includes(task_data[i].id)) {
if (task_data[j].latest_start < min) {
min = task_data[j].latest_start;
}
}
}
if (task_data[i].latest_finish !== min) {
task_data[i].latest_finish = min;
task_data[i].latest_start = min - parseInt(task_data[i].task_length);
changed = true;
}
}
}
}
// Función para calcular la holgura total para cada tarea
function calculateTotalFloat() {
for (var i = 0; i < num_tasks; i++) {
task_data[i].total_float = task_data[i].latest_start - task_data[i].earliest_start;
}
}
// Función para calcular todos los tiempos y actualizar la interfaz de usuario
function calculateAllTimes() {
calculateEarliestTimes();
calculateLatestTimes();
calculateTotalFloat();
updateUI();
}
// Función para actualizar la interfaz de usuario con los últimos tiempos de las tareas
function updateUI() {
// Only update UI if task cards are present
if (document.getElementById("task_cards").children.length > 0) {
for (var i = 0; i < num_tasks; i++) {
document.getElementById(`earliest_start_${i}`).value = task_data[i].earliest_start;
document.getElementById(`earliest_finish_${i}`).value = task_data[i].earliest_finish;
document.getElementById(`latest_start_${i}`).value = task_data[i].latest_start;
document.getElementById(`latest_finish_${i}`).value = task_data[i].latest_finish;
document.getElementById(`total_float_${i}`).value = task_data[i].total_float;
}
}
}
// Función para enviar los datos de las tareas y generar resultados
function submitTaskData() {
// Asegurar que todos los datos de las tareas estén actualizados
for (var i = 0; i < num_tasks; i++) {
updateTaskTimes(i);
}
// Calcular todos los tiempos una última vez
calculateAllTimes();
// Generar resultados
algorithm();
// Ocultar las tarjetas de entrada de tareas
document.getElementById("task_cards_container").style.display = 'none';
// Mostrar los resultados y el canvas
document.getElementById("result").style.display = 'block';
document.getElementById("canvas").style.display = 'block';
}
// ingresar datos
function insert_data() {
num_tasks = document.getElementById("num_tasks").value;
if (num_tasks < 1) {
alert("¡Debes ingresar al menos una tarea!");
window.location.href = 'index.html';
}
task_data = [];
for (var i = 0; i < num_tasks; i++) {
task_data[i] = new Task();
}
document.getElementById("task_cards_container").style.display = 'block';
document.getElementById("result").style.display = 'none';
document.getElementById("canvas").style.display = 'none';
var taskCards = document.getElementById("task_cards");
taskCards.innerHTML = '';
for (var i = 0; i < num_tasks; i++) {
var card = document.createElement('div');
card.className = 'task-card';
card.innerHTML = `
<h3>Tarea ${i + 1}</h3>
<label>Duración: <input type="number" id="task_length_${i}" min="1" onchange="updateTaskTimes(${i})"></label><br>
<label>Número de Predecesores: <input type="number" id="num_predecessors_${i}" min="0" onchange="updateTaskTimes(${i})"></label><br>
<div id="predecessors_${i}"></div>
<label>Inicio Más Temprano: <input type="number" id="earliest_start_${i}" min="0" readonly></label><br>
<label>Fin Más Temprano: <input type="number" id="earliest_finish_${i}" min="0" readonly></label><br>
<label>Inicio Más Tardío: <input type="number" id="latest_start_${i}" min="0" readonly></label><br>
<label>Fin Más Tardío: <input type="number" id="latest_finish_${i}" min="0" readonly></label><br>
<label>Holgura Total: <input type="number" id="total_float_${i}" min="0" readonly></label><br>
`;
taskCards.appendChild(card);
document.getElementById(`task_length_${i}`).addEventListener('change', function() {
updateTaskTimes(parseInt(this.id.split('_')[2]));
});
document.getElementById(`num_predecessors_${i}`).addEventListener('change', function() {
var index = parseInt(this.id.split('_')[2]);
var numPredecessors = parseInt(this.value);
var predecessorsDiv = document.getElementById(`predecessors_${index}`);
predecessorsDiv.innerHTML = '';
for (var j = 0; j < numPredecessors; j++) {
var predInput = document.createElement('input');
predInput.type = 'number';
predInput.min = '1';
predInput.max = num_tasks.toString();
predInput.placeholder = `Predecesor ${j + 1}`;
predInput.addEventListener('change', function() {
updateTaskTimes(index);
});
predecessorsDiv.appendChild(predInput);
}
updateTaskTimes(index);
});
}
}
// datos aleatorios
function random() {
num_tasks = document.getElementById("num_tasks").value;
if (num_tasks < 1) {
alert("¡Debes ingresar al menos una tarea!");
window.location.href = 'index.html';
}
task_data = [];
for (var i = 0; i < num_tasks; i++) {
task_data[i] = new Task();
}
for (var i = 0; i < num_tasks; i++) {
task_data[i].id = (i + 1).toString();
task_data[i].task_length = Math.floor(Math.random() * 50) + 1; // Ensure task length is at least 1
if (i > 0) {
task_data[i].num_predecessors = Math.floor(Math.random() * i) + 1;
} else {
task_data[i].num_predecessors = 0;
}
if (task_data[i].num_predecessors > 4) task_data[i].num_predecessors = 2;
if (task_data[i].num_predecessors == 0) {
task_data[i].predecessor = [];
} else {
var random_value = 0;
for (var j = 0; j < task_data[i].num_predecessors; j++) {
random_value = Math.floor(Math.random() * i);
for (var k = 0; k < j; k++) {
if (task_data[random_value].id == task_data[i].predecessor[k]) {
random_value = Math.floor(Math.random() * i);
k = 0;
} else {
k++;
}
}
task_data[i].predecessor[j] = task_data[random_value].id;
}
}
}
// Calculate all times and generate results
calculateAllTimes();
algorithm();
// Hide the task cards container
document.getElementById("task_cards_container").style.display = 'none';
// Show the results and canvas
document.getElementById("result").style.display = 'block';
document.getElementById("canvas").style.display = 'block';
}
// dibujar gráfico
function drawTitle() {
canvas.beginPath();
canvas.font = "14px Consolas";
canvas.fillText("Gráfico:", 5, 15);
canvas.stroke();
}
function drawTask(x, y, name, i) {
x = x * 30 + 30;
y = y * 30 + 30;
canvas.beginPath();
canvas.lineWidth = "2";
canvas.strokeStyle = "black";
canvas.rect(x, y, 60, 60);
canvas.moveTo(x + 30, y);
canvas.lineTo(x + 30, y + 60);
canvas.moveTo(x, y + 30);
canvas.lineTo(x + 60, y + 30);
canvas.font = "14px Consolas";
canvas.fillText(name, x, y - 5);
canvas.fillText(task_data[i].earliest_start, x + 3, y + 20);
canvas.fillText(task_data[i].earliest_finish, x + 33, y + 20);
canvas.fillText(task_data[i].latest_start, x + 33, y + 50);
canvas.fillText(task_data[i].latest_finish, x + 3, y + 50);
canvas.stroke();
}
function drawLine(x, y, m, n, c) {
canvas.beginPath();
canvas.lineWidth = "5";
if (c == 1) {
var color = "rgba(0, 0, 255, 0.8)";
} else {
var color = "rgba(60, 188, 141, 0.5)"
}
x = x * 30;
y = y * 30;
m = m * 30;
n = n * 30;
canvas.strokeStyle = color;
canvas.moveTo(x, y);
canvas.lineTo(m, n);
canvas.stroke();
}
function generatePDF() {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
// Add title
doc.setFontSize(16);
doc.text("Resultados del Método de la Ruta Crítica", 20, 20);
// Add task results
doc.setFontSize(12);
let yPosition = 40;
for (let i = 0; i < num_tasks; i++) {
doc.text(`Tarea ${task_data[i].id}:`, 20, yPosition);
yPosition += 10;
doc.text(`Duración: ${task_data[i].task_length}`, 30, yPosition);
yPosition += 10;
doc.text(`Predecesores: ${task_data[i].predecessor.join(", ")}`, 30, yPosition);
yPosition += 10;
doc.text(`Inicio Más Temprano: ${task_data[i].earliest_start}`, 30, yPosition);
yPosition += 10;
doc.text(`Fin Más Temprano: ${task_data[i].earliest_finish}`, 30, yPosition);
yPosition += 10;
doc.text(`Inicio Más Tardío: ${task_data[i].latest_start}`, 30, yPosition);
yPosition += 10;
doc.text(`Fin Más Tardío: ${task_data[i].latest_finish}`, 30, yPosition);
yPosition += 10;
doc.text(`Holgura Total: ${task_data[i].total_float}`, 30, yPosition);
yPosition += 20;
// Add a new page if we're running out of space
if (yPosition > 250) {
doc.addPage();
yPosition = 20;
}
}
// Add critical path
doc.text(`Camino Crítico: ${critical_path.join(" -> ")}`, 20, yPosition);
yPosition += 20;
// Add graph
const canvas = document.getElementById('cpm');
const scaledCanvas = scaleCanvas(canvas, 0.80); // Increased scale to 75%
const imgData = scaledCanvas.toDataURL('image/jpeg', 0.9); // Increased quality to 90%
const imgProps = doc.getImageProperties(imgData);
const pdfWidth = doc.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
// Check if we need a new page for the graph
if (yPosition + pdfHeight > doc.internal.pageSize.getHeight()) {
doc.addPage();
yPosition = 20;
}
doc.addImage(imgData, 'JPEG', 10, yPosition, pdfWidth - 20, pdfHeight);
// Save the PDF
doc.save("CPM_Results.pdf");
}
function scaleCanvas(canvas, scale) {
const scaledCanvas = document.createElement('canvas');
scaledCanvas.width = canvas.width * scale;
scaledCanvas.height = canvas.height * scale;
const ctx = scaledCanvas.getContext('2d');
// Fill the background with white
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, scaledCanvas.width, scaledCanvas.height);
// Draw the original canvas content onto the scaled canvas
ctx.drawImage(canvas, 0, 0, scaledCanvas.width, scaledCanvas.height);
return scaledCanvas;
}
delete Task;