dsh-math-calculator 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/CHANGELOG.md +221 -0
  2. package/LICENSE +21 -0
  3. package/README.md +454 -3
  4. package/cordis.patch.yml +7 -0
  5. package/dsh.plugin.json +8 -0
  6. package/lib/ai-brief.js +119 -0
  7. package/lib/anchor-solve.js +217 -0
  8. package/lib/api.js +798 -0
  9. package/lib/awareness.js +219 -0
  10. package/lib/back-solve.js +232 -0
  11. package/lib/balance.js +154 -0
  12. package/lib/civilization.js +329 -0
  13. package/lib/climate.js +388 -0
  14. package/lib/compute-budget.js +173 -0
  15. package/lib/consequences.js +342 -0
  16. package/lib/constants-core.js +241 -0
  17. package/lib/constants-graph.js +692 -0
  18. package/lib/custom-constants.js +320 -0
  19. package/lib/dead-universe.js +288 -0
  20. package/lib/derivation-log.js +186 -0
  21. package/lib/derivation-stack.js +471 -0
  22. package/lib/detector.js +237 -0
  23. package/lib/ecosystem.js +231 -0
  24. package/lib/fantasy-layer.js +213 -0
  25. package/lib/feasibility.js +386 -0
  26. package/lib/flip-claims.js +93 -0
  27. package/lib/flip.js +166 -0
  28. package/lib/format.js +217 -0
  29. package/lib/formula-bridge.js +78 -0
  30. package/lib/formula-builtins.js +110 -0
  31. package/lib/formula-library-basic.js +712 -0
  32. package/lib/formula-library-ext.js +1036 -0
  33. package/lib/formula-library-perception.js +593 -0
  34. package/lib/formula-library-power.js +276 -0
  35. package/lib/formula-library-story.js +487 -0
  36. package/lib/formula-library-story2.js +420 -0
  37. package/lib/formula-library.js +1333 -0
  38. package/lib/formula-pack.js +173 -0
  39. package/lib/formula-table.js +221 -0
  40. package/lib/formulas.js +475 -0
  41. package/lib/graph-layout.js +172 -0
  42. package/lib/graph-render.js +136 -0
  43. package/lib/heatmap.js +93 -0
  44. package/lib/impact.js +326 -0
  45. package/lib/index.js +2408 -0
  46. package/lib/integration.js +145 -0
  47. package/lib/life.js +172 -0
  48. package/lib/moons.js +221 -0
  49. package/lib/numeric.js +282 -0
  50. package/lib/observer.js +187 -0
  51. package/lib/ode.js +320 -0
  52. package/lib/ops/balance-op.js +141 -0
  53. package/lib/ops/constants-op.js +278 -0
  54. package/lib/ops/custom-op.js +191 -0
  55. package/lib/ops/derivation-op.js +710 -0
  56. package/lib/ops/feasibility-op.js +160 -0
  57. package/lib/ops/formula-table-op.js +261 -0
  58. package/lib/ops/impact-op.js +150 -0
  59. package/lib/ops/ode-op.js +113 -0
  60. package/lib/ops/quantities-op.js +176 -0
  61. package/lib/ops/shared.js +168 -0
  62. package/lib/ops/units-op.js +227 -0
  63. package/lib/ops/workspace-op.js +341 -0
  64. package/lib/ops/world-op.js +301 -0
  65. package/lib/pipeline.js +304 -0
  66. package/lib/playbook.js +352 -0
  67. package/lib/provenance-graph.js +262 -0
  68. package/lib/provenance.js +152 -0
  69. package/lib/quantities.js +530 -0
  70. package/lib/sky.js +348 -0
  71. package/lib/star-catalog.js +120 -0
  72. package/lib/stats.js +373 -0
  73. package/lib/stellar.js +175 -0
  74. package/lib/summary.js +225 -0
  75. package/lib/symbolic.js +264 -0
  76. package/lib/symbols.js +190 -0
  77. package/lib/systems.js +280 -0
  78. package/lib/taxonomy.js +278 -0
  79. package/lib/terrain.js +350 -0
  80. package/lib/timeline.js +244 -0
  81. package/lib/types/ai-brief.d.ts +72 -0
  82. package/lib/types/anchor-solve.d.ts +67 -0
  83. package/lib/types/api.d.ts +75 -0
  84. package/lib/types/awareness.d.ts +53 -0
  85. package/lib/types/back-solve.d.ts +70 -0
  86. package/lib/types/balance.d.ts +94 -0
  87. package/lib/types/civilization.d.ts +98 -0
  88. package/lib/types/client.d.ts +353 -0
  89. package/lib/types/climate.d.ts +256 -0
  90. package/lib/types/compute-budget.d.ts +103 -0
  91. package/lib/types/consequences.d.ts +49 -0
  92. package/lib/types/constants-core.d.ts +125 -0
  93. package/lib/types/constants-graph.d.ts +122 -0
  94. package/lib/types/custom-constants.d.ts +136 -0
  95. package/lib/types/dead-universe.d.ts +80 -0
  96. package/lib/types/derivation-log.d.ts +110 -0
  97. package/lib/types/derivation-stack.d.ts +191 -0
  98. package/lib/types/detector.d.ts +87 -0
  99. package/lib/types/ecosystem.d.ts +140 -0
  100. package/lib/types/fantasy-layer.d.ts +145 -0
  101. package/lib/types/feasibility.d.ts +136 -0
  102. package/lib/types/flip-claims.d.ts +51 -0
  103. package/lib/types/flip.d.ts +81 -0
  104. package/lib/types/format.d.ts +41 -0
  105. package/lib/types/formula-bridge.d.ts +51 -0
  106. package/lib/types/formula-builtins.d.ts +29 -0
  107. package/lib/types/formula-library-basic.d.ts +31 -0
  108. package/lib/types/formula-library-ext.d.ts +18 -0
  109. package/lib/types/formula-library-perception.d.ts +25 -0
  110. package/lib/types/formula-library-power.d.ts +37 -0
  111. package/lib/types/formula-library-story.d.ts +19 -0
  112. package/lib/types/formula-library-story2.d.ts +16 -0
  113. package/lib/types/formula-library.d.ts +65 -0
  114. package/lib/types/formula-pack.d.ts +65 -0
  115. package/lib/types/formula-table.d.ts +96 -0
  116. package/lib/types/formulas.d.ts +100 -0
  117. package/lib/types/graph-layout.d.ts +82 -0
  118. package/lib/types/graph-render.d.ts +68 -0
  119. package/lib/types/heatmap.d.ts +91 -0
  120. package/lib/types/impact.d.ts +89 -0
  121. package/lib/types/index.d.ts +95 -0
  122. package/lib/types/integration.d.ts +69 -0
  123. package/lib/types/life.d.ts +91 -0
  124. package/lib/types/moons.d.ts +103 -0
  125. package/lib/types/numeric.d.ts +61 -0
  126. package/lib/types/observer.d.ts +104 -0
  127. package/lib/types/ode.d.ts +104 -0
  128. package/lib/types/ops/balance-op.d.ts +26 -0
  129. package/lib/types/ops/constants-op.d.ts +16 -0
  130. package/lib/types/ops/custom-op.d.ts +19 -0
  131. package/lib/types/ops/derivation-op.d.ts +31 -0
  132. package/lib/types/ops/feasibility-op.d.ts +19 -0
  133. package/lib/types/ops/formula-table-op.d.ts +16 -0
  134. package/lib/types/ops/impact-op.d.ts +15 -0
  135. package/lib/types/ops/ode-op.d.ts +16 -0
  136. package/lib/types/ops/quantities-op.d.ts +22 -0
  137. package/lib/types/ops/shared.d.ts +334 -0
  138. package/lib/types/ops/units-op.d.ts +31 -0
  139. package/lib/types/ops/workspace-op.d.ts +20 -0
  140. package/lib/types/ops/world-op.d.ts +15 -0
  141. package/lib/types/pipeline.d.ts +69 -0
  142. package/lib/types/playbook.d.ts +157 -0
  143. package/lib/types/provenance-graph.d.ts +101 -0
  144. package/lib/types/provenance.d.ts +41 -0
  145. package/lib/types/quantities.d.ts +117 -0
  146. package/lib/types/sky.d.ts +137 -0
  147. package/lib/types/star-catalog.d.ts +57 -0
  148. package/lib/types/stats.d.ts +95 -0
  149. package/lib/types/stellar.d.ts +69 -0
  150. package/lib/types/summary.d.ts +75 -0
  151. package/lib/types/symbolic.d.ts +58 -0
  152. package/lib/types/symbols.d.ts +67 -0
  153. package/lib/types/systems.d.ts +41 -0
  154. package/lib/types/taxonomy.d.ts +75 -0
  155. package/lib/types/terrain.d.ts +95 -0
  156. package/lib/types/timeline.d.ts +156 -0
  157. package/lib/types/units.d.ts +115 -0
  158. package/lib/types/universe-ops.d.ts +143 -0
  159. package/lib/types/whitepaper.d.ts +106 -0
  160. package/lib/types/workspace.d.ts +315 -0
  161. package/lib/types/world-params.d.ts +111 -0
  162. package/lib/types/world-validation.d.ts +74 -0
  163. package/lib/types/world.d.ts +255 -0
  164. package/lib/units.js +294 -0
  165. package/lib/universe-ops.js +209 -0
  166. package/lib/whitepaper.js +219 -0
  167. package/lib/workspace.js +741 -0
  168. package/lib/world-params.js +369 -0
  169. package/lib/world-validation.js +296 -0
  170. package/lib/world.js +608 -0
  171. package/package.json +94 -4
  172. package/src/ai-brief.ts +141 -0
  173. package/src/algebrite.d.ts +19 -0
  174. package/src/anchor-solve.ts +262 -0
  175. package/src/api.ts +885 -0
  176. package/src/awareness.ts +240 -0
  177. package/src/back-solve.ts +274 -0
  178. package/src/balance.ts +205 -0
  179. package/src/civilization.ts +385 -0
  180. package/src/climate.ts +586 -0
  181. package/src/compute-budget.ts +204 -0
  182. package/src/consequences.ts +401 -0
  183. package/src/constants-core.ts +336 -0
  184. package/src/constants-graph.ts +772 -0
  185. package/src/custom-constants.ts +389 -0
  186. package/src/dead-universe.ts +328 -0
  187. package/src/derivation-log.ts +257 -0
  188. package/src/derivation-stack.ts +600 -0
  189. package/src/detector.ts +296 -0
  190. package/src/ecosystem.ts +271 -0
  191. package/src/fantasy-layer.ts +295 -0
  192. package/src/feasibility.ts +519 -0
  193. package/src/flip-claims.ts +119 -0
  194. package/src/flip.ts +210 -0
  195. package/src/format.ts +203 -0
  196. package/src/formula-bridge.ts +92 -0
  197. package/src/formula-builtins.ts +108 -0
  198. package/src/formula-library-basic.ts +747 -0
  199. package/src/formula-library-ext.ts +1048 -0
  200. package/src/formula-library-perception.ts +604 -0
  201. package/src/formula-library-power.ts +297 -0
  202. package/src/formula-library-story.ts +496 -0
  203. package/src/formula-library-story2.ts +428 -0
  204. package/src/formula-library.ts +1396 -0
  205. package/src/formula-pack.ts +189 -0
  206. package/src/formula-table.ts +277 -0
  207. package/src/formulas.ts +494 -0
  208. package/src/graph-layout.ts +209 -0
  209. package/src/graph-render.ts +158 -0
  210. package/src/heatmap.ts +139 -0
  211. package/src/impact.ts +393 -0
  212. package/src/index.ts +2679 -0
  213. package/src/integration.ts +198 -0
  214. package/src/life.ts +233 -0
  215. package/src/moons.ts +341 -0
  216. package/src/numeric.ts +268 -0
  217. package/src/observer.ts +245 -0
  218. package/src/ode.ts +415 -0
  219. package/src/ops/balance-op.ts +170 -0
  220. package/src/ops/constants-op.ts +324 -0
  221. package/src/ops/custom-op.ts +188 -0
  222. package/src/ops/derivation-op.ts +677 -0
  223. package/src/ops/feasibility-op.ts +174 -0
  224. package/src/ops/formula-table-op.ts +309 -0
  225. package/src/ops/impact-op.ts +166 -0
  226. package/src/ops/ode-op.ts +127 -0
  227. package/src/ops/quantities-op.ts +178 -0
  228. package/src/ops/shared.ts +483 -0
  229. package/src/ops/units-op.ts +261 -0
  230. package/src/ops/workspace-op.ts +392 -0
  231. package/src/ops/world-op.ts +333 -0
  232. package/src/pipeline.ts +386 -0
  233. package/src/playbook.ts +424 -0
  234. package/src/provenance-graph.ts +297 -0
  235. package/src/provenance.ts +176 -0
  236. package/src/quantities.ts +617 -0
  237. package/src/sky.ts +465 -0
  238. package/src/star-catalog.ts +241 -0
  239. package/src/stats.ts +409 -0
  240. package/src/stellar.ts +227 -0
  241. package/src/summary.ts +275 -0
  242. package/src/symbolic.ts +279 -0
  243. package/src/symbols.ts +216 -0
  244. package/src/systems.ts +320 -0
  245. package/src/taxonomy.ts +312 -0
  246. package/src/terrain.ts +461 -0
  247. package/src/timeline.ts +315 -0
  248. package/src/units.ts +353 -0
  249. package/src/universe-ops.ts +283 -0
  250. package/src/whitepaper.ts +278 -0
  251. package/src/workspace.ts +877 -0
  252. package/src/world-params.ts +440 -0
  253. package/src/world-validation.ts +314 -0
  254. package/src/world.ts +941 -0
package/lib/summary.js ADDED
@@ -0,0 +1,225 @@
1
+ /**
2
+ * 综合推演:一次请求拿到界面需要的全部结论。
3
+ *
4
+ * @module dsh-math-calculator/summary
5
+ * @description
6
+ * ## 为什么要有这个
7
+ *
8
+ * 界面改一个参数后要同时更新四样东西:派生量、生物、文明、能不能住。
9
+ * 分四次请求既慢、又容易不同步(第 2 次算完时参数可能已经被改了)。
10
+ * 所以做成一次调用、一次快照。
11
+ *
12
+ * 实测总耗时 2.1 ms——够实时。
13
+ *
14
+ * ## 分层原则
15
+ *
16
+ * 返回结构严格区分三层:
17
+ * · `params` —— 基础量(用户能改的,原样回显)
18
+ * · `derived` —— 派生量(只读,由 params 算出)
19
+ * · `impact` —— 结论(生物 / 文明 / 环境)
20
+ *
21
+ * 界面**绝不允许**把 derived 写回 params——那会破坏体系自洽。
22
+ */
23
+ import { opWorld } from './ops/world-op.js';
24
+ import { judgeDead } from './dead-universe.js';
25
+ import { runCivilization } from './civilization.js';
26
+ import { ecosystemFromWorld } from './ecosystem.js';
27
+ import { CONSTRAINTS, deriveConstraintContext } from './feasibility.js';
28
+ import { paramsByGroup, WORLD_PARAMS } from './world-params.js';
29
+ /**
30
+ * 把数字格式化成好读的串。
31
+ *
32
+ * @param value - 数值
33
+ * @param digits - 有效位数
34
+ * @returns 显示串
35
+ */
36
+ function fmt(value, digits = 3) {
37
+ if (!Number.isFinite(value))
38
+ return '—';
39
+ const abs = Math.abs(value);
40
+ if (abs >= 1e6 || (abs < 1e-2 && abs > 0))
41
+ return value.toExponential(2);
42
+ return Number(value.toPrecision(digits)).toString();
43
+ }
44
+ /**
45
+ * 把不可用的数字归一化为 `undefined`。
46
+ *
47
+ * 为什么需要:`JSON.stringify(Infinity)` 得到 `null`,但把 `Infinity` 原样放进
48
+ * 对象里,前端/AI 读到的可能是字符串 `"Infinity"`(取决于序列化路径)。
49
+ * 实测 `planetRadius=0` 时 `derived[0].value` 就是 `"Infinity"`,
50
+ * 而只有 `text` 被 `fmt()` 格式化成了 `—`。两个字段不一致会误导消费方。
51
+ *
52
+ * @param value - 原始值(可能来自显示串,也可能是数字)
53
+ * @returns 有限数原样返回,否则 `undefined`
54
+ */
55
+ function finite(value) {
56
+ if (typeof value === 'number')
57
+ return Number.isFinite(value) ? value : undefined;
58
+ if (typeof value === 'string') {
59
+ const num = Number(value);
60
+ return Number.isFinite(num) ? num : undefined;
61
+ }
62
+ return undefined;
63
+ }
64
+ /**
65
+ * 一次算出界面上要显示的全部内容。
66
+ *
67
+ * @param params - 基础量(只认白名单里的键)
68
+ * @returns 综合结果
69
+ */
70
+ export function deriveAll(params = {}) {
71
+ // 只保留白名单里的键——防止派生量或垃圾字段混进来。
72
+ // 这是「派生量绝不入库」的实现点:即使调用方硬塞 gravity,也会被丢弃。
73
+ const allowed = new Set(WORLD_PARAMS.map(function (item) { return item.key; }));
74
+ const clean = {};
75
+ for (const [key, value] of Object.entries(params)) {
76
+ if (!allowed.has(key))
77
+ continue;
78
+ if (value === undefined || value === null || value === '')
79
+ continue;
80
+ clean[key] = value;
81
+ }
82
+ const world = opWorld({ world: clean }, 32).value || {};
83
+ const planet = world.planet || {};
84
+ const orbit = world.orbit || {};
85
+ const temp = world.temperature || {};
86
+ const atm = world.atmosphere || {};
87
+ const stellar = world.stellar || {};
88
+ const gravity = finite(planet.surfaceGravity) ?? 0;
89
+ const radiusM = finite(planet.radiusM) ?? 6.371e6;
90
+ const escapeVelocity = Math.sqrt(2 * gravity * radiusM);
91
+ // ── 派生量:全部现算,一个都不存 ──
92
+ // value 一律过 finite():参数不合法时会算出 Infinity/NaN,
93
+ // 原样给出去会被 AI 当成真数字写进结语(见 test/sanity.mjs)。
94
+ const derived = [
95
+ {
96
+ key: 'gravity',
97
+ label: '表面重力',
98
+ value: gravity,
99
+ unit: 'm/s²',
100
+ text: fmt(gravity) + ' m/s²(' + fmt(finite(planet.surfaceGravityEarth) ?? 0, 2) + ' g)',
101
+ },
102
+ {
103
+ key: 'escapeVelocity',
104
+ label: '逃逸速度',
105
+ value: escapeVelocity,
106
+ unit: 'km/s',
107
+ text: fmt(escapeVelocity / 1000) + ' km/s',
108
+ },
109
+ {
110
+ key: 'dayHours',
111
+ label: '一天',
112
+ value: finite(planet.dayHours) ?? 0,
113
+ unit: '小时',
114
+ text: fmt(finite(planet.dayHours) ?? 0) + ' 小时',
115
+ },
116
+ {
117
+ key: 'yearDays',
118
+ label: '一年',
119
+ value: finite(orbit.yearDays) ?? 0,
120
+ unit: '天',
121
+ text: fmt(finite(orbit.yearDays) ?? 0) + ' 天',
122
+ },
123
+ {
124
+ key: 'meanTemp',
125
+ label: '年均温',
126
+ value: finite(temp.surfaceMeanK) ?? 0,
127
+ unit: 'K',
128
+ text: fmt(finite(temp.surfaceMeanK) ?? 0) + ' K(' + fmt((finite(temp.surfaceMeanK) ?? 0) - 273.15) + ' °C)',
129
+ },
130
+ {
131
+ key: 'scaleHeight',
132
+ label: '大气标高',
133
+ value: finite(atm.scaleHeightM) ?? 0,
134
+ unit: 'm',
135
+ text: fmt(finite(atm.scaleHeightM) ?? 0) + ' m',
136
+ },
137
+ {
138
+ key: 'starLifetime',
139
+ label: '恒星寿命',
140
+ value: finite(stellar.lifetimeGyr) ?? 0,
141
+ unit: 'Gyr',
142
+ text: fmt(finite(stellar.lifetimeGyr) ?? 0) + ' Gyr(' + fmt((finite(stellar.lifetimeGyr) ?? 0) * 10) + ' 亿年)',
143
+ },
144
+ ];
145
+ // ── 生物:复用 feasibility,不重写物理 ──
146
+ const ctx = deriveConstraintContext(clean);
147
+ const biology = CONSTRAINTS
148
+ .filter(function (item) { return item.category === 'biology'; })
149
+ .map(function (item) {
150
+ const limit = item.limit(ctx);
151
+ return {
152
+ label: item.name,
153
+ value: fmt(limit) + ' ' + item.unit,
154
+ note: item.formula,
155
+ };
156
+ });
157
+ // ── 文明 ──
158
+ const civ = runCivilization(clean);
159
+ const eco = ecosystemFromWorld(world);
160
+ const civilization = [];
161
+ for (const item of civ.limits) {
162
+ if (item.category !== 'material' && item.category !== 'transport')
163
+ continue;
164
+ if (item.name === '逃逸速度' || item.name === '第一宇宙速度')
165
+ continue;
166
+ civilization.push({ label: item.name, value: fmt(item.value) + ' ' + item.unit, note: item.basis });
167
+ }
168
+ civilization.push({
169
+ label: '生态承载力',
170
+ value: fmt(eco.carryingCapacity / 1e8) + ' 亿人',
171
+ note: eco.note,
172
+ });
173
+ for (const tech of civ.tech) {
174
+ civilization.push({
175
+ label: tech.branch,
176
+ value: tech.status === 'open' ? '✓ 可行' : tech.status === 'conditional' ? '△ 有条件' : '✗ 被锁死',
177
+ note: tech.reason,
178
+ });
179
+ }
180
+ // ── 环境与可居住性 ──
181
+ const dead = judgeDead(world);
182
+ const environment = [];
183
+ environment.push({
184
+ label: '能不能住人',
185
+ value: dead.level === 'alive' ? '✓ 可以' : dead.level === 'marginal' ? '△ 勉强' : '✗ 不行',
186
+ note: dead.summary,
187
+ });
188
+ if (temp.surfaceMeanK !== undefined) {
189
+ environment.push({
190
+ label: '地表均温',
191
+ value: fmt(temp.surfaceMeanK) + ' K',
192
+ note: temp.surfaceMeanK > 273.15 ? '高于冰点,可能有液态水' : '低于冰点,水会冻住',
193
+ });
194
+ }
195
+ if (atm.pressureAtm !== undefined) {
196
+ environment.push({
197
+ label: '气压',
198
+ value: fmt(atm.pressureAtm) + ' atm',
199
+ note: atm.pressureAtm < 0.5 ? '很稀薄,难以呼吸'
200
+ : atm.pressureAtm > 3 ? '高压,呼吸阻力大' : '接近地球,可呼吸',
201
+ });
202
+ }
203
+ environment.push({
204
+ label: '一天',
205
+ value: fmt(planet.dayHours || 0) + ' 小时',
206
+ note: (planet.dayHours || 24) < 12 ? '自转快,风暴强'
207
+ : (planet.dayHours || 24) > 48 ? '自转慢,昼夜温差大' : '与地球相当',
208
+ });
209
+ const headline = '重力 ' + fmt(planet.surfaceGravityEarth || 0, 2) + ' g、一天 ' +
210
+ fmt(planet.dayHours || 0) + ' 小时、均温 ' + fmt(temp.surfaceMeanK || 0) + ' K 的世界';
211
+ return {
212
+ params: clean,
213
+ paramGroups: paramsByGroup(),
214
+ derived: derived,
215
+ biology: biology,
216
+ civilization: civilization,
217
+ environment: environment,
218
+ verdict: {
219
+ level: dead.level,
220
+ summary: dead.summary,
221
+ causes: dead.causes.map(function (cause) { return cause.name + ':' + cause.value; }),
222
+ },
223
+ headline: headline,
224
+ };
225
+ }
@@ -0,0 +1,264 @@
1
+ /**
2
+ * 符号代数:包一层 Algebrite。
3
+ *
4
+ * 为什么需要它:mathjs 只有 `derivative`,**没有符号积分**
5
+ * (`math.integrate` 是 undefined)。Algebrite 是纯 JS 的 CAS,
6
+ * 能给出 `∫x^2 = 1/3*x^3`、`∫sin(x) = -cos(x)` 这样的符号解。
7
+ *
8
+ * 能力边界(实测):
9
+ * 能:x^2、sin(x)、1/x、ln(x)、tan(x)、x*exp(x)、cos(x)^2、sqrt(1-x^2)、exp(-x^2)
10
+ * 不能:x^3*sin(x)(返回 "could not find a solution")
11
+ *
12
+ * 安全性:Algebrite 的 `eval` 是**符号求值**,不是 JS 求值。
13
+ * `A.eval('Math.abs(-1)')` 返回符号串 `NaN...*Math`,不会执行 JS。
14
+ * 仍然在入口做标识符黑名单,避免把可疑输入喂给它的解析器。
15
+ *
16
+ * @module dsh-math-calculator/symbolic
17
+ */
18
+ import algebrite from 'algebrite';
19
+ /** Algebrite 的 CJS 默认导出在不同构建下形状不同,统一取一次。 */
20
+ const A = algebrite?.default ?? algebrite;
21
+ /** 禁用标识符:JS 全局对象/函数名,出现即拒绝。 */
22
+ const FORBIDDEN_IDENTIFIERS = [
23
+ 'process',
24
+ 'require',
25
+ 'globalThis',
26
+ 'global',
27
+ 'module',
28
+ 'exports',
29
+ 'Function',
30
+ 'eval',
31
+ 'constructor',
32
+ 'prototype',
33
+ '__proto__',
34
+ 'import',
35
+ ];
36
+ /** 符号表达式长度上限。 */
37
+ const MAX_SYMBOLIC_LENGTH = 2_000;
38
+ /** 符号求值失败。 */
39
+ export class SymbolicError extends Error {
40
+ stage;
41
+ constructor(stage, message) {
42
+ super(message);
43
+ this.name = 'SymbolicError';
44
+ this.stage = stage;
45
+ }
46
+ }
47
+ /** 入口校验:长度 + 黑名单标识符。 */
48
+ function guard(source, stage) {
49
+ if (typeof source !== 'string') {
50
+ throw new SymbolicError(stage, '表达式必须是字符串');
51
+ }
52
+ const text = source.trim();
53
+ if (text === '')
54
+ throw new SymbolicError(stage, '表达式为空');
55
+ if (text.length > MAX_SYMBOLIC_LENGTH) {
56
+ throw new SymbolicError(stage, `表达式过长(${text.length} > ${MAX_SYMBOLIC_LENGTH})`);
57
+ }
58
+ for (const identifier of FORBIDDEN_IDENTIFIERS) {
59
+ const pattern = new RegExp(`(^|[^A-Za-z0-9_$])${identifier}([^A-Za-z0-9_$]|$)`);
60
+ if (pattern.test(text)) {
61
+ throw new SymbolicError(stage, `不允许使用标识符 "${identifier}"`);
62
+ }
63
+ }
64
+ return text;
65
+ }
66
+ /** 把 Algebrite 的 `1/3*x^3` 转成更易读的 `x^3/3` 形态(尽力而为,不改变语义)。 */
67
+ function tidy(expression) {
68
+ return expression
69
+ .replace(/\s+/g, ' ')
70
+ .replace(/\s*\*\s*/g, '*')
71
+ .replace(/\s*\+\s*/g, ' + ')
72
+ .replace(/\s*-\s*/g, ' - ')
73
+ .replace(/\s*\^\s*/g, '^')
74
+ .trim();
75
+ }
76
+ /**
77
+ * 符号求导:优先 Algebrite(能化简),失败退回 mathjs。
78
+ */
79
+ export function symbolicDerivative(expression, variable) {
80
+ const text = guard(expression, 'derivative');
81
+ try {
82
+ const result = A.derivative(text, variable);
83
+ const output = tidy(String(result));
84
+ if (output && output !== 'Stop')
85
+ return output;
86
+ }
87
+ catch {
88
+ /* 退回下面的 mathjs */
89
+ }
90
+ throw new SymbolicError('derivative', `无法对 "${text}" 求导`);
91
+ }
92
+ /**
93
+ * 符号积分(不定积分)。
94
+ * 这是 Algebrite 相对 mathjs 的核心增量能力。
95
+ */
96
+ export function symbolicIntegral(expression, variable) {
97
+ const text = guard(expression, 'integral');
98
+ let raw;
99
+ try {
100
+ raw = String(A.integral(text, variable));
101
+ }
102
+ catch (error) {
103
+ const detail = error instanceof Error ? error.message : String(error);
104
+ if (/could not find a solution/i.test(detail)) {
105
+ throw new SymbolicError('integral', `符号积分引擎无法求出 "${text}" 的原函数`);
106
+ }
107
+ throw new SymbolicError('integral', `积分失败: ${detail}`);
108
+ }
109
+ const output = tidy(raw);
110
+ if (!output || /^Stop\b/.test(output)) {
111
+ throw new SymbolicError('integral', `符号积分引擎无法求出 "${text}" 的原函数`);
112
+ }
113
+ return output;
114
+ }
115
+ /** 符号化简。 */
116
+ export function symbolicSimplify(expression) {
117
+ const text = guard(expression, 'simplify');
118
+ try {
119
+ return tidy(String(A.simplify(text)));
120
+ }
121
+ catch (error) {
122
+ throw new SymbolicError('simplify', `化简失败: ${error instanceof Error ? error.message : String(error)}`);
123
+ }
124
+ }
125
+ /** 符号展开。 */
126
+ export function symbolicExpand(expression) {
127
+ const text = guard(expression, 'expand');
128
+ try {
129
+ return tidy(String(A.expand(text)));
130
+ }
131
+ catch (error) {
132
+ throw new SymbolicError('expand', `展开失败: ${error instanceof Error ? error.message : String(error)}`);
133
+ }
134
+ }
135
+ /**
136
+ * 把符号表达式转成复数。
137
+ *
138
+ * 关键坑:Algebrite 的 `float()` 输出带**省略号**,例如
139
+ * `-0.5-0.866025...*i`
140
+ * 那是显示截断,不是合法数字。正则必须容忍 `...` 并把它去掉。
141
+ */
142
+ function toComplex(symbolic) {
143
+ let floated;
144
+ try {
145
+ floated = String(A.float(symbolic));
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ // 去掉空白与 float() 的截断省略号
151
+ const text = floated.replace(/\s+/g, '').replace(/\.\.\./g, '');
152
+ // 纯实数
153
+ const plain = Number(text);
154
+ if (Number.isFinite(plain))
155
+ return { re: plain, im: 0 };
156
+ const NUMBER = '-?[\\d.]+(?:e[+-]?\\d+)?';
157
+ // 纯虚:`-i`、`i`、`0.5*i`、`-0.5*i`
158
+ if (text === 'i')
159
+ return { re: 0, im: 1 };
160
+ if (text === '-i')
161
+ return { re: 0, im: -1 };
162
+ const imaginaryOnly = text.match(new RegExp(`^(${NUMBER})\\*?i$`));
163
+ if (imaginaryOnly) {
164
+ const im = Number(imaginaryOnly[1]);
165
+ if (Number.isFinite(im))
166
+ return { re: 0, im };
167
+ }
168
+ // a+bi / a-bi(虚部可带或不带 *)
169
+ const both = text.match(new RegExp(`^(${NUMBER})([+-])(${NUMBER})\\*?i$`));
170
+ if (both) {
171
+ const re = Number(both[1]);
172
+ const im = Number(both[3]) * (both[2] === '-' ? -1 : 1);
173
+ if (Number.isFinite(re) && Number.isFinite(im))
174
+ return { re, im };
175
+ }
176
+ // 只以 i 结尾但形式怪异(如 `0.300000...*i` 已被去点)
177
+ if (text.endsWith('i')) {
178
+ const head = text.slice(0, -1).replace(/\*$/, '');
179
+ const im = Number(head);
180
+ if (Number.isFinite(im))
181
+ return { re: 0, im };
182
+ }
183
+ return undefined;
184
+ }
185
+ /** 按顶层逗号切分(不切断括号内的逗号)。 */
186
+ function splitTopLevel(text) {
187
+ const pieces = [];
188
+ let depth = 0;
189
+ let current = '';
190
+ for (const char of text) {
191
+ if (char === '(' || char === '[')
192
+ depth += 1;
193
+ if (char === ')' || char === ']')
194
+ depth -= 1;
195
+ if (char === ',' && depth === 0) {
196
+ if (current.trim() !== '')
197
+ pieces.push(current.trim());
198
+ current = '';
199
+ continue;
200
+ }
201
+ current += char;
202
+ }
203
+ if (current.trim() !== '')
204
+ pieces.push(current.trim());
205
+ return pieces;
206
+ }
207
+ /** 多项式求根,返回含复数的根。 */
208
+ export function symbolicRootsWithComplex(expression, variable) {
209
+ const text = guard(expression, 'roots');
210
+ let raw;
211
+ try {
212
+ raw = String(A.roots(text, variable));
213
+ }
214
+ catch (error) {
215
+ throw new SymbolicError('roots', `求根失败: ${error instanceof Error ? error.message : String(error)}`);
216
+ }
217
+ const match = raw.match(/^\[([\s\S]*)\]$/);
218
+ if (!match)
219
+ throw new SymbolicError('roots', `无法解析根: ${raw}`);
220
+ const inner = match[1].trim();
221
+ if (inner === '')
222
+ return [];
223
+ const roots = [];
224
+ for (const piece of splitTopLevel(inner)) {
225
+ const complex = toComplex(piece);
226
+ if (complex)
227
+ roots.push(complex);
228
+ }
229
+ return roots;
230
+ }
231
+ /** 多项式求根,只返回实数根。 */
232
+ export function symbolicRoots(expression, variable) {
233
+ return symbolicRootsWithComplex(expression, variable)
234
+ .filter((root) => Math.abs(root.im) < 1e-9)
235
+ .map((root) => root.re);
236
+ }
237
+ /**
238
+ * 把系数数组转成多项式字符串(升幂 → 通常写法)。
239
+ * 用于把矩阵法解出的方程组结果回写成符号形式。
240
+ */
241
+ export function coefficientsToPolynomial(coefficients, variable = 'x') {
242
+ const terms = [];
243
+ for (let power = coefficients.length - 1; power >= 0; power -= 1) {
244
+ const coefficient = coefficients[power];
245
+ if (!Number.isFinite(coefficient) || Math.abs(coefficient) < 1e-15)
246
+ continue;
247
+ const sign = coefficient < 0 ? '-' : '+';
248
+ const magnitude = Math.abs(coefficient);
249
+ let body;
250
+ if (power === 0)
251
+ body = String(magnitude);
252
+ else if (power === 1)
253
+ body = magnitude === 1 ? variable : `${magnitude}*${variable}`;
254
+ else
255
+ body = magnitude === 1 ? `${variable}^${power}` : `${magnitude}*${variable}^${power}`;
256
+ terms.push(`${sign} ${body}`);
257
+ }
258
+ if (terms.length === 0)
259
+ return '0';
260
+ const first = terms[0].replace(/^\+\s*/, '');
261
+ return terms
262
+ .slice(1)
263
+ .reduce((accumulator, term) => `${accumulator} ${term}`, first);
264
+ }
package/lib/symbols.js ADDED
@@ -0,0 +1,190 @@
1
+ /**
2
+ * 符号表:每个符号在不同公式里代表什么物理量。
3
+ *
4
+ * 为什么需要(用户要求):
5
+ * 1. 公式库要能被后来的人或 AI 读懂 —— 光有 id 和表达式不够,
6
+ * 还得知道 m 是质量还是米、T 是温度还是周期;
7
+ * 2. 同一个字母不可避免会被复用(m 可以是质量/米/分钟),
8
+ * 所以要用「符号 + 语境」区分,而不是假装没有冲突。
9
+ *
10
+ * 做法:**从公式本身自动生成**符号索引,而不是手工维护第二份表——
11
+ * 手工表一定会和公式脱节。参数名就是表达式里的符号(m1、r、T…),
12
+ * 单位与概念从参数描述里解析(例如 "质量1 kg" → 概念=质量1,单位=kg)。
13
+ *
14
+ * 消歧语法:`symbol@提示`,例如 `m@质量`、`r@半径`。
15
+ *
16
+ * @module dsh-math-calculator/symbols
17
+ */
18
+ import { FORMULAS } from './formulas.js';
19
+ /** 常见多义符号的人工提示(自动索引之外的补充说明)。 */
20
+ const SYMBOL_NOTES = {
21
+ m: '质量(kg)、米(m)、分钟(min)都可能写作 m —— 看所属公式与单位',
22
+ r: '半径、距离、速率都可能写作 r —— 看单位与公式语境',
23
+ T: '温度(K)、周期(s)、张力(N)都可能写作 T',
24
+ A: '面积(m²)、振幅、安培(A)都可能写作 A',
25
+ V: '体积(m³)、电压(V)、速度都可能写作 V',
26
+ E: '能量(J)、电场强度(V/m)、弹性模量(Pa)都可能写作 E',
27
+ P: '功率(W)、压强(Pa)、周期都可能写作 P',
28
+ L: '长度、角动量、光度(L☉)都可能写作 L',
29
+ R: '半径、电阻(Ω)、气体常数都可能写作 R',
30
+ C: '电容(F)、浓度、热容都可能写作 C',
31
+ N: '力(N)、数量、匝数都可能写作 N',
32
+ K: '开尔文(K)、体积模量、平衡常数都可能写作 K',
33
+ d: '距离、直径、厚度都可能写作 d',
34
+ t: '时间(s)、厚度、温度(口语)都可能写作 t',
35
+ v: '速度(m/s)、比容都可能写作 v',
36
+ a: '加速度(m/s²)、半长轴(m)、面积都可能写作 a',
37
+ };
38
+ /**
39
+ * 单位白名单(从参数描述尾部识别)。
40
+ *
41
+ * 用「按长度倒序的字符串后缀匹配」而不是正则:
42
+ * 单位里有 `/`、`^`、`(` 这些正则元字符,手写正则会不断被转义问题咬到。
43
+ */
44
+ const UNIT_ALIASES = [
45
+ 'J/(kg·K)',
46
+ 'J/(mol·K)',
47
+ 'W/(m·K)',
48
+ 'kg/m^3',
49
+ 'W/m^2',
50
+ 'm/s^2',
51
+ 'kg·m/s',
52
+ 'N·m',
53
+ 'K/km',
54
+ 'm/s',
55
+ 'm^2',
56
+ 'm^3',
57
+ 'GPa',
58
+ 'MPa',
59
+ 'kPa',
60
+ 'eV',
61
+ 'kg',
62
+ 'km',
63
+ 'cm',
64
+ 'mm',
65
+ 'AU',
66
+ 'ly',
67
+ 'pc',
68
+ 'mol',
69
+ 'Pa',
70
+ 'Hz',
71
+ 'rad',
72
+ 'dB',
73
+ 'm',
74
+ 's',
75
+ 'N',
76
+ 'J',
77
+ 'W',
78
+ 'K',
79
+ 'A',
80
+ 'V',
81
+ 'F',
82
+ 'H',
83
+ 'S',
84
+ 'T',
85
+ 'C',
86
+ 'Ω',
87
+ '°',
88
+ '%',
89
+ ];
90
+ /** 按长度倒序(长单位优先,避免 "m/s" 被 "s" 截断)。 */
91
+ const UNIT_BY_LENGTH = [...UNIT_ALIASES].sort((a, b) => b.length - a.length);
92
+ /**
93
+ * 从参数描述里解析「概念 + 单位」。
94
+ * 例:"质量1 kg" → { concept: '质量1', unit: 'kg' }
95
+ * "距离 m" → { concept: '距离', unit: 'm' }
96
+ * "数组" → { concept: '数组', unit: '' }
97
+ */
98
+ export function parseParamDesc(desc) {
99
+ const text = String(desc ?? '').trim();
100
+ for (const unit of UNIT_BY_LENGTH) {
101
+ if (text.endsWith(unit)) {
102
+ const concept = text
103
+ .slice(0, text.length - unit.length)
104
+ .replace(/[\s,,..、::;;\-]+$/g, '')
105
+ .trim();
106
+ return { concept: concept || text, unit };
107
+ }
108
+ }
109
+ return { concept: text, unit: '' };
110
+ }
111
+ /** 构建符号索引:符号 → 全部含义。 */
112
+ export function buildSymbolIndex() {
113
+ const index = new Map();
114
+ for (const formula of FORMULAS) {
115
+ for (const [symbol, spec] of Object.entries(formula.params)) {
116
+ const { concept, unit } = parseParamDesc(spec.desc);
117
+ const meaning = {
118
+ symbol,
119
+ concept,
120
+ unit,
121
+ formulaId: formula.id,
122
+ formulaName: formula.name,
123
+ category: formula.cat,
124
+ };
125
+ const list = index.get(symbol) ?? [];
126
+ if (!list.some((item) => item.formulaId === formula.id))
127
+ list.push(meaning);
128
+ index.set(symbol, list);
129
+ }
130
+ }
131
+ return index;
132
+ }
133
+ /** 某个符号的全部含义。 */
134
+ export function symbolMeanings(symbol) {
135
+ return buildSymbolIndex().get(symbol.trim()) ?? [];
136
+ }
137
+ /**
138
+ * 消歧:按提示过滤含义。提示可以是概念、公式 id、分类或公式名的子串。
139
+ * @param symbol - 符号,如 "m"。
140
+ * @param hint - 语境提示,如 "质量" / "gravitation" / "physics/gravity"。
141
+ */
142
+ export function resolveSymbol(symbol, hint) {
143
+ const all = symbolMeanings(symbol);
144
+ if (!hint || hint.trim() === '')
145
+ return all;
146
+ const text = hint.trim().toLowerCase();
147
+ return all.filter((item) => item.concept.toLowerCase().includes(text) ||
148
+ item.formulaId.toLowerCase().includes(text) ||
149
+ item.formulaName.toLowerCase().includes(text) ||
150
+ item.category.toLowerCase().includes(text) ||
151
+ item.unit.toLowerCase().includes(text));
152
+ }
153
+ /** 多义符号列表:同一符号在不同公式里概念不同。 */
154
+ export function ambiguousSymbols(limit = 40) {
155
+ const out = [];
156
+ for (const [symbol, meanings] of buildSymbolIndex()) {
157
+ const concepts = [...new Set(meanings.map((item) => item.concept))];
158
+ if (concepts.length > 1) {
159
+ out.push({ symbol, count: meanings.length, concepts: concepts.slice(0, 6), note: SYMBOL_NOTES[symbol] });
160
+ }
161
+ }
162
+ return out.sort((a, b) => b.count - a.count).slice(0, limit);
163
+ }
164
+ /** 生成给 AI/人看的符号说明(逐行)。 */
165
+ export function explainSymbol(symbol, hint) {
166
+ const matches = resolveSymbol(symbol, hint);
167
+ const note = SYMBOL_NOTES[symbol];
168
+ const lines = [];
169
+ if (matches.length === 0) {
170
+ lines.push(`没有找到符号 "${symbol}"${hint ? `(提示:${hint})` : ''}。`);
171
+ return lines;
172
+ }
173
+ lines.push(`符号 "${symbol}" 在 ${matches.length} 条公式里出现${hint ? `(已按 "${hint}" 过滤)` : ''}:`);
174
+ for (const item of matches.slice(0, 20)) {
175
+ lines.push(` · ${item.formulaId}(${item.formulaName}):${item.concept}${item.unit ? ` [${item.unit}]` : ''}`);
176
+ }
177
+ if (matches.length > 20)
178
+ lines.push(` …还有 ${matches.length - 20} 条`);
179
+ if (note)
180
+ lines.push(`提示:${note}`);
181
+ lines.push('用法:query="symbol:m@质量" 可缩到具体含义。');
182
+ return lines;
183
+ }
184
+ /** 给公式参数补上符号元数据(供展示/JSON 用)。 */
185
+ export function annotateFormula(formula) {
186
+ return Object.entries(formula.params).map(([symbol, spec]) => {
187
+ const { concept, unit } = parseParamDesc(spec.desc);
188
+ return { symbol, concept, unit, defaultValue: spec.value };
189
+ });
190
+ }