-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerador-datos.js
More file actions
428 lines (349 loc) · 15.1 KB
/
generador-datos.js
File metadata and controls
428 lines (349 loc) · 15.1 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
// ========================================
// GENERADOR DE BASE DE DATOS SIMULADA
// ========================================
class GeneradorDatos {
constructor() {
this.datosGenerados = null;
this.configuracion = {
tamanoMuestra: 100,
pruebas: [],
sociodemograficos: []
};
}
// ========================================
// RECOLECCIÓN DE CONFIGURACIÓN
// ========================================
recolectarConfiguracion() {
// Tamaño muestral
const tamano = parseInt(document.getElementById('tamanoMuestra').value);
if (isNaN(tamano) || tamano < 2) {
throw new Error('El tamaño muestral debe ser al menos 2');
}
this.configuracion.tamanoMuestra = tamano;
// Pruebas aplicadas
this.configuracion.pruebas = this.recolectarPruebas();
if (this.configuracion.pruebas.length === 0) {
throw new Error('Debe agregar al menos una prueba');
}
// Datos sociodemográficos
this.configuracion.sociodemograficos = this.recolectarSociodemograficos();
if (this.configuracion.sociodemograficos.length === 0) {
throw new Error('Debe agregar al menos un dato sociodemográfico');
}
return this.configuracion;
}
recolectarPruebas() {
const pruebas = [];
const filas = document.querySelectorAll('#bodyPruebas .fila-prueba');
filas.forEach((fila, index) => {
const inputs = fila.querySelectorAll('input');
const nombre = inputs[0].value.trim();
const numItems = parseInt(inputs[1].value);
const media = parseFloat(inputs[2].value);
const desviacion = parseFloat(inputs[3].value);
const minimo = parseFloat(inputs[4].value);
const maximo = parseFloat(inputs[5].value);
if (nombre && !isNaN(numItems) && !isNaN(media) && !isNaN(desviacion)) {
if (numItems < 1) {
throw new Error(`Prueba "${nombre}": El número de ítems debe ser al menos 1`);
}
if (desviacion <= 0) {
throw new Error(`Prueba "${nombre}": La desviación estándar debe ser mayor a 0`);
}
// Validar rango si se especifica
if (!isNaN(minimo) && !isNaN(maximo)) {
if (minimo >= maximo) {
throw new Error(`Prueba "${nombre}": El mínimo debe ser menor que el máximo`);
}
}
pruebas.push({
nombre: nombre,
nombreCorto: this.generarNombreCorto(nombre),
numItems: numItems,
media: media,
desviacion: desviacion,
minimo: !isNaN(minimo) ? minimo : null,
maximo: !isNaN(maximo) ? maximo : null
});
}
});
return pruebas;
}
recolectarSociodemograficos() {
const socio = [];
const filas = document.querySelectorAll('#bodySocio .fila-socio');
filas.forEach((fila, index) => {
const inputs = fila.querySelectorAll('input');
const categoria = inputs[0].value.trim();
const promedio = parseFloat(inputs[1].value);
const desviacion = parseFloat(inputs[2].value);
const minimo = parseFloat(inputs[3].value);
const maximo = parseFloat(inputs[4].value);
const decimales = parseInt(inputs[5].value);
if (categoria && !isNaN(promedio) && !isNaN(desviacion)) {
if (desviacion <= 0) {
throw new Error(`Categoría "${categoria}": La desviación estándar debe ser mayor a 0`);
}
// Validar rango si se especifica
if (!isNaN(minimo) && !isNaN(maximo)) {
if (minimo >= maximo) {
throw new Error(`Categoría "${categoria}": El mínimo debe ser menor que el máximo`);
}
}
// Validar número de decimales
let numDecimales = 2; // Por defecto
if (!isNaN(decimales)) {
if (decimales < 0 || decimales > 4) {
throw new Error(`Categoría "${categoria}": Los decimales deben estar entre 0 y 4`);
}
numDecimales = decimales;
}
socio.push({
categoria: categoria,
categoriaCorta: this.generarNombreCorto(categoria),
promedio: promedio,
desviacion: desviacion,
minimo: !isNaN(minimo) ? minimo : null,
maximo: !isNaN(maximo) ? maximo : null,
decimales: numDecimales
});
}
});
return socio;
}
generarNombreCorto(nombre) {
// Genera un nombre corto a partir del nombre completo
// Toma las iniciales y números
let corto = nombre
.replace(/[^a-zA-Z0-9\s]/g, '') // Eliminar caracteres especiales
.split(/\s+/) // Separar por espacios
.map(palabra => palabra.charAt(0).toUpperCase()) // Primera letra
.join('');
return corto.substring(0, 10); // Máximo 10 caracteres
}
// ========================================
// GENERACIÓN DE DATOS ALEATORIOS
// ========================================
generarBaseDatos() {
const n = this.configuracion.tamanoMuestra;
const datos = [];
// Generar datos para cada participante
for (let i = 0; i < n; i++) {
const participante = { ID: i + 1 };
// Generar datos sociodemográficos
this.configuracion.sociodemograficos.forEach(socio => {
let valor = this.generarValorNormal(
socio.promedio,
socio.desviacion
);
// Aplicar límites si están definidos
if (socio.minimo !== null && socio.maximo !== null) {
valor = Math.max(socio.minimo, Math.min(socio.maximo, valor));
}
// Redondear según número de decimales especificado
const factor = Math.pow(10, socio.decimales);
participante[socio.categoriaCorta] = Math.round(valor * factor) / factor;
});
// Generar datos de cada prueba
this.configuracion.pruebas.forEach(prueba => {
const puntajes = this.generarPuntajesPrueba(
prueba.numItems,
prueba.media,
prueba.desviacion,
prueba.minimo,
prueba.maximo
);
// Agregar cada ítem
puntajes.items.forEach((puntaje, idx) => {
const nombreColumna = `${prueba.nombreCorto}${idx + 1}`;
participante[nombreColumna] = puntaje;
});
// Agregar total
participante[`Total_${prueba.nombreCorto}`] = puntajes.total;
});
datos.push(participante);
}
this.datosGenerados = datos;
return datos;
}
generarPuntajesPrueba(numItems, mediaPorItem, desviacionPorItem, minItem = null, maxItem = null) {
// IMPORTANTE: mediaPorItem y desviacionPorItem son los valores PROMEDIO de cada ítem
// NO son el total de la prueba
// Establecer límites por defecto si no se especifican
if (minItem === null) minItem = 1;
if (maxItem === null) maxItem = 7;
const items = [];
// Generar cada ítem de forma independiente con distribución normal
// Cada ítem tiene su propia media y desviación
for (let i = 0; i < numItems; i++) {
// Generar valor usando distribución normal
// La media es directamente la media por ítem (no dividir entre numItems)
let valor = this.generarValorNormal(mediaPorItem, desviacionPorItem);
// Aplicar límites del rango
valor = Math.max(minItem, Math.min(maxItem, valor));
// Redondear al entero más cercano
valor = Math.round(valor);
items.push(valor);
}
// Calcular el total sumando todos los ítems
const totalReal = items.reduce((a, b) => a + b, 0);
return {
items: items,
total: totalReal
};
}
generarValorNormal(media, desviacion) {
// Método Box-Muller para generar valores con distribución normal
let u1 = Math.random();
let u2 = Math.random();
// Evitar log(0)
while (u1 === 0) u1 = Math.random();
const z0 = Math.sqrt(-2.0 * Math.log(u1)) * Math.cos(2.0 * Math.PI * u2);
const valor = media + desviacion * z0;
return valor; // NO redondear aquí, se redondeará después según el contexto
}
// autor: Joel pasapera
// ========================================
// EXPORTACIÓN A CSV
// ========================================
exportarCSV() {
if (!this.datosGenerados || this.datosGenerados.length === 0) {
throw new Error('No hay datos generados para exportar');
}
// Obtener encabezados
const encabezados = Object.keys(this.datosGenerados[0]);
// Crear contenido CSV
let csv = encabezados.join(',') + '\n';
this.datosGenerados.forEach(fila => {
const valores = encabezados.map(encabezado => {
let valor = fila[encabezado];
// Escapar valores que contengan comas
if (typeof valor === 'string' && valor.includes(',')) {
valor = `"${valor}"`;
}
return valor;
});
csv += valores.join(',') + '\n';
});
return csv;
}
descargarCSV(nombreArchivo = 'base_datos_simulada.csv') {
const csv = this.exportarCSV();
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', nombreArchivo);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
// ========================================
// UTILIDADES
// ========================================
obtenerDatosGenerados() {
return this.datosGenerados;
}
obtenerConfiguracion() {
return this.configuracion;
}
limpiarDatos() {
this.datosGenerados = null;
this.configuracion = {
tamanoMuestra: 100,
pruebas: [],
sociodemograficos: []
};
}
// ========================================
// VALIDACIONES
// ========================================
validarConfiguracion() {
const errores = [];
const advertencias = [];
// Validar tamaño muestral
if (this.configuracion.tamanoMuestra < 30) {
advertencias.push('Tamaño muestral < 30: Los análisis estadísticos pueden tener bajo poder');
}
if (this.configuracion.tamanoMuestra > 10000) {
advertencias.push('Tamaño muestral muy grande: Puede ser poco realista');
}
// Validar pruebas
this.configuracion.pruebas.forEach(prueba => {
// Validar desviación estándar razonable
const rangoEsperado = prueba.numItems * 5; // Suposición de escala Likert
if (prueba.desviacion > rangoEsperado / 2) {
advertencias.push(
`Prueba "${prueba.nombre}": Desviación estándar muy alta (${prueba.desviacion}) para ${prueba.numItems} ítems`
);
}
// Validar que la media sea positiva
if (prueba.media < 0) {
errores.push(`Prueba "${prueba.nombre}": La media no puede ser negativa`);
}
});
// Validar sociodemográficos
this.configuracion.sociodemograficos.forEach(socio => {
// Validar desviación razonable
if (socio.desviacion > Math.abs(socio.promedio) * 2) {
advertencias.push(
`Variable "${socio.categoria}": Desviación estándar muy alta (${socio.desviacion}) comparada con la media (${socio.promedio})`
);
}
// Validar coherencia de límites con la media
if (socio.minimo !== null && socio.maximo !== null) {
if (socio.promedio < socio.minimo || socio.promedio > socio.maximo) {
advertencias.push(
`Variable "${socio.categoria}": La media (${socio.promedio}) está fuera del rango [${socio.minimo}, ${socio.maximo}]`
);
}
// Validar que el rango sea razonable para la desviación
const rango = socio.maximo - socio.minimo;
if (socio.desviacion > rango / 2) {
advertencias.push(
`Variable "${socio.categoria}": La desviación estándar (${socio.desviacion}) es muy alta para el rango [${socio.minimo}, ${socio.maximo}]`
);
}
}
});
return { errores, advertencias };
}
// ========================================
// ESTADÍSTICAS DESCRIPTIVAS RÁPIDAS
// ========================================
calcularEstadisticas(columna) {
if (!this.datosGenerados) return null;
const valores = this.datosGenerados
.map(fila => fila[columna])
.filter(v => v !== null && v !== undefined && !isNaN(v));
if (valores.length === 0) return null;
valores.sort((a, b) => a - b);
const n = valores.length;
const suma = valores.reduce((a, b) => a + b, 0);
const media = suma / n;
const varianza = valores
.map(v => Math.pow(v - media, 2))
.reduce((a, b) => a + b, 0) / n;
const desviacion = Math.sqrt(varianza);
const min = valores[0];
const max = valores[n - 1];
const mediana = n % 2 === 0
? (valores[n / 2 - 1] + valores[n / 2]) / 2
: valores[Math.floor(n / 2)];
return {
n: n,
media: media,
desviacion: desviacion,
min: min,
max: max,
mediana: mediana
};
}
}
// ========================================
// INSTANCIA GLOBAL
// ========================================
const generadorDatos = new GeneradorDatos();