-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1605 lines (1377 loc) · 57.6 KB
/
Copy pathscript.js
File metadata and controls
1605 lines (1377 loc) · 57.6 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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Global variables
let csvData = [];
let headers = [];
let currentPage = 1;
let rowsPerPage = 25;
let searchTerm = '';
let charts = {};
let parseConfig = {
header: true,
dynamicTyping: true,
skipEmptyLines: true
};
// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
// Event listeners for UI interactions
document.getElementById('uploadBtn').addEventListener('click', function() {
document.getElementById('fileInput').click();
});
// Hero upload button
document.getElementById('heroUploadBtn').addEventListener('click', function() {
document.getElementById('fileInput').click();
});
document.getElementById('fileInput').addEventListener('change', handleFileUpload);
// Tab switching
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', function() {
const tabId = this.getAttribute('data-tab');
switchTab(tabId);
});
});
// Data explorer pagination
document.getElementById('prevPage').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
renderDataTable();
}
});
document.getElementById('nextPage').addEventListener('click', () => {
const totalPages = Math.ceil(getFilteredData().length / rowsPerPage);
if (currentPage < totalPages) {
currentPage++;
renderDataTable();
}
});
document.getElementById('rowsPerPage').addEventListener('change', function() {
rowsPerPage = parseInt(this.value);
currentPage = 1;
renderDataTable();
});
document.getElementById('searchData').addEventListener('input', function() {
searchTerm = this.value.toLowerCase();
currentPage = 1;
renderDataTable();
});
// Column selector change events
document.getElementById('columnSelector').addEventListener('change', function() {
analyzeColumn(this.value);
});
document.getElementById('generateChart').addEventListener('click', generateVisualization);
document.getElementById('distributionColumnSelector').addEventListener('change', function() {
generateDistributionChart(this.value);
});
// Report buttons
document.getElementById('generateReport').addEventListener('click', generateTextReport);
document.getElementById('copyReport').addEventListener('click', copyTextReport);
document.getElementById('downloadReport').addEventListener('click', downloadTextReport);
document.getElementById('exportCSV').addEventListener('click', exportProcessedCSV);
document.getElementById('exportJSON').addEventListener('click', exportAsJSON);
});
// File upload handler
function handleFileUpload(event) {
const file = event.target.files[0];
if (!file) return;
document.getElementById('fileName').textContent = file.name;
const reader = new FileReader();
reader.onload = function(e) {
try {
const csvText = e.target.result;
// Show loading indicator
document.getElementById('fileName').textContent = `Analyzing ${file.name}...`;
// Parse CSV using Papa Parse
Papa.parse(csvText, {
...parseConfig,
complete: function(results) {
processCSVData(results);
},
error: function(error) {
alert('Error parsing CSV file: ' + error.message);
console.error(error);
document.getElementById('fileName').textContent = file.name;
}
});
} catch (error) {
alert('Error reading the CSV file: ' + error.message);
console.error(error);
document.getElementById('fileName').textContent = file.name;
}
};
reader.onerror = function() {
alert('Failed to read the file');
document.getElementById('fileName').textContent = file.name;
};
reader.readAsText(file);
}
// Process CSV data
function processCSVData(results) {
if (results.errors.length > 0) {
console.warn('CSV parsing had some errors:', results.errors);
}
csvData = results.data;
if (csvData.length === 0) {
alert('No data found in the CSV file');
return;
}
// Get headers
headers = Object.keys(csvData[0] || {});
// Show the main content after successful upload
document.getElementById('mainContent').classList.remove('hidden');
// Update file name display
document.getElementById('fileName').textContent = document.getElementById('fileInput').files[0].name;
// Switch to the Overview tab
switchTab('overview');
// Generate overviews
generateFileOverview();
populateColumnSelector();
analyzeColumn(headers[0] || '');
renderDataTable();
analyzeStatistics();
populateAxisSelectors();
populateDistributionColumnSelector();
// Scroll to results
document.getElementById('mainContent').scrollIntoView({ behavior: 'smooth' });
}
// Populate column selector dropdown
function populateColumnSelector() {
const columnSelector = document.getElementById('columnSelector');
columnSelector.innerHTML = '';
headers.forEach(header => {
const option = document.createElement('option');
option.value = header;
option.textContent = header;
columnSelector.appendChild(option);
});
}
// Populate axis selectors for visualization
function populateAxisSelectors() {
const xAxisSelector = document.getElementById('xAxisSelector');
const yAxisSelector = document.getElementById('yAxisSelector');
xAxisSelector.innerHTML = '';
yAxisSelector.innerHTML = '';
headers.forEach(header => {
const xOption = document.createElement('option');
xOption.value = header;
xOption.textContent = header;
xAxisSelector.appendChild(xOption);
const yOption = document.createElement('option');
yOption.value = header;
yOption.textContent = header;
yAxisSelector.appendChild(yOption);
});
// Set default Y-axis to the second column if available
if (headers.length > 1) {
yAxisSelector.value = headers[1];
}
}
// Populate distribution column selector
function populateDistributionColumnSelector() {
const distributionColumnSelector = document.getElementById('distributionColumnSelector');
distributionColumnSelector.innerHTML = '';
headers.forEach(header => {
const option = document.createElement('option');
option.value = header;
option.textContent = header;
distributionColumnSelector.appendChild(option);
});
// Generate distribution chart for the first column by default
if (headers.length > 0) {
generateDistributionChart(headers[0]);
}
}
// Switch between tabs
function switchTab(tabId) {
// Hide all tab content
document.querySelectorAll('.tab-content').forEach(content => {
content.classList.remove('active');
});
// Remove active class from all tabs
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.remove('active');
});
// Show the selected tab content
document.getElementById(tabId).classList.add('active');
// Add active class to the clicked tab
document.querySelector(`.tab[data-tab="${tabId}"]`).classList.add('active');
}
// Generate file overview
function generateFileOverview() {
const fileInfo = document.getElementById('fileInfo');
const quickStats = document.getElementById('quickStats');
const columnOverview = document.getElementById('columnOverview');
// File information
let fileInfoHTML = `
<div class="stat-card">
<h4>File Properties</h4>
<p><strong>File Name:</strong> ${document.getElementById('fileName').textContent}</p>
<p><strong>Number of Columns:</strong> ${headers.length}</p>
<p><strong>Number of Rows:</strong> ${csvData.length}</p>
<p><strong>File Size:</strong> ${formatFileSize(document.getElementById('fileInput').files[0].size)}</p>
</div>
`;
fileInfo.innerHTML = fileInfoHTML;
// Quick statistics
let totalCells = csvData.length * headers.length;
let nonEmptyCells = 0;
let numericCells = 0;
let textCells = 0;
csvData.forEach(row => {
headers.forEach(header => {
const value = row[header];
if (value !== null && value !== undefined && value !== '') {
nonEmptyCells++;
if (typeof value === 'number') {
numericCells++;
} else if (typeof value === 'string') {
textCells++;
}
}
});
});
const statsHTML = `
<div class="flex-item stat-card">
<h4>Total Rows</h4>
<div class="stat-value">${csvData.length.toLocaleString()}</div>
</div>
<div class="flex-item stat-card">
<h4>Total Columns</h4>
<div class="stat-value">${headers.length.toLocaleString()}</div>
</div>
<div class="flex-item stat-card">
<h4>Data Density</h4>
<div class="stat-value">${Math.round((nonEmptyCells / totalCells) * 100)}%</div>
<p>${nonEmptyCells.toLocaleString()} non-empty cells</p>
</div>
<div class="flex-item stat-card">
<h4>Data Types</h4>
<p><strong>Numeric:</strong> ${numericCells.toLocaleString()} (${Math.round((numericCells / nonEmptyCells) * 100)}%)</p>
<p><strong>Text:</strong> ${textCells.toLocaleString()} (${Math.round((textCells / nonEmptyCells) * 100)}%)</p>
<p><strong>Other:</strong> ${(nonEmptyCells - numericCells - textCells).toLocaleString()}</p>
</div>
`;
quickStats.innerHTML = statsHTML;
// Column overview
let columnHTML = '<table><tr><th>Column</th><th>Type</th><th>Non-Empty</th><th>Empty %</th></tr>';
headers.forEach(header => {
let columnStats = {
total: csvData.length,
nonEmpty: 0,
types: {
number: 0,
string: 0,
boolean: 0,
other: 0
}
};
csvData.forEach(row => {
const value = row[header];
if (value !== null && value !== undefined && value !== '') {
columnStats.nonEmpty++;
if (typeof value === 'number') {
columnStats.types.number++;
} else if (typeof value === 'string') {
columnStats.types.string++;
} else if (typeof value === 'boolean') {
columnStats.types.boolean++;
} else {
columnStats.types.other++;
}
}
});
// Determine dominant type
let dominantType = 'text';
let maxTypeCount = columnStats.types.string;
if (columnStats.types.number > maxTypeCount) {
dominantType = 'numeric';
maxTypeCount = columnStats.types.number;
}
if (columnStats.types.boolean > maxTypeCount) {
dominantType = 'boolean';
maxTypeCount = columnStats.types.boolean;
}
const emptyPercentage = ((columnStats.total - columnStats.nonEmpty) / columnStats.total) * 100;
const badgeClass = emptyPercentage > 50 ? 'badge-danger' :
emptyPercentage > 20 ? 'badge-warning' :
emptyPercentage > 5 ? 'badge-primary' :
'badge-success';
columnHTML += `
<tr>
<td>${header}</td>
<td>${dominantType}</td>
<td>${columnStats.nonEmpty}/${columnStats.total}</td>
<td><span class="badge ${badgeClass}">${emptyPercentage.toFixed(1)}%</span></td>
</tr>
`;
});
columnHTML += '</table>';
columnOverview.innerHTML = columnHTML;
}
// Format file size in human-readable format
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Render data table with pagination and search
function renderDataTable() {
const dataTable = document.getElementById('dataTable');
const pageInfo = document.getElementById('pageInfo');
// Get the filtered data
const data = getFilteredData();
// Calculate pagination information
const totalRows = data.length;
const totalPages = Math.ceil(totalRows / rowsPerPage);
currentPage = Math.min(currentPage, totalPages || 1);
// Update page info
pageInfo.textContent = `Page ${currentPage} of ${totalPages || 1}`;
// Get the rows for the current page
const startRow = (currentPage - 1) * rowsPerPage;
const endRow = Math.min(startRow + rowsPerPage, totalRows);
const pageData = data.slice(startRow, endRow);
// Create the table
let tableHTML = '<table>';
// Headers
tableHTML += '<thead><tr>';
headers.forEach(header => {
tableHTML += `<th>${header}</th>`;
});
tableHTML += '</tr></thead>';
// Body
tableHTML += '<tbody>';
if (pageData.length > 0) {
pageData.forEach(row => {
tableHTML += '<tr>';
headers.forEach(header => {
const cellValue = row[header];
tableHTML += `<td>${formatCellValue(cellValue)}</td>`;
});
tableHTML += '</tr>';
});
} else {
tableHTML += `<tr><td colspan="${headers.length}" style="text-align: center;">No data to display</td></tr>`;
}
tableHTML += '</tbody></table>';
// Display the table
dataTable.innerHTML = tableHTML;
}
// Get filtered data based on search term
function getFilteredData() {
if (!searchTerm) {
return csvData;
}
// Filter rows based on search term
return csvData.filter(row => {
return headers.some(header => {
const value = row[header];
return value !== null &&
value !== undefined &&
formatCellValue(value).toLowerCase().includes(searchTerm);
});
});
}
// Format cell value for display
function formatCellValue(value) {
if (value === null || value === undefined) {
return '';
}
if (value instanceof Date) {
return value.toLocaleString();
}
if (typeof value === 'number') {
return value.toLocaleString();
}
return String(value);
}
// Analyze column
function analyzeColumn(columnName) {
const columnAnalysis = document.getElementById('columnAnalysis');
if (!columnName || csvData.length === 0) {
columnAnalysis.innerHTML = '<p>No data available for analysis</p>';
return;
}
// Get column values
const columnValues = csvData.map(row => row[columnName]);
// Determine column type
const valueTypes = columnValues.map(value => {
if (value === null || value === undefined || value === '') return 'empty';
if (typeof value === 'number') return 'number';
if (typeof value === 'boolean') return 'boolean';
if (value instanceof Date) return 'date';
return 'string';
});
const typeCounts = {};
valueTypes.forEach(type => {
typeCounts[type] = (typeCounts[type] || 0) + 1;
});
// Determine dominant type
let dominantType = 'string';
let maxCount = 0;
for (const type in typeCounts) {
if (typeCounts[type] > maxCount && type !== 'empty') {
maxCount = typeCounts[type];
dominantType = type;
}
}
// Basic statistics
const nonEmptyValues = columnValues.filter(val => val !== null && val !== undefined && val !== '');
const uniqueValues = [...new Set(nonEmptyValues)].length;
let analysisHTML = `
<div class="stat-card">
<h4>Column: ${columnName}</h4>
<p><strong>Values:</strong> ${columnValues.length}</p>
<p><strong>Non-Empty:</strong> ${nonEmptyValues.length} (${Math.round((nonEmptyValues.length / columnValues.length) * 100)}%)</p>
<p><strong>Unique Values:</strong> ${uniqueValues}</p>
<p><strong>Dominant Type:</strong> ${dominantType}</p>
</div>
`;
// Type-specific analysis
if (dominantType === 'number') {
const numericValues = columnValues.filter(val => typeof val === 'number');
if (numericValues.length > 0) {
const min = Math.min(...numericValues);
const max = Math.max(...numericValues);
const sum = numericValues.reduce((total, val) => total + val, 0);
const avg = sum / numericValues.length;
// Calculate median
const sorted = [...numericValues].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
const median = sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
// Standard deviation
const variance = numericValues.reduce((total, val) => total + Math.pow(val - avg, 2), 0) / numericValues.length;
const stdDev = Math.sqrt(variance);
analysisHTML += `
<div class="stat-card">
<h4>Numeric Analysis</h4>
<p><strong>Minimum:</strong> ${min.toLocaleString()}</p>
<p><strong>Maximum:</strong> ${max.toLocaleString()}</p>
<p><strong>Range:</strong> ${(max - min).toLocaleString()}</p>
<p><strong>Sum:</strong> ${sum.toLocaleString()}</p>
<p><strong>Mean:</strong> ${avg.toLocaleString()}</p>
<p><strong>Median:</strong> ${median.toLocaleString()}</p>
<p><strong>Standard Deviation:</strong> ${stdDev.toFixed(2)}</p>
</div>
`;
// Generate a mini histogram
if (charts.miniHistogram) {
charts.miniHistogram.destroy();
}
analysisHTML += `<div class="chart-container"><canvas id="miniHistogram"></canvas></div>`;
}
} else if (dominantType === 'string') {
const stringValues = columnValues.filter(val => typeof val === 'string');
if (stringValues.length > 0) {
const lengthSum = stringValues.reduce((total, val) => total + val.length, 0);
const avgLength = lengthSum / stringValues.length;
// Find most frequent values
const valueCounts = {};
stringValues.forEach(val => {
valueCounts[val] = (valueCounts[val] || 0) + 1;
});
const sortedValues = Object.entries(valueCounts).sort((a, b) => b[1] - a[1]);
analysisHTML += `
<div class="stat-card">
<h4>Text Analysis</h4>
<p><strong>Average Length:</strong> ${avgLength.toFixed(2)} characters</p>
<p><strong>Most Common Values:</strong></p>
<table>
<tr>
<th>Value</th>
<th>Count</th>
<th>Percentage</th>
</tr>
`;
sortedValues.slice(0, 5).forEach(([value, count]) => {
const percentage = (count / stringValues.length * 100).toFixed(2);
analysisHTML += `
<tr>
<td>${value.length > 30 ? value.substring(0, 30) + '...' : value}</td>
<td>${count}</td>
<td>${percentage}%</td>
</tr>
`;
});
analysisHTML += `
</table>
</div>
`;
}
}
columnAnalysis.innerHTML = analysisHTML;
// Draw histogram for numeric columns
if (dominantType === 'number') {
const numericValues = columnValues.filter(val => typeof val === 'number');
if (numericValues.length > 0) {
setTimeout(() => {
const canvas = document.getElementById('miniHistogram');
if (canvas) {
const ctx = canvas.getContext('2d');
// Create histogram data
const min = Math.min(...numericValues);
const max = Math.max(...numericValues);
const range = max - min;
const binCount = Math.min(15, Math.ceil(Math.sqrt(numericValues.length)));
const binWidth = range / binCount;
const bins = Array(binCount).fill(0);
const binLabels = [];
for (let i = 0; i < binCount; i++) {
const binStart = min + i * binWidth;
const binEnd = binStart + binWidth;
binLabels.push(`${binStart.toFixed(1)} - ${binEnd.toFixed(1)}`);
}
numericValues.forEach(val => {
if (val === max) {
bins[binCount - 1]++;
} else {
const binIndex = Math.floor((val - min) / binWidth);
bins[binIndex]++;
}
});
charts.miniHistogram = new Chart(ctx, {
type: 'bar',
data: {
labels: binLabels,
datasets: [{
label: 'Frequency',
data: bins,
backgroundColor: 'rgba(52, 152, 219, 0.5)',
borderColor: 'rgba(52, 152, 219, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: `Distribution of ${columnName}`
},
legend: {
display: false
}
}
}
});
}
}, 50);
}
}
}
// Analyze statistics
function analyzeStatistics() {
const numericalStats = document.getElementById('numericalStats');
const textStats = document.getElementById('textStats');
const dataQuality = document.getElementById('dataQuality');
if (csvData.length === 0) {
numericalStats.innerHTML = '<p>No data available for analysis</p>';
textStats.innerHTML = '';
dataQuality.innerHTML = '';
return;
}
// Analyze each column
const columnTypes = [];
const numericColumns = [];
const textColumns = [];
headers.forEach(header => {
const columnValues = csvData.map(row => row[header]);
// Determine column type
const valueTypes = columnValues.map(value => {
if (value === null || value === undefined || value === '') return 'empty';
if (typeof value === 'number') return 'number';
if (typeof value === 'boolean') return 'boolean';
if (value instanceof Date) return 'date';
return 'string';
});
const typeCounts = {};
valueTypes.forEach(type => {
typeCounts[type] = (typeCounts[type] || 0) + 1;
});
// Determine dominant type
let dominantType = 'string';
let maxCount = 0;
for (const type in typeCounts) {
if (typeCounts[type] > maxCount && type !== 'empty') {
maxCount = typeCounts[type];
dominantType = type;
}
}
columnTypes.push(dominantType);
// Add to appropriate category
if (dominantType === 'number') {
numericColumns.push({
header: header,
values: columnValues.filter(val => typeof val === 'number')
});
} else if (dominantType === 'string') {
textColumns.push({
header: header,
values: columnValues.filter(val => typeof val === 'string')
});
}
});
// Numerical statistics
let numericHTML = '';
if (numericColumns.length > 0) {
numericHTML += `
<table>
<tr>
<th>Column</th>
<th>Count</th>
<th>Min</th>
<th>Max</th>
<th>Mean</th>
<th>Median</th>
<th>Std Dev</th>
</tr>
`;
numericColumns.forEach(column => {
const values = column.values;
if (values.length > 0) {
const min = Math.min(...values);
const max = Math.max(...values);
const sum = values.reduce((total, val) => total + val, 0);
const avg = sum / values.length;
// Calculate median
const sorted = [...values].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
const median = sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
// Standard deviation
const variance = values.reduce((total, val) => total + Math.pow(val - avg, 2), 0) / values.length;
const stdDev = Math.sqrt(variance);
numericHTML += `
<tr>
<td>${column.header}</td>
<td>${values.length}</td>
<td>${min.toLocaleString()}</td>
<td>${max.toLocaleString()}</td>
<td>${avg.toFixed(2)}</td>
<td>${median.toFixed(2)}</td>
<td>${stdDev.toFixed(2)}</td>
</tr>
`;
}
});
numericHTML += '</table>';
} else {
numericHTML = '<p>No numerical columns found for analysis</p>';
}
numericalStats.innerHTML = numericHTML;
// Text statistics
let textHTML = '';
if (textColumns.length > 0) {
textHTML += `
<table>
<tr>
<th>Column</th>
<th>Count</th>
<th>Unique Values</th>
<th>Avg Length</th>
<th>Most Common</th>
</tr>
`;
textColumns.forEach(column => {
const values = column.values;
if (values.length > 0) {
const uniqueCount = new Set(values).size;
const lengthSum = values.reduce((total, val) => total + val.length, 0);
const avgLength = lengthSum / values.length;
// Find most frequent value
const valueCounts = {};
values.forEach(val => {
valueCounts[val] = (valueCounts[val] || 0) + 1;
});
const mostCommon = Object.entries(valueCounts).sort((a, b) => b[1] - a[1])[0];
const mostCommonValue = mostCommon ? mostCommon[0] : 'N/A';
const mostCommonCount = mostCommon ? mostCommon[1] : 0;
textHTML += `
<tr>
<td>${column.header}</td>
<td>${values.length}</td>
<td>${uniqueCount}</td>
<td>${avgLength.toFixed(2)}</td>
<td>${mostCommonValue.length > 20 ? mostCommonValue.substring(0, 20) + '...' : mostCommonValue} (${mostCommonCount})</td>
</tr>
`;
}
});
textHTML += '</table>';
} else {
textHTML = '<p>No text columns found for analysis</p>';
}
textStats.innerHTML = textHTML;
// Data quality analysis
const totalRows = csvData.length;
const totalCells = totalRows * headers.length;
// Count missing values per column
const missingValues = [];
let totalMissing = 0;
headers.forEach(header => {
let missing = 0;
csvData.forEach(row => {
const value = row[header];
if (value === null || value === undefined || value === '') {
missing++;
}
});
missingValues.push({
header: header,
missing: missing,
percentage: (missing / totalRows) * 100
});
totalMissing += missing;
});
// Sort columns by missing percentage
missingValues.sort((a, b) => b.missing - a.missing);
// Data quality metrics
const completeness = ((totalCells - totalMissing) / totalCells) * 100;
let dataQualityHTML = `
<div class="stat-card">
<h4>Data Completeness</h4>
<div class="stat-value">${completeness.toFixed(2)}%</div>
<p>${totalMissing} missing values out of ${totalCells} cells</p>
</div>
<div class="stat-card">
<h4>Missing Values by Column</h4>
<table>
<tr>
<th>Column</th>
<th>Missing</th>
<th>Percentage</th>
</tr>
`;
missingValues.forEach(column => {
const badgeClass = column.percentage > 50 ? 'badge-danger' :
column.percentage > 20 ? 'badge-warning' :
column.percentage > 5 ? 'badge-primary' :
'badge-success';
dataQualityHTML += `
<tr>
<td>${column.header}</td>
<td>${column.missing}</td>
<td><span class="badge ${badgeClass}">${column.percentage.toFixed(2)}%</span></td>
</tr>
`;
});
dataQualityHTML += `
</table>
</div>
`;
dataQuality.innerHTML = dataQualityHTML;
// Create data quality chart
if (charts.dataQualityChart) {
charts.dataQualityChart.destroy();
}
const qualityCtx = document.getElementById('dataQualityChart').getContext('2d');
charts.dataQualityChart = new Chart(qualityCtx, {
type: 'bar',
data: {
labels: missingValues.slice(0, 10).map(col => col.header),
datasets: [{
label: 'Missing Values %',
data: missingValues.slice(0, 10).map(col => col.percentage),
backgroundColor: '#e74c3c'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: 'y',
scales: {
x: {
beginAtZero: true,
max: 100,
title: {
display: true,
text: 'Missing Values (%)'
}
},
y: {
title: {
display: true,
text: 'Column'
}
}
},
plugins: {
title: {
display: true,
text: 'Columns with Highest Missing Value Rates'
}
}
}
});
}
// Generate visualization
function generateVisualization() {
const chartType = document.getElementById('chartType').value;
const xAxis = document.getElementById('xAxisSelector').value;
const yAxis = document.getElementById('yAxisSelector').value;
if (csvData.length === 0) {
alert('Not enough data for visualization');
return;
}
// Extract data points
const chartData = csvData.map(row => ({
x: row[xAxis],
y: row[yAxis]
})).filter(point => point.x !== null && point.x !== undefined &&
point.y !== null && point.y !== undefined);
// Create the visualization
if (charts.vizChart) {
charts.vizChart.destroy();
}
const vizCtx = document.getElementById('dataVisualizationChart').getContext('2d');
// Configure the chart based on type
let chartConfig = {
type: chartType,
data: {
labels: chartData.map(point => point.x),
datasets: [{
label: yAxis,
data: chartData.map(point => point.y),
backgroundColor: 'rgba(52, 152, 219, 0.4)',
borderColor: 'rgba(52, 152, 219, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: `${yAxis} by ${xAxis}`
}
}
}