-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
636 lines (546 loc) · 23 KB
/
Copy pathapp.js
File metadata and controls
636 lines (546 loc) · 23 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
// Student Dropout Early Warning System JavaScript
// Application state
const appState = {
currentSection: 'dashboard',
assessedStudents: [],
riskFactors: {
attendance: { high_risk_threshold: 70, medium_risk_threshold: 85, weight: 3 },
academic_performance: { high_risk_threshold: 60, medium_risk_threshold: 70, weight: 3 },
disciplinary_actions: { high_risk_threshold: 3, weight: 2 },
family_support: { high_risk_threshold: 4, weight: 2 },
homework_completion: { high_risk_threshold: 60, medium_risk_threshold: 80, weight: 2 }
},
interventions: {
high_risk: [
"Immediate counselor meeting",
"Parent/guardian conference",
"Intensive tutoring program",
"Attendance monitoring plan",
"Behavioral intervention support"
],
medium_risk: [
"Academic support programs",
"Peer mentoring",
"Study skills workshops",
"Regular check-ins with advisor"
],
low_risk: [
"Continue monitoring",
"Encourage extracurricular participation",
"Recognize achievements"
]
},
sampleStudents: [
{
student_id: "S001", age: 16, gender: "Female", socioeconomic_status: "Medium",
math_grade: 85, english_grade: 88, science_grade: 82, previous_gpa: 3.2,
attendance_rate: 92, days_absent: 8, disciplinary_actions: 0,
participation_score: 8, homework_completion: 90, parent_education: "College",
family_support: 8, extracurricular_activities: 2, teacher_relationship: 7
},
{
student_id: "S002", age: 17, gender: "Male", socioeconomic_status: "Low",
math_grade: 55, english_grade: 58, science_grade: 52, previous_gpa: 2.1,
attendance_rate: 65, days_absent: 25, disciplinary_actions: 4,
participation_score: 4, homework_completion: 45, parent_education: "High_School",
family_support: 3, extracurricular_activities: 0, teacher_relationship: 4
}
]
};
// Initialize application when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
console.log('Initializing Student Dropout Early Warning System...');
initializeApp();
});
function initializeApp() {
try {
initializeNavigation();
initializeAssessmentForm();
initializeBatchAnalysis();
console.log('Application initialized successfully');
} catch (error) {
console.error('Error initializing application:', error);
}
}
// Navigation functionality
function initializeNavigation() {
console.log('Setting up navigation...');
// Get all navigation elements
const navButtons = document.querySelectorAll('[data-section]');
console.log('Found', navButtons.length, 'navigation elements');
navButtons.forEach((button, index) => {
const targetSection = button.getAttribute('data-section');
console.log(`Setting up navigation button ${index}: ${targetSection}`);
button.addEventListener('click', function(event) {
event.preventDefault();
event.stopPropagation();
console.log('Navigation clicked:', targetSection);
showSection(targetSection);
});
});
// Ensure dashboard is shown initially
showSection('dashboard');
}
function showSection(sectionId) {
console.log('Switching to section:', sectionId);
try {
// Hide all sections
const allSections = document.querySelectorAll('.section');
allSections.forEach(section => {
section.classList.remove('section--active');
console.log('Hiding section:', section.id);
});
// Show target section
const targetSection = document.getElementById(sectionId);
if (targetSection) {
targetSection.classList.add('section--active');
console.log('Showing section:', sectionId);
} else {
console.error('Section not found:', sectionId);
}
// Update navigation active states
const navLinks = document.querySelectorAll('.nav__link');
navLinks.forEach(link => {
link.classList.remove('nav__link--active');
if (link.getAttribute('data-section') === sectionId) {
link.classList.add('nav__link--active');
console.log('Activated nav link for:', sectionId);
}
});
appState.currentSection = sectionId;
// Initialize section-specific functionality
if (sectionId === 'analytics') {
setTimeout(() => initializeAnalytics(), 200);
}
} catch (error) {
console.error('Error showing section:', error);
}
}
// Assessment form functionality
function initializeAssessmentForm() {
console.log('Setting up assessment form...');
const assessmentForm = document.getElementById('assessmentForm');
const loadSampleBtn = document.getElementById('loadSampleBtn');
const newAssessmentBtn = document.getElementById('newAssessmentBtn');
if (assessmentForm) {
assessmentForm.addEventListener('submit', function(event) {
event.preventDefault();
handleAssessmentSubmit(event);
});
console.log('Assessment form submit handler added');
}
if (loadSampleBtn) {
loadSampleBtn.addEventListener('click', function(event) {
event.preventDefault();
loadSampleData();
});
console.log('Load sample button handler added');
}
if (newAssessmentBtn) {
newAssessmentBtn.addEventListener('click', function(event) {
event.preventDefault();
resetAssessmentForm();
});
console.log('New assessment button handler added');
}
}
function handleAssessmentSubmit(event) {
console.log('Processing assessment form submission...');
try {
const formData = new FormData(event.target);
const studentData = {};
// Convert form data to object
for (let [key, value] of formData.entries()) {
studentData[key] = isNaN(value) || value === '' ? value : parseFloat(value);
}
console.log('Student data collected:', studentData);
// Validate data
if (!validateStudentData(studentData)) {
alert('Please fill in all required fields with valid values.');
return;
}
// Calculate risk assessment
const riskAssessment = calculateRiskAssessment(studentData);
console.log('Risk assessment calculated:', riskAssessment);
// Store assessment
appState.assessedStudents.push({
...studentData,
...riskAssessment,
assessmentDate: new Date().toISOString()
});
// Display results
displayAssessmentResults(studentData, riskAssessment);
} catch (error) {
console.error('Error processing assessment:', error);
alert('There was an error processing the assessment. Please try again.');
}
}
function validateStudentData(data) {
const requiredFields = [
'student_id', 'age', 'gender', 'socioeconomic_status',
'math_grade', 'english_grade', 'science_grade', 'previous_gpa',
'attendance_rate', 'days_absent', 'disciplinary_actions',
'participation_score', 'homework_completion', 'parent_education',
'family_support', 'extracurricular_activities', 'teacher_relationship'
];
for (let field of requiredFields) {
if (data[field] === undefined || data[field] === null || data[field] === '') {
console.log('Validation failed - missing field:', field);
return false;
}
}
// Validate numeric ranges
if (data.age < 14 || data.age > 19) return false;
if (data.math_grade < 0 || data.math_grade > 100) return false;
if (data.english_grade < 0 || data.english_grade > 100) return false;
if (data.science_grade < 0 || data.science_grade > 100) return false;
if (data.previous_gpa < 0 || data.previous_gpa > 4) return false;
if (data.attendance_rate < 0 || data.attendance_rate > 100) return false;
if (data.participation_score < 1 || data.participation_score > 10) return false;
if (data.homework_completion < 0 || data.homework_completion > 100) return false;
if (data.family_support < 1 || data.family_support > 10) return false;
if (data.teacher_relationship < 1 || data.teacher_relationship > 10) return false;
return true;
}
function calculateRiskAssessment(student) {
let riskScore = 0;
let maxScore = 0;
const riskFactors = [];
// Calculate academic performance average
const academicAvg = (student.math_grade + student.english_grade + student.science_grade) / 3;
// Attendance risk
maxScore += appState.riskFactors.attendance.weight;
if (student.attendance_rate < appState.riskFactors.attendance.high_risk_threshold) {
riskScore += appState.riskFactors.attendance.weight;
riskFactors.push('Very low attendance rate (' + student.attendance_rate + '%)');
} else if (student.attendance_rate < appState.riskFactors.attendance.medium_risk_threshold) {
riskScore += appState.riskFactors.attendance.weight * 0.6;
riskFactors.push('Below average attendance (' + student.attendance_rate + '%)');
}
// Academic performance risk
maxScore += appState.riskFactors.academic_performance.weight;
if (academicAvg < appState.riskFactors.academic_performance.high_risk_threshold) {
riskScore += appState.riskFactors.academic_performance.weight;
riskFactors.push('Poor academic performance (avg: ' + academicAvg.toFixed(1) + '%)');
} else if (academicAvg < appState.riskFactors.academic_performance.medium_risk_threshold) {
riskScore += appState.riskFactors.academic_performance.weight * 0.6;
riskFactors.push('Below average grades (avg: ' + academicAvg.toFixed(1) + '%)');
}
// Disciplinary actions risk
maxScore += appState.riskFactors.disciplinary_actions.weight;
if (student.disciplinary_actions >= appState.riskFactors.disciplinary_actions.high_risk_threshold) {
riskScore += appState.riskFactors.disciplinary_actions.weight;
riskFactors.push('Multiple disciplinary issues (' + student.disciplinary_actions + ' actions)');
} else if (student.disciplinary_actions > 0) {
riskScore += appState.riskFactors.disciplinary_actions.weight * 0.4;
riskFactors.push('Some behavioral concerns (' + student.disciplinary_actions + ' actions)');
}
// Family support risk
maxScore += appState.riskFactors.family_support.weight;
if (student.family_support <= appState.riskFactors.family_support.high_risk_threshold) {
riskScore += appState.riskFactors.family_support.weight;
riskFactors.push('Limited family support (score: ' + student.family_support + '/10)');
} else if (student.family_support <= 6) {
riskScore += appState.riskFactors.family_support.weight * 0.5;
riskFactors.push('Moderate family support concerns (score: ' + student.family_support + '/10)');
}
// Homework completion risk
maxScore += appState.riskFactors.homework_completion.weight;
if (student.homework_completion < appState.riskFactors.homework_completion.high_risk_threshold) {
riskScore += appState.riskFactors.homework_completion.weight;
riskFactors.push('Poor homework completion (' + student.homework_completion + '%)');
} else if (student.homework_completion < appState.riskFactors.homework_completion.medium_risk_threshold) {
riskScore += appState.riskFactors.homework_completion.weight * 0.6;
riskFactors.push('Inconsistent homework completion (' + student.homework_completion + '%)');
}
// Additional factors
if (student.participation_score <= 4) {
riskScore += 1;
maxScore += 1;
riskFactors.push('Low class participation (score: ' + student.participation_score + '/10)');
}
if (student.teacher_relationship <= 4) {
riskScore += 1;
maxScore += 1;
riskFactors.push('Poor teacher relationships (score: ' + student.teacher_relationship + '/10)');
}
if (student.extracurricular_activities === 0) {
riskScore += 0.5;
maxScore += 0.5;
riskFactors.push('No extracurricular involvement');
}
// Calculate risk percentage and determine level
const riskPercentage = Math.min(100, (riskScore / maxScore) * 100);
let riskLevel, riskClass;
if (riskPercentage < 30) {
riskLevel = 'Low Risk';
riskClass = 'low';
} else if (riskPercentage < 60) {
riskLevel = 'Medium Risk';
riskClass = 'medium';
} else {
riskLevel = 'High Risk';
riskClass = 'high';
}
return {
riskScore: riskPercentage.toFixed(1),
riskLevel,
riskClass,
riskFactors: riskFactors.length > 0 ? riskFactors : ['No significant risk factors identified'],
interventions: appState.interventions[riskClass] || appState.interventions.low_risk
};
}
function displayAssessmentResults(student, assessment) {
console.log('Displaying assessment results...');
const resultsContainer = document.getElementById('resultsContainer');
const resultsContent = document.getElementById('resultsContent');
if (!resultsContainer || !resultsContent) {
console.error('Results container elements not found');
return;
}
resultsContent.innerHTML = `
<div class="risk-result risk-result--${assessment.riskClass}">
<div class="risk-level risk-level--${assessment.riskClass}">${assessment.riskLevel}</div>
<div class="risk-probability">${assessment.riskScore}% Risk Score</div>
<p><strong>Student ID:</strong> ${student.student_id}</p>
</div>
<div class="risk-factors">
<h4>Key Risk Factors</h4>
<ul class="factor-list">
${assessment.riskFactors.map(factor => `<li>${factor}</li>`).join('')}
</ul>
</div>
<div class="interventions">
<h4>Recommended Interventions</h4>
<ul class="intervention-list">
${assessment.interventions.map(intervention => `<li>${intervention}</li>`).join('')}
</ul>
</div>
`;
resultsContainer.classList.remove('hidden');
resultsContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function loadSampleData() {
console.log('Loading sample student data...');
const assessmentForm = document.getElementById('assessmentForm');
if (!assessmentForm) {
console.error('Assessment form not found');
return;
}
const sampleStudent = appState.sampleStudents[0];
Object.keys(sampleStudent).forEach(key => {
const input = assessmentForm.querySelector(`[name="${key}"]`);
if (input) {
input.value = sampleStudent[key];
}
});
console.log('Sample data loaded successfully');
}
function resetAssessmentForm() {
console.log('Resetting assessment form...');
const assessmentForm = document.getElementById('assessmentForm');
const resultsContainer = document.getElementById('resultsContainer');
if (assessmentForm) {
assessmentForm.reset();
}
if (resultsContainer) {
resultsContainer.classList.add('hidden');
}
}
// Batch Analysis functionality
function initializeBatchAnalysis() {
console.log('Setting up batch analysis...');
const loadSampleDataBtn = document.getElementById('loadSampleDataBtn');
const csvFile = document.getElementById('csvFile');
if (loadSampleDataBtn) {
loadSampleDataBtn.addEventListener('click', function(event) {
event.preventDefault();
loadSampleBatchData();
});
console.log('Load sample batch data button handler added');
}
if (csvFile) {
csvFile.addEventListener('change', handleCSVUpload);
console.log('CSV file input handler added');
}
}
function loadSampleBatchData() {
console.log('Loading sample batch data...');
try {
const batchStudents = appState.sampleStudents.map(student => {
const assessment = calculateRiskAssessment(student);
return { ...student, ...assessment };
});
displayBatchResults(batchStudents);
} catch (error) {
console.error('Error loading sample batch data:', error);
}
}
function handleCSVUpload(event) {
const file = event.target.files[0];
if (!file) return;
alert('CSV upload functionality would parse the file here. Loading sample data instead.');
loadSampleBatchData();
}
function displayBatchResults(students) {
console.log('Displaying batch analysis results...');
const summaryStats = document.getElementById('summaryStats');
const batchTable = document.getElementById('batchTable');
const batchResults = document.getElementById('batchResults');
if (!summaryStats || !batchTable || !batchResults) {
console.error('Batch results elements not found');
return;
}
// Calculate summary statistics
const totalStudents = students.length;
const highRisk = students.filter(s => s.riskClass === 'high').length;
const mediumRisk = students.filter(s => s.riskClass === 'medium').length;
const lowRisk = students.filter(s => s.riskClass === 'low').length;
summaryStats.innerHTML = `
<div class="stat-item">
<span class="stat-value">${totalStudents}</span>
<span class="stat-label">Total Students</span>
</div>
<div class="stat-item">
<span class="stat-value">${highRisk}</span>
<span class="stat-label">High Risk</span>
</div>
<div class="stat-item">
<span class="stat-value">${mediumRisk}</span>
<span class="stat-label">Medium Risk</span>
</div>
<div class="stat-item">
<span class="stat-value">${lowRisk}</span>
<span class="stat-label">Low Risk</span>
</div>
`;
// Populate table
const tbody = batchTable.querySelector('tbody');
if (tbody) {
tbody.innerHTML = students.map(student => `
<tr>
<td>${student.student_id}</td>
<td>${student.age}</td>
<td>${student.gender}</td>
<td><span class="risk-badge risk-badge--${student.riskClass}">${student.riskLevel}</span></td>
<td>${student.riskScore}%</td>
<td>
<button class="btn btn--sm btn--outline" onclick="viewStudentDetails('${student.student_id}')">
View Details
</button>
</td>
</tr>
`).join('');
}
batchResults.classList.remove('hidden');
console.log('Batch results displayed successfully');
}
function viewStudentDetails(studentId) {
alert(`Detailed view for student ${studentId} would be implemented here.`);
}
// Analytics functionality
function initializeAnalytics() {
console.log('Initializing analytics charts...');
if (typeof Chart === 'undefined') {
console.error('Chart.js library not loaded');
return;
}
setTimeout(() => {
createAnalyticsCharts();
}, 100);
}
function createAnalyticsCharts() {
console.log('Creating analytics charts...');
try {
// Risk Distribution Chart
const riskDistributionCtx = document.getElementById('riskDistributionChart');
if (riskDistributionCtx) {
new Chart(riskDistributionCtx, {
type: 'doughnut',
data: {
labels: ['Low Risk', 'Medium Risk', 'High Risk'],
datasets: [{
data: [65, 25, 10],
backgroundColor: ['#1FB8CD', '#FFC185', '#B4413C']
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: 'Risk Level Distribution'
}
}
}
});
}
// Feature Importance Chart
const featureImportanceCtx = document.getElementById('featureImportanceChart');
if (featureImportanceCtx) {
new Chart(featureImportanceCtx, {
type: 'bar',
data: {
labels: ['Attendance', 'Academic Performance', 'Family Support', 'Homework', 'Disciplinary'],
datasets: [{
label: 'Importance Score',
data: [0.85, 0.78, 0.65, 0.58, 0.45],
backgroundColor: '#1FB8CD'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
max: 1
}
},
plugins: {
title: {
display: true,
text: 'Feature Importance Scores'
}
}
}
});
}
// Demographics Chart
const demographicsCtx = document.getElementById('demographicsChart');
if (demographicsCtx) {
new Chart(demographicsCtx, {
type: 'bar',
data: {
labels: ['Male Low', 'Male Medium', 'Male High', 'Female Low', 'Female Medium', 'Female High'],
datasets: [{
label: 'Student Count',
data: [32, 12, 6, 33, 13, 4],
backgroundColor: ['#1FB8CD', '#FFC185', '#B4413C', '#ECEBD5', '#5D878F', '#DB4545']
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true
}
},
plugins: {
title: {
display: true,
text: 'Risk Distribution by Gender'
}
}
}
});
}
console.log('Analytics charts created successfully');
} catch (error) {
console.error('Error creating analytics charts:', error);
}
}
// Global function exports
window.viewStudentDetails = viewStudentDetails;