MasteryCalculator.php 28 KB

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