-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfacultyanalysis.js
More file actions
319 lines (280 loc) · 14.2 KB
/
Copy pathfacultyanalysis.js
File metadata and controls
319 lines (280 loc) · 14.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
document.addEventListener('DOMContentLoaded', () => {
// Helper function to convert "1st", "2nd" to numbers
function parseOrdinal(ordinalString) {
if (!ordinalString) return null;
const lowerCaseString = ordinalString.toLowerCase().trim();
// More robust parsing using includes
if (lowerCaseString.includes('1st') || lowerCaseString.includes('1')) return 1;
if (lowerCaseString.includes('2nd') || lowerCaseString.includes('2')) return 2;
if (lowerCaseString.includes('3rd') || lowerCaseString.includes('3')) return 3;
if (lowerCaseString.includes('4th') || lowerCaseString.includes('4')) return 4;
if (lowerCaseString.includes('5th') || lowerCaseString.includes('5')) return 5;
if (lowerCaseString.includes('6th') || lowerCaseString.includes('6')) return 6;
// Fallback for direct numbers, though less likely if "1st" format is consistent
const num = parseInt(lowerCaseString);
return isNaN(num) ? null : num;
}
// Function to fetch and parse data from facultyshowresultdetails.html
async function fetchAndParseTableData() {
try {
const response = await fetch('facultyshowresultdetails.html');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const htmlText = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(htmlText, 'text/html');
const table = doc.getElementById('showresult');
if (!table) {
console.error('Table with id "showresult" not found in facultyshowresultdetails.html');
return [];
}
const rows = table.querySelectorAll('tbody tr');
const studentsData = [];
rows.forEach((row, index) => {
const columns = row.querySelectorAll('td');
if (columns.length >= 6) { // Ensure all expected columns are present
const yearString = columns[2].textContent.trim();
const semesterString = columns[3].textContent.trim();
const parsedYear = parseOrdinal(yearString);
const parsedSemester = parseOrdinal(semesterString);
const parsedMarks = parseInt(columns[5].textContent.trim());
console.log(`Parsed Row ${index + 1}:`, {
name: columns[0].textContent.trim(),
regNumber: columns[1].textContent.trim(),
year_string: yearString,
year_parsed: parsedYear,
semester_string: semesterString,
semester_parsed: parsedSemester,
subject: columns[4].textContent.trim(),
marks: parsedMarks,
totalMarks: 100 // Assumption: Each subject is out of 100 marks
});
if (parsedYear !== null && parsedSemester !== null && !isNaN(parsedMarks)) {
studentsData.push({
name: columns[0].textContent.trim(),
regNumber: columns[1].textContent.trim(),
year: parsedYear,
semester: parsedSemester,
subject: columns[4].textContent.trim(),
marks: parsedMarks,
totalMarks: 100
});
} else {
console.warn(`Skipping row ${index + 1} due to parsing error or invalid data:`, row.textContent);
}
} else {
console.warn(`Skipping row ${index + 1} due to insufficient columns:`, row.textContent);
}
});
console.log('Total Parsed Students Data:', studentsData);
return studentsData;
} catch (error) {
console.error('Error fetching or parsing table data:', error);
return [];
}
}
// Function to categorize students by percentage ranges for a given semester
function categorizeByPercentage(students, semester) {
const categories = {
'0-20%': 0, '21-40%': 0, '41-60%': 0, '61-80%': 0, '81-100%': 0
};
const semesterData = students.filter(s => s.semester === semester);
const studentSemesterTotals = {};
semesterData.forEach(s => {
if (!studentSemesterTotals[s.regNumber]) {
studentSemesterTotals[s.regNumber] = { totalMarksObtained: 0, totalPossibleMarks: 0 };
}
studentSemesterTotals[s.regNumber].totalMarksObtained += s.marks;
studentSemesterTotals[s.regNumber].totalPossibleMarks += s.totalMarks;
});
Object.values(studentSemesterTotals).forEach(data => {
if (data.totalPossibleMarks === 0) return;
const percentage = (data.totalMarksObtained / data.totalPossibleMarks) * 100;
if (percentage >= 0 && percentage <= 20) {
categories['0-20%']++;
} else if (percentage > 20 && percentage <= 40) {
categories['21-40%']++;
} else if (percentage > 40 && percentage <= 60) {
categories['41-60%']++;
} else if (percentage > 60 && percentage <= 80) {
categories['61-80%']++;
} else if (percentage > 80 && percentage <= 100) {
categories['81-100%']++;
}
});
return categories;
}
// Function to render a bar graph (unchanged from previous version)
function renderBarGraph(canvasId, title, labels, data) {
const ctx = document.getElementById(canvasId).getContext('2d');
if (window[canvasId + 'Chart']) {
window[canvasId + 'Chart'].destroy();
}
window[canvasId + 'Chart'] = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Number of Students',
data: data,
backgroundColor: [
'rgba(255, 99, 132, 0.6)', 'rgba(54, 162, 235, 0.6)',
'rgba(255, 206, 86, 0.6)', 'rgba(75, 192, 192, 0.6)',
'rgba(153, 102, 255, 0.6)'
],
borderColor: [
'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: { display: true, text: title, font: { size: 16 } },
legend: { display: false }
},
scales: {
y: { beginAtZero: true, title: { display: true, text: 'Number of Students' }, ticks: { precision: 0 } },
x: { title: { display: true, text: 'Percentage Range' } }
}
}
});
}
// Function to check and display "require more information" (unchanged from previous version)
function checkAndDisplayMissingInfo(studentsData, semester, elementId) {
const semesterExists = studentsData.some(s => s.semester === semester);
const missingInfoElement = document.getElementById(elementId);
const chartCanvas = document.getElementById(`semester${semester}Chart`);
if (!semesterExists) {
missingInfoElement.textContent = "Require more information for this semester.";
missingInfoElement.style.display = 'block';
chartCanvas.style.display = 'none';
} else {
missingInfoElement.textContent = '';
missingInfoElement.style.display = 'none';
chartCanvas.style.display = 'block';
}
return semesterExists;
}
// Main function to initialize all graphs
async function initializeGraphs() {
const studentsData = await fetchAndParseTableData();
for (let i = 1; i <= 6; i++) {
const semesterExists = checkAndDisplayMissingInfo(studentsData, i, `missing${i}`);
if (semesterExists) {
const categories = categorizeByPercentage(studentsData, i);
const labels = Object.keys(categories);
const data = Object.values(categories);
renderBarGraph(`semester${i}Chart`, `Semester ${i} Marks Distribution`, labels, data);
}
}
}
// Function to render student-specific marks graph
function renderStudentMarksGraph(regNumber, year, semester, studentsData) {
const studentMarksGraphDiv = document.getElementById('student-marks-graph');
const studentMarksChartCanvas = document.getElementById('studentMarksChart');
const studentNotFoundPara = document.getElementById('studentNotFound');
studentNotFoundPara.textContent = ''; // Clear previous messages
studentMarksGraphDiv.style.display = 'none'; // Hide by default
studentMarksChartCanvas.style.display = 'none'; // Hide canvas by default
// Ensure canvas and its context are available
if (!studentMarksChartCanvas) {
console.error("Student marks chart canvas element not found!");
studentNotFoundPara.textContent = 'Error: Chart display area not found.';
studentNotFoundPara.style.display = 'block';
return;
}
const ctx = studentMarksChartCanvas.getContext('2d');
if (!ctx) {
console.error("Could not get 2D context for studentMarksChartCanvas. Is the canvas element valid?");
studentNotFoundPara.textContent = 'Error: Could not prepare chart.';
studentNotFoundPara.style.display = 'block';
return;
}
// --- DEBUG LOG: Search Query ---
console.log('Search Query:', { regNumber: regNumber.toLowerCase(), year, semester });
// Safely destroy previous chart instance if it exists and is a Chart.js instance
if (window.studentMarksChart && typeof window.studentMarksChart.destroy === 'function') {
console.log("Destroying previous chart instance...");
window.studentMarksChart.destroy();
window.studentMarksChart = null; // Explicitly clear the reference after destruction
} else if (window.studentMarksChart) {
// This case indicates window.studentMarksChart exists but isn't a Chart instance with a destroy method.
// It's already corrupted or not a proper Chart object, so we'll just clear the reference.
console.warn("window.studentMarksChart exists but is not a valid Chart.js instance. Clearing reference to prevent further errors.");
window.studentMarksChart = null;
}
const studentSemesterData = studentsData.filter(s =>
s.regNumber.toLowerCase() === regNumber.toLowerCase() &&
s.year === year &&
s.semester === semester
);
// --- DEBUG LOG: Filtered Student Data ---
console.log('Filtered Student Data for search:', studentSemesterData);
if (studentSemesterData.length === 0) {
studentNotFoundPara.textContent = 'No data found for this student, year, and semester. Please check registration number, year, and semester.';
studentMarksGraphDiv.style.display = 'block';
studentNotFoundPara.style.display = 'block'; // Ensure the message is visible
return;
}
const labels = studentSemesterData.map(s => s.subject);
const data = studentSemesterData.map(s => (s.marks / s.totalMarks) * 100);
// Create the new chart
window.studentMarksChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Marks (%)',
data: data,
backgroundColor: 'rgba(153, 102, 255, 0.6)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: `Marks for ${studentSemesterData[0].name} (${regNumber}, Year ${year}, Semester ${semester})`,
font: { size: 16 }
}
},
scales: {
y: { beginAtZero: true, max: 100, title: { display: true, text: 'Percentage Marks' } },
x: { title: { display: true, text: 'Subject' } }
}
}
});
studentMarksGraphDiv.style.display = 'block';
studentMarksChartCanvas.style.display = 'block';
studentNotFoundPara.style.display = 'none'; // Hide "not found" message if graph is shown
}
// Event listener for the search button
const searchButton = document.getElementById('searchButton');
if (searchButton) {
searchButton.addEventListener('click', async (event) => {
event.preventDefault(); // Prevent form submission which causes page reload
const regNumber = document.getElementById('regNumber').value.trim();
const year = parseInt(document.getElementById('searchYear').value);
const semester = parseInt(document.getElementById('searchSemester').value);
console.log('Input Values from Form:', { regNumber, year, semester });
if (!regNumber || isNaN(year) || isNaN(semester)) {
alert('Please enter a valid Registration Number, Year, and Semester.');
console.log('Validation Failed: Missing or invalid input.');
return;
}
const studentsData = await fetchAndParseTableData();
renderStudentMarksGraph(regNumber, year, semester, studentsData);
});
}
// Initialize the semester graphs when the page loads
initializeGraphs();
});