KnowledgeGraphService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. namespace App\Services;
  3. class KnowledgeGraphService
  4. {
  5. protected MathRecSysService $mathRecSys;
  6. public function __construct(MathRecSysService $mathRecSys)
  7. {
  8. $this->mathRecSys = $mathRecSys;
  9. }
  10. /**
  11. * 获取知识图谱数据(格式化后)
  12. *
  13. * @param string|null $focus 焦点知识点
  14. * @return array
  15. */
  16. public function getGraphData(?string $focus = null): array
  17. {
  18. try {
  19. $graphData = $this->mathRecSys->getKnowledgeGraph($focus);
  20. return [
  21. 'success' => true,
  22. 'nodes' => $this->formatNodes($graphData['nodes'] ?? []),
  23. 'edges' => $this->formatEdges($graphData['edges'] ?? []),
  24. 'categories' => $this->extractCategories($graphData['nodes'] ?? []),
  25. 'metadata' => [
  26. 'total_nodes' => count($graphData['nodes'] ?? []),
  27. 'total_edges' => count($graphData['edges'] ?? []),
  28. 'focus' => $focus
  29. ]
  30. ];
  31. } catch (\Exception $e) {
  32. \Log::error('获取知识图谱数据失败', ['error' => $e->getMessage()]);
  33. return [
  34. 'success' => false,
  35. 'nodes' => [],
  36. 'edges' => [],
  37. 'categories' => [],
  38. 'error' => $e->getMessage()
  39. ];
  40. }
  41. }
  42. /**
  43. * 获取知识点详情
  44. *
  45. * @param string $kpId 知识点ID
  46. * @return array
  47. */
  48. public function getKnowledgePointDetail(string $kpId): array
  49. {
  50. try {
  51. // 从MathRecSys获取
  52. $detail = $this->mathRecSys->getKnowledgePoint($kpId);
  53. // 从本地获取相关题目(这里需要实现)
  54. $relatedQuestions = $this->getRelatedQuestions($kpId);
  55. return [
  56. 'success' => true,
  57. 'data' => array_merge($detail['data'] ?? [], [
  58. 'related_questions' => $relatedQuestions
  59. ])
  60. ];
  61. } catch (\Exception $e) {
  62. \Log::error('获取知识点详情失败', [
  63. 'kp_id' => $kpId,
  64. 'error' => $e->getMessage()
  65. ]);
  66. return [
  67. 'success' => false,
  68. 'error' => $e->getMessage()
  69. ];
  70. }
  71. }
  72. /**
  73. * 获取知识点依赖关系
  74. *
  75. * @param string $kpId 知识点ID
  76. * @return array
  77. */
  78. public function getKnowledgePointDependencies(string $kpId): array
  79. {
  80. try {
  81. $graphData = $this->mathRecSys->getKnowledgeGraph($kpId);
  82. $dependencies = [
  83. 'prerequisites' => [], // 前置知识点
  84. 'advances' => [], // 后续知识点
  85. 'contrasts' => [] // 对比知识点
  86. ];
  87. foreach ($graphData['edges'] ?? [] as $edge) {
  88. if ($edge['start_uuid'] === $kpId) {
  89. // 该知识点指向其他知识点
  90. if ($edge['type'] === 'AdvancesTo') {
  91. $dependencies['advances'][] = [
  92. 'target' => $edge['end_uuid'],
  93. 'description' => $edge['properties']['description'] ?? ''
  94. ];
  95. } elseif ($edge['type'] === 'ContrastsWith') {
  96. $dependencies['contrasts'][] = [
  97. 'target' => $edge['end_uuid'],
  98. 'description' => $edge['properties']['description'] ?? ''
  99. ];
  100. }
  101. } elseif ($edge['end_uuid'] === $kpId) {
  102. // 其他知识点指向该知识点
  103. if ($edge['type'] === 'Prerequisite') {
  104. $dependencies['prerequisites'][] = [
  105. 'source' => $edge['start_uuid'],
  106. 'description' => $edge['properties']['description'] ?? ''
  107. ];
  108. }
  109. }
  110. }
  111. return [
  112. 'success' => true,
  113. 'data' => $dependencies
  114. ];
  115. } catch (\Exception $e) {
  116. \Log::error('获取知识点依赖关系失败', [
  117. 'kp_id' => $kpId,
  118. 'error' => $e->getMessage()
  119. ]);
  120. return [
  121. 'success' => false,
  122. 'error' => $e->getMessage()
  123. ];
  124. }
  125. }
  126. /**
  127. * 获取学习路径建议
  128. *
  129. * @param string $studentId 学生ID
  130. * @param string $targetKp 目标知识点
  131. * @return array
  132. */
  133. public function getLearningPath(string $studentId, string $targetKp): array
  134. {
  135. try {
  136. // 获取学生画像
  137. $profile = $this->mathRecSys->getStudentProfile($studentId);
  138. // 获取知识图谱
  139. $graphData = $this->mathRecSys->getKnowledgeGraph($targetKp);
  140. // 分析前置知识点掌握情况
  141. $prerequisites = [];
  142. foreach ($graphData['edges'] ?? [] as $edge) {
  143. if ($edge['end_uuid'] === $targetKp && $edge['type'] === 'Prerequisite') {
  144. $prereqId = $edge['start_uuid'];
  145. $mastery = $this->getMasteryFromProfile($profile, $prereqId);
  146. $prerequisites[] = [
  147. 'kp_id' => $prereqId,
  148. 'description' => $edge['properties']['description'] ?? '',
  149. 'current_mastery' => $mastery,
  150. 'is_ready' => $mastery >= 0.6,
  151. 'priority' => $this->calculatePriority($mastery)
  152. ];
  153. }
  154. }
  155. // 按优先级排序
  156. usort($prerequisites, function ($a, $b) {
  157. return $b['priority'] <=> $a['priority'];
  158. });
  159. // 生成学习路径
  160. $learningPath = [];
  161. foreach ($prerequisites as $prereq) {
  162. if (!$prereq['is_ready']) {
  163. $learningPath[] = [
  164. 'type' => 'review',
  165. 'kp_id' => $prereq['kp_id'],
  166. 'reason' => '需要先掌握前置知识点',
  167. 'priority' => $prereq['priority']
  168. ];
  169. }
  170. }
  171. // 添加目标知识点
  172. $learningPath[] = [
  173. 'type' => 'learn',
  174. 'kp_id' => $targetKp,
  175. 'reason' => '学习目标知识点',
  176. 'priority' => 100
  177. ];
  178. return [
  179. 'success' => true,
  180. 'data' => [
  181. 'student_id' => $studentId,
  182. 'target_kp' => $targetKp,
  183. 'learning_path' => $learningPath,
  184. 'total_steps' => count($learningPath),
  185. 'estimated_hours' => count($learningPath) * 2 // 假设每个知识点需要2小时
  186. ]
  187. ];
  188. } catch (\Exception $e) {
  189. \Log::error('获取学习路径失败', [
  190. 'student_id' => $studentId,
  191. 'target_kp' => $targetKp,
  192. 'error' => $e->getMessage()
  193. ]);
  194. return [
  195. 'success' => false,
  196. 'error' => $e->getMessage()
  197. ];
  198. }
  199. }
  200. /**
  201. * 格式化节点数据
  202. *
  203. * @param array $nodes 原始节点数据
  204. * @return array
  205. */
  206. private function formatNodes(array $nodes): array
  207. {
  208. return array_map(function ($node) {
  209. $props = $node['properties'] ?? [];
  210. return [
  211. 'id' => $props['uuid'] ?? $props['kp_id'] ?? uniqid(),
  212. 'name' => $props['node_name'] ?? $props['kp_name'] ?? '未知知识点',
  213. 'category' => $props['grade'] ?? $props['grade_label'] ?? '未分类',
  214. 'description' => $props['description'] ?? '',
  215. 'value' => $props['mastery'] ?? 0.6,
  216. 'difficulty' => $props['difficulty'] ?? 0.5,
  217. 'book' => $props['book'] ?? '',
  218. 'chapter' => $props['chapter'] ?? '',
  219. 'keywords' => $props['keywords'] ?? '',
  220. 'uuid' => $props['uuid'] ?? null,
  221. 'kp_id' => $props['kp_id'] ?? null
  222. ];
  223. }, $nodes);
  224. }
  225. /**
  226. * 格式化边数据
  227. *
  228. * @param array $edges 原始边数据
  229. * @return array
  230. */
  231. private function formatEdges(array $edges): array
  232. {
  233. return array_map(function ($edge) {
  234. return [
  235. 'source' => $edge['start_uuid'] ?? $edge['parent_kp'] ?? '',
  236. 'target' => $edge['end_uuid'] ?? $edge['child_kp'] ?? '',
  237. 'type' => $edge['type'] ?? $edge['relation_type'] ?? 'Prerequisite',
  238. 'description' => $edge['properties']['description'] ?? '',
  239. 'strength' => $edge['properties']['strength'] ?? 0.8
  240. ];
  241. }, $edges);
  242. }
  243. /**
  244. * 提取分类
  245. *
  246. * @param array $nodes 节点数据
  247. * @return array
  248. */
  249. private function extractCategories(array $nodes): array
  250. {
  251. $categories = [];
  252. foreach ($nodes as $node) {
  253. $props = $node['properties'] ?? [];
  254. $category = $props['grade'] ?? $props['grade_label'] ?? '未分类';
  255. if (!in_array($category, $categories)) {
  256. $categories[] = $category;
  257. }
  258. }
  259. // 为每个分类分配颜色
  260. return array_map(function ($category, $index) {
  261. return [
  262. 'name' => $category,
  263. 'color' => $this->getCategoryColor($index)
  264. ];
  265. }, $categories, array_keys($categories));
  266. }
  267. /**
  268. * 获取分类颜色
  269. *
  270. * @param int $index 分类索引
  271. * @return string
  272. */
  273. private function getCategoryColor(int $index): string
  274. {
  275. $colors = [
  276. '#3b82f6', // 蓝色
  277. '#10b981', // 绿色
  278. '#f59e0b', // 黄色
  279. '#ef4444', // 红色
  280. '#8b5cf6', // 紫色
  281. '#ec4899', // 粉色
  282. '#06b6d4', // 青色
  283. '#84cc16', // 青柠
  284. ];
  285. return $colors[$index % count($colors)];
  286. }
  287. /**
  288. * 从画像中获取掌握度
  289. *
  290. * @param array $profile 学生画像
  291. * @param string $kpId 知识点ID
  292. * @return float
  293. */
  294. private function getMasteryFromProfile(array $profile, string $kpId): float
  295. {
  296. $masteryData = $profile['data']['mastery'] ?? $profile['mastery'] ?? [];
  297. foreach ($masteryData as $mastery) {
  298. if (($mastery['kp'] ?? $mastery['kp_id'] ?? '') === $kpId) {
  299. return floatval($mastery['level'] ?? $mastery['mastery_level'] ?? 0);
  300. }
  301. }
  302. return 0.0;
  303. }
  304. /**
  305. * 计算优先级
  306. *
  307. * @param float $mastery 掌握度
  308. * @return int
  309. */
  310. private function calculatePriority(float $mastery): int
  311. {
  312. if ($mastery < 0.3) {
  313. return 90; // 急需掌握
  314. } elseif ($mastery < 0.6) {
  315. return 70; // 需要复习
  316. } elseif ($mastery < 0.8) {
  317. return 50; // 适当巩固
  318. } else {
  319. return 10; // 已经掌握
  320. }
  321. }
  322. /**
  323. * 获取相关题目(需要根据实际题库实现)
  324. *
  325. * @param string $kpId 知识点ID
  326. * @return array
  327. */
  328. private function getRelatedQuestions(string $kpId): array
  329. {
  330. // 这里需要实现从本地题库查询相关题目的逻辑
  331. // 暂时返回空数组
  332. return [];
  333. }
  334. }