MasteryCalculator.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Collection;
  6. /**
  7. * 知识掌握度计算引擎(PHP版本)
  8. * 基于学案基准难度的动态加减逻辑计算掌握度
  9. *
  10. * 新算法特点:
  11. * 1. 根据学案基准难度(筑基、提分、培优、竞赛)动态调整权重
  12. * 2. 难度映射:0.0-1.0 → 1-4级
  13. * 3. 权重计算:越级、适应、降级三种情况
  14. * 4. 父节点掌握度:子节点平均值
  15. */
  16. class MasteryCalculator
  17. {
  18. /**
  19. * 掌握度阈值配置
  20. */
  21. private const MASTERY_THRESHOLD_WEAK = 0.50; // 薄弱点阈值
  22. private const MASTERY_THRESHOLD_GOOD = 0.70; // 良好阈值
  23. private const MASTERY_THRESHOLD_MASTER = 0.85; // 掌握阈值
  24. /**
  25. * 最小正确率要求
  26. */
  27. private const MIN_CORRECT_RATE = 0.60;
  28. /**
  29. * 计算学生对指定知识点的掌握度
  30. *
  31. * @param string $studentId 学生ID
  32. * @param string $kpCode 知识点编码
  33. * @param array|null $attempts 答题记录(可选,默认从数据库查询)
  34. * @param int|null $examBaseDifficulty 学案基准难度(1-4级,1=筑基, 2=提分, 3=培优, 4=竞赛)
  35. * @return array 返回['mastery' => 掌握度, 'confidence' => 置信度, 'trend' => 趋势]
  36. */
  37. public function calculateMasteryLevel(string $studentId, string $kpCode, ?array $attempts = null, ?int $examBaseDifficulty = null): array
  38. {
  39. // 优先使用传递的答题记录,如果没有则从数据库查询
  40. if ($attempts === null || empty($attempts)) {
  41. $attempts = $this->getStudentAttempts($studentId, $kpCode);
  42. }
  43. if (empty($attempts)) {
  44. Log::warning('没有答题记录,无法计算掌握度', [
  45. 'student_id' => $studentId,
  46. 'kp_code' => $kpCode,
  47. 'attempts_provided' => $attempts !== null,
  48. ]);
  49. // 【公司要求】返回值:只返回核心掌握度数据
  50. return [
  51. 'mastery' => 0.0,
  52. 'total_attempts' => 0,
  53. 'correct_attempts' => 0,
  54. 'accuracy_rate' => 0.0,
  55. ];
  56. }
  57. // 如果没有学案基准难度,使用默认值2(提分)
  58. if ($examBaseDifficulty === null) {
  59. Log::warning('缺少学案基准难度,使用默认值2(提分)', [
  60. 'student_id' => $studentId,
  61. 'kp_code' => $kpCode,
  62. 'attempts_count' => count($attempts),
  63. ]);
  64. $examBaseDifficulty = 2; // 默认提分难度
  65. }
  66. $masteryData = $this->calculateMasteryWithExamDifficulty($studentId, $kpCode, $attempts, $examBaseDifficulty);
  67. // 【公司要求】日志输出:只记录核心掌握度数据
  68. Log::info('掌握度计算完成', [
  69. 'student_id' => $studentId,
  70. 'kp_code' => $kpCode,
  71. 'exam_base_difficulty' => $examBaseDifficulty,
  72. 'difficulty_name' => $this->getDifficultyName($examBaseDifficulty),
  73. 'total_attempts' => count($attempts),
  74. 'correct_attempts' => $masteryData['correct_attempts'],
  75. 'final_mastery' => $masteryData['mastery'],
  76. ]);
  77. return $masteryData;
  78. }
  79. /**
  80. * 获取难度等级名称
  81. */
  82. private function getDifficultyName(int $difficultyLevel): string
  83. {
  84. return match ($difficultyLevel) {
  85. 1 => '筑基',
  86. 2 => '提分',
  87. 3 => '培优',
  88. 4 => '竞赛',
  89. default => '未知',
  90. };
  91. }
  92. /**
  93. * 【新算法】使用学案基准难度的动态加减逻辑计算掌握度
  94. */
  95. private function calculateMasteryWithExamDifficulty(string $studentId, string $kpCode, array $attempts, int $examBaseDifficulty): array
  96. {
  97. // 获取历史掌握度
  98. $historyMastery = DB::table('student_knowledge_mastery')
  99. ->where('student_id', $studentId)
  100. ->where('kp_code', $kpCode)
  101. ->first();
  102. $oldMastery = $historyMastery->mastery_level ?? 0.0; // 默认 0.0
  103. // 统计正确和错误次数
  104. $totalAttempts = count($attempts);
  105. $correctAttempts = 0;
  106. $incorrectAttempts = 0;
  107. // 计算每次答题的权重变化
  108. $totalChange = 0.0;
  109. foreach ($attempts as $attempt) {
  110. $isCorrect = boolval($attempt['is_correct'] ?? false);
  111. $questionDifficulty = floatval($attempt['question_difficulty'] ?? 0.6);
  112. // 难度映射:将0.0-1.0的浮点数难度映射为 1-4 等级
  113. $questionLevel = $this->mapDifficultyToLevel($questionDifficulty);
  114. // 根据难度关系计算权重变化
  115. $change = $this->calculateWeightByDifficultyRelation($questionLevel, $examBaseDifficulty, $isCorrect);
  116. $totalChange += $change;
  117. if ($isCorrect) {
  118. $correctAttempts++;
  119. } else {
  120. $incorrectAttempts++;
  121. }
  122. Log::debug('掌握度变化计算', [
  123. 'question_id' => $attempt['question_id'] ?? '',
  124. 'question_difficulty' => $questionDifficulty,
  125. 'question_level' => $questionLevel,
  126. 'exam_base_difficulty' => $examBaseDifficulty,
  127. 'is_correct' => $isCorrect,
  128. 'change' => $change,
  129. 'running_total' => $totalChange
  130. ]);
  131. }
  132. // 【公司要求】数值更新:newMastery = oldMastery + change
  133. $newMastery = $oldMastery + $totalChange;
  134. // 【公司要求】边界限制:0.0 ~ 1.0
  135. $newMastery = max(0.0, min(1.0, $newMastery));
  136. // 【公司要求】保存到数据库(只保存核心掌握度数据)
  137. // 【新增】同时更新 direct_mastery_level(直接学习掌握度),用于判断达标时优先使用
  138. DB::table('student_knowledge_mastery')
  139. ->updateOrInsert(
  140. ['student_id' => $studentId, 'kp_code' => $kpCode],
  141. [
  142. 'mastery_level' => $newMastery,
  143. 'direct_mastery_level' => $newMastery, // 直接学习掌握度,不会被子节点聚合覆盖
  144. 'confidence_level' => 0.0, // 不再计算置信度
  145. 'total_attempts' => ($historyMastery->total_attempts ?? 0) + $totalAttempts,
  146. 'correct_attempts' => ($historyMastery->correct_attempts ?? 0) + $correctAttempts,
  147. 'mastery_trend' => 'stable', // 不再判断趋势,统一设为stable
  148. 'last_mastery_update' => now(),
  149. 'updated_at' => now(),
  150. ]
  151. );
  152. // 【公司要求】返回值:只返回核心掌握度数据
  153. return [
  154. 'mastery' => round($newMastery, 4),
  155. 'total_attempts' => $totalAttempts,
  156. 'correct_attempts' => $correctAttempts,
  157. 'accuracy_rate' => round(($correctAttempts / $totalAttempts) * 100, 2),
  158. 'old_mastery' => $oldMastery,
  159. 'change' => round($totalChange, 4),
  160. 'details' => [
  161. 'exam_base_difficulty' => $examBaseDifficulty,
  162. 'total_change' => round($totalChange, 4)
  163. ],
  164. ];
  165. }
  166. /**
  167. * 【公司要求】难度映射:将题目中0.0-1.0的浮点数难度映射为1-4等级
  168. *
  169. * 公司要求:
  170. * 0.0 ~ 0.25 -> 1级(筑基)
  171. * 0.25 ~ 0.5 -> 2级(提分)
  172. * 0.5 ~ 0.75 -> 3级(培优)
  173. * 0.75 ~ 1.0 -> 4级(竞赛)
  174. *
  175. * @param float $difficulty 题目难度(0.0-1.0浮点数)
  176. * @return int 难度等级(1-4级)
  177. */
  178. private function mapDifficultyToLevel(float $difficulty): int
  179. {
  180. if ($difficulty >= 0.0 && $difficulty < 0.25) {
  181. return 1; // 1级(筑基)
  182. } elseif ($difficulty >= 0.25 && $difficulty < 0.5) {
  183. return 2; // 2级(提分)
  184. } elseif ($difficulty >= 0.5 && $difficulty < 0.75) {
  185. return 3; // 3级(培优)
  186. } else {
  187. return 4; // 4级(竞赛)
  188. }
  189. }
  190. /**
  191. * 【公司要求】根据难度关系计算权重变化
  192. *
  193. * 公司要求的三种难度关系及权重:
  194. * 1. 越级(Question > {学案基准难度}):对 +0.15 / 错 -0.05
  195. * 2. 适应(Question = {学案基准难度}):对 +0.10 / 错 -0.10
  196. * 3. 降级(Question < {学案基准难度}):对 +0.05 / 错 -0.15
  197. *
  198. * 学案基准难度获取:
  199. * - 来源:试卷表(papers.difficulty_category)
  200. * - 映射:筑基→1级,提分→2级,培优→3级,竞赛→4级
  201. *
  202. * @param int $questionLevel 题目难度等级(1-4)
  203. * @param int $examBaseDifficulty 学案基准难度(1-4)
  204. * @param bool $isCorrect 答题是否正确
  205. * @return float 权重变化值
  206. */
  207. private function calculateWeightByDifficultyRelation(int $questionLevel, int $examBaseDifficulty, bool $isCorrect): float
  208. {
  209. if ($questionLevel > $examBaseDifficulty) {
  210. // 越级:题目难度 > 学案基准难度
  211. return $isCorrect ? 0.15 : -0.05;
  212. } elseif ($questionLevel == $examBaseDifficulty) {
  213. // 适应:题目难度 = 学案基准难度
  214. return $isCorrect ? 0.10 : -0.10;
  215. } else {
  216. // 降级:题目难度 < 学案基准难度
  217. return $isCorrect ? 0.05 : -0.15;
  218. }
  219. }
  220. /**
  221. * 获取学生的答题记录
  222. */
  223. private function getStudentAttempts(string $studentId, string $kpCode): array
  224. {
  225. $attempts = [];
  226. // 优先从 student_answer_steps 表获取(步骤级记录)
  227. $stepAttempts = DB::table('student_answer_steps')
  228. ->where('student_id', $studentId)
  229. ->where('kp_id', $kpCode)
  230. ->orderBy('created_at', 'asc')
  231. ->get();
  232. foreach ($stepAttempts as $step) {
  233. // 【关键修复】从题目表查询题目难度
  234. $questionDifficulty = 0.6; // 默认难度
  235. if ($step->question_id) {
  236. $question = DB::table('questions')
  237. ->where('id', $step->question_id)
  238. ->orWhere('question_code', $step->question_id)
  239. ->first();
  240. if ($question && $question->difficulty !== null) {
  241. $questionDifficulty = floatval($question->difficulty);
  242. }
  243. }
  244. $attempts[] = [
  245. 'student_id' => $step->student_id,
  246. 'paper_id' => $step->exam_id,
  247. 'question_id' => $step->question_id,
  248. 'kp_code' => $step->kp_id,
  249. 'is_correct' => (bool) $step->is_correct,
  250. 'score_obtained' => $step->step_score,
  251. 'max_score' => $step->step_score, // 步骤分数本身就是满分
  252. 'question_difficulty' => $questionDifficulty, // 【新增】题目难度
  253. 'created_at' => $step->created_at,
  254. ];
  255. }
  256. // 如果没有步骤级记录,从 student_answer_questions 表获取(题目级记录)
  257. if (empty($attempts)) {
  258. $questionAttempts = DB::table('student_answer_questions')
  259. ->where('student_id', $studentId)
  260. ->orderBy('created_at', 'asc')
  261. ->get();
  262. foreach ($questionAttempts as $question) {
  263. // 【关键修复】从题目表查询题目难度
  264. $questionDifficulty = 0.6; // 默认难度
  265. if ($question->question_id) {
  266. $questionInfo = DB::table('questions')
  267. ->where('id', $question->question_id)
  268. ->orWhere('question_code', $question->question_id)
  269. ->first();
  270. if ($questionInfo && $questionInfo->difficulty !== null) {
  271. $questionDifficulty = floatval($questionInfo->difficulty);
  272. }
  273. }
  274. $attempts[] = [
  275. 'student_id' => $question->student_id,
  276. 'paper_id' => $question->exam_id,
  277. 'question_id' => $question->question_id,
  278. 'kp_code' => $kpCode, // 使用传入的kpCode
  279. 'is_correct' => ($question->score_obtained ?? 0) > 0,
  280. 'score_obtained' => $question->score_obtained ?? 0,
  281. 'max_score' => $question->max_score ?? 0,
  282. 'question_difficulty' => $questionDifficulty, // 【新增】题目难度
  283. 'created_at' => $question->created_at,
  284. ];
  285. }
  286. }
  287. return $attempts;
  288. }
  289. /**
  290. * 批量更新学生掌握度
  291. */
  292. public function batchUpdateMastery(string $studentId, array $kpCodes): array
  293. {
  294. $results = [];
  295. foreach ($kpCodes as $kpCode) {
  296. // calculateMasteryLevel 内部的 calculateMasteryWithExamDifficulty 已经会保存到数据库
  297. // 包括 direct_mastery_level,所以这里不需要再次保存
  298. $masteryData = $this->calculateMasteryLevel($studentId, $kpCode);
  299. $results[$kpCode] = $masteryData;
  300. }
  301. return $results;
  302. }
  303. /**
  304. * 获取学生所有知识点的掌握度概览
  305. */
  306. public function getStudentMasteryOverview(string $studentId): array
  307. {
  308. $masteryList = DB::table('student_knowledge_mastery')
  309. ->where('student_id', $studentId)
  310. ->get();
  311. if ($masteryList->isEmpty()) {
  312. return [
  313. 'total_knowledge_points' => 0,
  314. 'average_mastery_level' => 0.0,
  315. 'mastered_knowledge_points' => 0,
  316. 'good_knowledge_points' => 0,
  317. 'weak_knowledge_points' => 0,
  318. 'weak_knowledge_points_list' => [],
  319. 'details' => [],
  320. ];
  321. }
  322. $masteryArray = $masteryList->toArray();
  323. $total = count($masteryArray);
  324. $average = $masteryArray ? array_sum(array_column($masteryArray, 'mastery_level')) / $total : 0;
  325. $mastered = [];
  326. $good = [];
  327. $weak = [];
  328. foreach ($masteryArray as $item) {
  329. $level = floatval($item->mastery_level);
  330. if ($level >= self::MASTERY_THRESHOLD_MASTER) {
  331. $mastered[] = $item;
  332. } elseif ($level >= self::MASTERY_THRESHOLD_GOOD) {
  333. $good[] = $item;
  334. } else {
  335. $weak[] = $item;
  336. }
  337. }
  338. return [
  339. 'total_knowledge_points' => $total,
  340. 'average_mastery_level' => round($average, 4),
  341. 'mastered_knowledge_points' => count($mastered),
  342. 'good_knowledge_points' => count($good),
  343. 'weak_knowledge_points' => count($weak),
  344. 'weak_knowledge_points_list' => $weak,
  345. 'details' => $masteryArray,
  346. ];
  347. }
  348. /**
  349. * 【新功能】获取知识点层级关系
  350. */
  351. private function getKnowledgePointHierarchy(string $kpCode): ?array
  352. {
  353. try {
  354. $kp = DB::table('knowledge_points')
  355. ->where('kp_code', $kpCode)
  356. ->first();
  357. if (!$kp) {
  358. return null;
  359. }
  360. return [
  361. 'kp_code' => $kp->kp_code,
  362. 'parent_kp_code' => $kp->parent_kp_code,
  363. 'level' => $kp->level ?? 1,
  364. ];
  365. } catch (\Exception $e) {
  366. Log::warning('获取知识点层级关系失败', [
  367. 'kp_code' => $kpCode,
  368. 'error' => $e->getMessage(),
  369. ]);
  370. return null;
  371. }
  372. }
  373. /**
  374. * 【公司要求】计算父节点掌握度(所有子节点算术平均值)
  375. *
  376. * 公司要求:
  377. * 1. 查询结构:通过 knowledge_points 表获取知识点的层级关系(parent_kp_code)
  378. * 2. 平均值计算:如果一个知识点是父节点,它的掌握度不再从数据库直接读,
  379. * 而是实时计算其下所有子节点掌握度的算术平均数
  380. * 3. 多级递归:支持多级结构,能够从最底层逐级向上求平均
  381. *
  382. * 递归计算流程:
  383. * - 从最底层叶子节点开始,逐级向上计算每个父节点的掌握度
  384. * - 父节点掌握度 = 所有直接子节点掌握度的算术平均数
  385. *
  386. * @param string $studentId 学生ID
  387. * @param string $parentKpCode 父节点编码
  388. * @param int $maxDepth 最大递归深度(默认10级)
  389. * @return float 父节点掌握度(0.0-1.0)
  390. */
  391. public function calculateParentMastery(string $studentId, string $parentKpCode, int $maxDepth = 3): float
  392. {
  393. return $this->calculateParentMasteryRecursive($studentId, $parentKpCode, 1, $maxDepth);
  394. }
  395. /**
  396. * 【公司要求】递归计算父节点掌握度(多级结构支持)
  397. *
  398. * 多级递归计算流程:
  399. * 1. 获取父节点的所有直接子节点
  400. * 2. 对每个子节点:
  401. * - 如果子节点也是父节点,递归计算其掌握度
  402. * - 如果子节点是叶子节点,从 student_knowledge_mastery 表读取掌握度
  403. * 3. 计算所有子节点掌握度的算术平均数
  404. * 4. 返回父节点掌握度
  405. *
  406. * @param string $studentId 学生ID
  407. * @param string $parentKpCode 父节点编码
  408. * @param int $currentDepth 当前递归深度
  409. * @param int $maxDepth 最大递归深度(防止无限递归)
  410. * @return float 父节点掌握度
  411. */
  412. private function calculateParentMasteryRecursive(string $studentId, string $parentKpCode, int $currentDepth, int $maxDepth): float
  413. {
  414. try {
  415. // 【公司要求】防止无限递归
  416. if ($currentDepth > $maxDepth) {
  417. Log::warning('父节点掌握度计算达到最大递归深度', [
  418. 'student_id' => $studentId,
  419. 'parent_kp_code' => $parentKpCode,
  420. 'current_depth' => $currentDepth,
  421. 'max_depth' => $maxDepth
  422. ]);
  423. return 0.0;
  424. }
  425. // 【公司要求】查询结构:通过 knowledge_points 表获取知识点的层级关系(parent_kp_code)
  426. // 获取所有直接子节点
  427. $childKps = DB::table('knowledge_points')
  428. ->where('parent_kp_code', $parentKpCode)
  429. ->pluck('kp_code')
  430. ->toArray();
  431. if (empty($childKps)) {
  432. // 如果没有子节点,返回0
  433. Log::debug('父节点没有子节点,返回0', [
  434. 'student_id' => $studentId,
  435. 'parent_kp_code' => $parentKpCode
  436. ]);
  437. return 0.0;
  438. }
  439. // 【公司要求】多级递归:支持多级结构,能够从最底层逐级向上求平均
  440. // 获取所有子节点的掌握度(递归计算)
  441. $masteryLevels = [];
  442. foreach ($childKps as $childKpCode) {
  443. // 【公司要求】多级递归:递归计算子节点掌握度
  444. $childMastery = $this->calculateParentMasteryRecursive($studentId, $childKpCode, $currentDepth + 1, $maxDepth);
  445. // 如果子节点没有子节点,则从student_knowledge_mastery表读取
  446. if ($childMastery == 0.0) {
  447. $mastery = DB::table('student_knowledge_mastery')
  448. ->where('student_id', $studentId)
  449. ->where('kp_code', $childKpCode)
  450. ->value('mastery_level');
  451. if ($mastery !== null) {
  452. $masteryLevels[] = floatval($mastery);
  453. }
  454. } else {
  455. // 子节点有子节点,使用递归计算的结果
  456. $masteryLevels[] = $childMastery;
  457. }
  458. }
  459. if (empty($masteryLevels)) {
  460. Log::warning('父节点所有子节点都没有掌握度数据', [
  461. 'student_id' => $studentId,
  462. 'parent_kp_code' => $parentKpCode,
  463. 'child_count' => count($childKps)
  464. ]);
  465. return 0.0;
  466. }
  467. // 【公司要求】平均值计算:父节点掌握度 = 所有子节点掌握度的算术平均数
  468. $averageMastery = array_sum($masteryLevels) / count($masteryLevels);
  469. $result = round($averageMastery, 4);
  470. Log::info('父节点掌握度计算完成', [
  471. 'student_id' => $studentId,
  472. 'parent_kp_code' => $parentKpCode,
  473. 'child_count' => count($childKps),
  474. 'mastery_count' => count($masteryLevels),
  475. 'average_mastery' => $result,
  476. 'child_masteries' => $masteryLevels,
  477. 'current_depth' => $currentDepth
  478. ]);
  479. return $result;
  480. } catch (\Exception $e) {
  481. Log::error('计算父节点掌握度失败', [
  482. 'student_id' => $studentId,
  483. 'parent_kp_code' => $parentKpCode,
  484. 'current_depth' => $currentDepth,
  485. 'error' => $e->getMessage(),
  486. ]);
  487. return 0.0;
  488. }
  489. }
  490. /**
  491. * 【增强】获取学生所有知识点的掌握度概览(支持父节点计算)
  492. * 【优化】预加载所有数据到内存,避免 N+1 查询问题
  493. */
  494. public function getStudentMasteryOverviewWithHierarchy(string $studentId): array
  495. {
  496. $startTime = microtime(true);
  497. // 1. 一次性查询学生所有知识点的掌握度
  498. $masteryList = DB::table('student_knowledge_mastery')
  499. ->where('student_id', $studentId)
  500. ->get();
  501. if ($masteryList->isEmpty()) {
  502. return [
  503. 'total_knowledge_points' => 0,
  504. 'average_mastery_level' => 0.0,
  505. 'mastered_knowledge_points' => 0,
  506. 'good_knowledge_points' => 0,
  507. 'weak_knowledge_points' => 0,
  508. 'weak_knowledge_points_list' => [],
  509. 'details' => [],
  510. 'parent_mastery_levels' => [],
  511. ];
  512. }
  513. $masteryArray = $masteryList->toArray();
  514. // 构建掌握度映射表(kp_code => mastery_level)
  515. $masteryMap = [];
  516. foreach ($masteryArray as $item) {
  517. $masteryMap[$item->kp_code] = floatval($item->mastery_level);
  518. }
  519. $total = count($masteryArray);
  520. $average = array_sum($masteryMap) / $total;
  521. $mastered = [];
  522. $good = [];
  523. $weak = [];
  524. foreach ($masteryArray as $item) {
  525. $level = floatval($item->mastery_level);
  526. if ($level >= self::MASTERY_THRESHOLD_MASTER) {
  527. $mastered[] = $item;
  528. } elseif ($level >= self::MASTERY_THRESHOLD_GOOD) {
  529. $good[] = $item;
  530. } else {
  531. $weak[] = $item;
  532. }
  533. }
  534. // 2. 一次性查询所有知识点的层级关系
  535. $allKpRelations = DB::table('knowledge_points')
  536. ->whereNotNull('parent_kp_code')
  537. ->select('kp_code', 'parent_kp_code')
  538. ->get();
  539. // 构建父子关系映射(parent_kp_code => [child_kp_codes])
  540. $childrenMap = [];
  541. $allParentKpCodes = [];
  542. foreach ($allKpRelations as $relation) {
  543. $parentCode = $relation->parent_kp_code;
  544. $childCode = $relation->kp_code;
  545. if (!isset($childrenMap[$parentCode])) {
  546. $childrenMap[$parentCode] = [];
  547. }
  548. $childrenMap[$parentCode][] = $childCode;
  549. $allParentKpCodes[$parentCode] = true;
  550. }
  551. Log::debug('MasteryCalculator: 预加载数据完成', [
  552. 'student_id' => $studentId,
  553. 'mastery_count' => count($masteryMap),
  554. 'parent_count' => count($allParentKpCodes),
  555. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  556. ]);
  557. // 3. 在内存中计算所有父节点的掌握度(不再查询数据库)
  558. $parentMasteryLevels = [];
  559. foreach (array_keys($allParentKpCodes) as $parentKpCode) {
  560. $parentMastery = $this->calculateParentMasteryInMemory(
  561. $parentKpCode,
  562. $childrenMap,
  563. $masteryMap,
  564. 1,
  565. 3
  566. );
  567. if ($parentMastery > 0) {
  568. $parentMasteryLevels[$parentKpCode] = $parentMastery;
  569. }
  570. }
  571. Log::info('MasteryCalculator: getStudentMasteryOverviewWithHierarchy 完成', [
  572. 'student_id' => $studentId,
  573. 'total_kp' => $total,
  574. 'parent_mastery_count' => count($parentMasteryLevels),
  575. 'total_time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  576. ]);
  577. return [
  578. 'total_knowledge_points' => $total,
  579. 'average_mastery_level' => round($average, 4),
  580. 'mastered_knowledge_points' => count($mastered),
  581. 'good_knowledge_points' => count($good),
  582. 'weak_knowledge_points' => count($weak),
  583. 'weak_knowledge_points_list' => $weak,
  584. 'details' => $masteryArray,
  585. 'parent_mastery_levels' => $parentMasteryLevels,
  586. ];
  587. }
  588. /**
  589. * 【优化】在内存中递归计算父节点掌握度(不查询数据库)
  590. *
  591. * @param string $parentKpCode 父节点编码
  592. * @param array $childrenMap 父子关系映射(parent => [children])
  593. * @param array $masteryMap 掌握度映射(kp_code => mastery_level)
  594. * @param int $currentDepth 当前递归深度
  595. * @param int $maxDepth 最大递归深度
  596. * @return float 父节点掌握度
  597. */
  598. private function calculateParentMasteryInMemory(
  599. string $parentKpCode,
  600. array $childrenMap,
  601. array $masteryMap,
  602. int $currentDepth,
  603. int $maxDepth
  604. ): float {
  605. // 防止无限递归
  606. if ($currentDepth > $maxDepth) {
  607. return 0.0;
  608. }
  609. // 获取子节点
  610. $childKpCodes = $childrenMap[$parentKpCode] ?? [];
  611. if (empty($childKpCodes)) {
  612. return 0.0;
  613. }
  614. $masteryLevels = [];
  615. foreach ($childKpCodes as $childKpCode) {
  616. // 如果子节点也是父节点,递归计算
  617. if (isset($childrenMap[$childKpCode])) {
  618. $childMastery = $this->calculateParentMasteryInMemory(
  619. $childKpCode,
  620. $childrenMap,
  621. $masteryMap,
  622. $currentDepth + 1,
  623. $maxDepth
  624. );
  625. if ($childMastery > 0) {
  626. $masteryLevels[] = $childMastery;
  627. }
  628. }
  629. // 如果子节点有掌握度数据,使用它
  630. if (isset($masteryMap[$childKpCode])) {
  631. $masteryLevels[] = $masteryMap[$childKpCode];
  632. }
  633. }
  634. if (empty($masteryLevels)) {
  635. return 0.0;
  636. }
  637. // 计算平均值
  638. return round(array_sum($masteryLevels) / count($masteryLevels), 4);
  639. }
  640. }