MasteryCalculator.php 32 KB

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