dsh-math-calculator 2.3.2 → 2.3.4
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.
- package/CHANGELOG.md +192 -0
- package/dsh.plugin.json +1 -1
- package/lib/help.js +547 -184
- package/lib/index.js +190 -35
- package/lib/ode.js +34 -0
- package/lib/ops/ode-op.js +42 -1
- package/lib/ops/recurrence-op.js +222 -0
- package/lib/ops/shared.js +19 -0
- package/lib/types/help.d.ts +15 -1
- package/lib/types/ode.d.ts +17 -0
- package/lib/types/ops/recurrence-op.d.ts +44 -0
- package/lib/types/ops/shared.d.ts +22 -1
- package/lib/units-data.js +29 -6
- package/package.json +1 -1
- package/src/help.ts +561 -186
- package/src/index.ts +190 -35
- package/src/ode.ts +46 -0
- package/src/ops/ode-op.ts +43 -1
- package/src/ops/recurrence-op.ts +215 -0
- package/src/ops/shared.ts +33 -0
- package/src/units-data.ts +29 -6
package/src/index.ts
CHANGED
|
@@ -208,6 +208,7 @@ import {
|
|
|
208
208
|
setDisplayPrecisionExplicit,
|
|
209
209
|
} from './precision-report.js'
|
|
210
210
|
import { opOde } from './ops/ode-op.js'
|
|
211
|
+
import { opRecurrence } from './ops/recurrence-op.js'
|
|
211
212
|
import { opWorld } from './ops/world-op.js'
|
|
212
213
|
import { opConstants } from './ops/constants-op.js'
|
|
213
214
|
import { opWorkspace } from './ops/workspace-op.js'
|
|
@@ -349,6 +350,7 @@ const OPERATIONS: readonly MathOperation[] = [
|
|
|
349
350
|
'formula',
|
|
350
351
|
'formulas',
|
|
351
352
|
'ode',
|
|
353
|
+
'recurrence',
|
|
352
354
|
'world',
|
|
353
355
|
'constants',
|
|
354
356
|
'workspace',
|
|
@@ -2677,6 +2679,25 @@ function formaliveUnitOf(formula: FormulaDef, name: string): string {
|
|
|
2677
2679
|
return unitFromDescription(spec.desc, (name) => { try { return findUnit(name) !== undefined } catch { return false } })
|
|
2678
2680
|
}
|
|
2679
2681
|
function opFormula(args: MathArgs, engine: any, precision: number): Outcome {
|
|
2682
|
+
/**
|
|
2683
|
+
* ## 批量调公式:`formulas: [...]`(结构性不足文档第四节)
|
|
2684
|
+
*
|
|
2685
|
+
* 实测反馈:「需要对 22 条公式做批量调用,但 `formula` 不支持 expressions 数组,
|
|
2686
|
+
* 每次只能手动拆成单条 evaluate,等于放弃了公式库的全部价值。」
|
|
2687
|
+
*
|
|
2688
|
+
* 这不是「再开一个 operation」,而是**同一条公式的 N 次调用**——
|
|
2689
|
+
* 所以做成 `formula` 的数组入参,语义与单个调用完全一致(含 unitFrom/unitTo/terse)。
|
|
2690
|
+
*
|
|
2691
|
+
* 元素两种写法:
|
|
2692
|
+
* · 字符串 "kleiber"
|
|
2693
|
+
* · 对象 {formula:"kleiber", overrides:{m:100}, label:"鼠"}
|
|
2694
|
+
*
|
|
2695
|
+
* ★ 一条失败不影响其它条 —— 与 `evaluate` 的 expressions 同一条纪律:
|
|
2696
|
+
* 批量是「多条独立查询」,不是「一个事务」。汇总里会如实报 failed 条数。
|
|
2697
|
+
*/
|
|
2698
|
+
if (Array.isArray((args as any).formulas) && (args as any).formulas.length > 0) {
|
|
2699
|
+
return opFormulaBatch(args, engine, precision)
|
|
2700
|
+
}
|
|
2680
2701
|
const query = (args.formula ?? args.expression ?? '').trim()
|
|
2681
2702
|
if (query === '') {
|
|
2682
2703
|
throw new CalcError('invalid_argument', '需要 formula 参数', '传公式 id 或名称,例如 "escape_velocity"、"逃逸速度"。用 operation="formulas" 检索。')
|
|
@@ -3211,10 +3232,12 @@ const KNOWN_ARGUMENT_KEYS: ReadonlySet<string> = new Set<string>([
|
|
|
3211
3232
|
'matrix', 'vector', 'precision', 'displayPrecision',
|
|
3212
3233
|
// 数据与统计
|
|
3213
3234
|
'data', 'dataY', 'distribution', 'params', 'x', 'degree',
|
|
3214
|
-
//
|
|
3215
|
-
'formula', 'overrides', 'query', 'customExpression',
|
|
3216
|
-
// 微分方程 /
|
|
3217
|
-
'initial', 'from', 'to', 'steps', 'samples',
|
|
3235
|
+
// 公式(formulas 是批量,一次算多条)
|
|
3236
|
+
'formula', 'formulas', 'overrides', 'query', 'customExpression',
|
|
3237
|
+
// 微分方程 / 物理(at 是 ode 的指定采样时点)
|
|
3238
|
+
'initial', 'from', 'to', 'steps', 'samples', 'at',
|
|
3239
|
+
// 离散递推
|
|
3240
|
+
'recurrence', 'periods',
|
|
3218
3241
|
// 星球与推演
|
|
3219
3242
|
'world', 'terrain', 'constants', 'derivation', 'layer',
|
|
3220
3243
|
// 工作区
|
|
@@ -3478,7 +3501,7 @@ export function runMathTool(rawArguments: unknown): MathResult {
|
|
|
3478
3501
|
const CACHEABLE: MathOperation[] = [
|
|
3479
3502
|
'auto', 'evaluate', 'solve', 'system', 'derivative', 'integral',
|
|
3480
3503
|
'simplify', 'expand', 'roots', 'matrix', 'eigen', 'stats', 'dist',
|
|
3481
|
-
'regression', 'ode', 'formula', 'units',
|
|
3504
|
+
'regression', 'ode', 'recurrence', 'formula', 'units',
|
|
3482
3505
|
]
|
|
3483
3506
|
/**
|
|
3484
3507
|
* 状态变更类操作:先清空缓存,再走正常流程。
|
|
@@ -3661,15 +3684,50 @@ export function runMathTool(rawArguments: unknown): MathResult {
|
|
|
3661
3684
|
case 'regression':
|
|
3662
3685
|
outcome = opRegression(args, input, precision)
|
|
3663
3686
|
break
|
|
3664
|
-
case 'formula':
|
|
3687
|
+
case 'formula': {
|
|
3665
3688
|
outcome = opFormula(args, engine, precision)
|
|
3689
|
+
/**
|
|
3690
|
+
* 批量公式的成败要在这里汇总成 `ok/partial/failed/succeeded`。
|
|
3691
|
+
*
|
|
3692
|
+
* 与 `evaluate` 的批量走同一套语义(见上方 3590 行那段注释):
|
|
3693
|
+
* · `ok:false` 告诉自动化流程「本批不是全好」
|
|
3694
|
+
* · `partial:true` 告诉它「但有成功的条目可用」
|
|
3695
|
+
* · 顶层 `error` 仍是 `undefined`(这是批量失败,不是整体错误)
|
|
3696
|
+
*
|
|
3697
|
+
* 踩过:这些字段直接在 `opFormulaBatch` 的返回值上展开,
|
|
3698
|
+
* 会被 `Outcome` 类型断言吞掉 —— 正文写着「成功 0,失败 3」,
|
|
3699
|
+
* 而结构化字段全是 `undefined`。所以在这里显式赋给 `MathResult`。
|
|
3700
|
+
*/
|
|
3701
|
+
if (Array.isArray((args as any).formulas)) {
|
|
3702
|
+
const batch = (outcome.value ?? {}) as Record<string, unknown>
|
|
3703
|
+
const failedCount = typeof batch.failed === 'number' ? batch.failed : 0
|
|
3704
|
+
const succeededCount = typeof batch.succeeded === 'number' ? batch.succeeded : 0
|
|
3705
|
+
const batched: MathResult = {
|
|
3706
|
+
ok: failedCount === 0,
|
|
3707
|
+
operation: 'formula',
|
|
3708
|
+
input: 'formulas: ' + (args as any).formulas.length + ' 条',
|
|
3709
|
+
result: outcome.result,
|
|
3710
|
+
precision,
|
|
3711
|
+
}
|
|
3712
|
+
if (outcome.value !== undefined) batched.value = outcome.value
|
|
3713
|
+
if (failedCount > 0) {
|
|
3714
|
+
batched.partial = succeededCount > 0
|
|
3715
|
+
batched.failed = failedCount
|
|
3716
|
+
batched.succeeded = succeededCount
|
|
3717
|
+
}
|
|
3718
|
+
outcome = batched
|
|
3719
|
+
}
|
|
3666
3720
|
break
|
|
3721
|
+
}
|
|
3667
3722
|
case 'formulas':
|
|
3668
3723
|
outcome = opFormulas(args)
|
|
3669
3724
|
break
|
|
3670
3725
|
case 'ode':
|
|
3671
3726
|
outcome = opOde(args, engine, precision)
|
|
3672
3727
|
break
|
|
3728
|
+
case 'recurrence':
|
|
3729
|
+
outcome = opRecurrence(args, precision)
|
|
3730
|
+
break
|
|
3673
3731
|
case 'world':
|
|
3674
3732
|
outcome = opWorld(args, precision)
|
|
3675
3733
|
break
|
|
@@ -3712,14 +3770,29 @@ export function runMathTool(rawArguments: unknown): MathResult {
|
|
|
3712
3770
|
break
|
|
3713
3771
|
}
|
|
3714
3772
|
|
|
3773
|
+
/**
|
|
3774
|
+
* ## 这里重新构造 `MathResult`,所以 `outcome` 上的成败字段必须**显式搬过来**
|
|
3775
|
+
*
|
|
3776
|
+
* 踩过两次,都是同一类:
|
|
3777
|
+
* ① 批量公式把 `ok/partial/failed/succeeded` 挂在 `outcome` 上 → 被这里覆盖成 `ok:true`
|
|
3778
|
+
* ② 早先 `evaluate` 批量也有同样问题,但它有独立的组装分支绕过去了
|
|
3779
|
+
*
|
|
3780
|
+
* 教训:`Outcome` 只是中间载体,真正的返回对象在这一处生成。
|
|
3781
|
+
* 想加任何顶层字段,都得在这里接一次。
|
|
3782
|
+
*/
|
|
3783
|
+
const batchOk = (outcome as any).ok as boolean | undefined
|
|
3715
3784
|
const result: MathResult = {
|
|
3716
|
-
ok: true,
|
|
3785
|
+
ok: batchOk === undefined ? true : batchOk,
|
|
3717
3786
|
operation,
|
|
3718
3787
|
input,
|
|
3719
3788
|
result: outcome.result,
|
|
3720
3789
|
precision,
|
|
3721
3790
|
}
|
|
3722
3791
|
if (outcome.value !== undefined) result.value = outcome.value
|
|
3792
|
+
for (const key of ['partial', 'failed', 'succeeded'] as const) {
|
|
3793
|
+
const value = (outcome as any)[key]
|
|
3794
|
+
if (value !== undefined) (result as any)[key] = value
|
|
3795
|
+
}
|
|
3723
3796
|
const variables = scopeSummary(args.variables)
|
|
3724
3797
|
if (variables !== undefined) result.variables = variables
|
|
3725
3798
|
|
|
@@ -4238,8 +4311,7 @@ const PARAMETER_SPEC = {
|
|
|
4238
4311
|
expression: {
|
|
4239
4312
|
type: 'string',
|
|
4240
4313
|
description:
|
|
4241
|
-
'
|
|
4242
|
-
'例:10^20 + 5、factorial(50)、x^3 * sin(x)、[[1,2],[3,4]] * [[5],[6]]、[1,2,3,4]。operation=help 时可空。',
|
|
4314
|
+
'表达式、方程或数据。多方程逗号分隔。例:10^20+5、x^3*sin(x)、[[1,2],[3,4]]*[[5],[6]]。',
|
|
4243
4315
|
},
|
|
4244
4316
|
expressions: {
|
|
4245
4317
|
type: 'array',
|
|
@@ -4285,8 +4357,7 @@ const PARAMETER_SPEC = {
|
|
|
4285
4357
|
// 不逐个解释每个 operation 名称:enum 里已经列全,而 `help` 有完整说明。
|
|
4286
4358
|
// 这里只给「怎么选」的判断线索,那才是 AI 真正需要的。
|
|
4287
4359
|
description:
|
|
4288
|
-
'默认 auto
|
|
4289
|
-
'改动设定后用 world/derivation;不确定就调 help 看全表。',
|
|
4360
|
+
'默认 auto。简易算式 evaluate;数据 stats;改设定 world/derivation;不确定调 help。',
|
|
4290
4361
|
},
|
|
4291
4362
|
variable: {
|
|
4292
4363
|
type: 'string',
|
|
@@ -4301,9 +4372,7 @@ const PARAMETER_SPEC = {
|
|
|
4301
4372
|
unitFrom: {
|
|
4302
4373
|
type: 'string',
|
|
4303
4374
|
description:
|
|
4304
|
-
'
|
|
4305
|
-
'英制(英里/英尺/磅/加仑)、天文(AU/光年/秒差距/地球半径/太阳半径)。' +
|
|
4306
|
-
'只给单位不给参数则列出全部可用单位。',
|
|
4375
|
+
'源单位(units)。支持中文古制(里/丈/斤/亩/时辰/刻)、英制(英里/磅/加仑)、天文(AU/光年)。只给单位不给数值则列全表。',
|
|
4307
4376
|
},
|
|
4308
4377
|
unitTo: {
|
|
4309
4378
|
type: 'string',
|
|
@@ -4319,14 +4388,12 @@ const PARAMETER_SPEC = {
|
|
|
4319
4388
|
type: 'object',
|
|
4320
4389
|
additionalProperties: true,
|
|
4321
4390
|
description:
|
|
4322
|
-
'收支盘点(
|
|
4323
|
-
'只判社会收支;单项生理/工程上限用 feasibility。',
|
|
4391
|
+
'收支盘点(balance):每项 {demand, supply, unit?},给最短板。单项上限用 feasibility。',
|
|
4324
4392
|
},
|
|
4325
4393
|
bodyName: {
|
|
4326
4394
|
type: 'string',
|
|
4327
4395
|
description:
|
|
4328
|
-
'
|
|
4329
|
-
'已收录太阳系全 8 大行星 + 月球类卫星 + 代表性系外行星 + 矮行星 + 各亮度级恒星。',
|
|
4396
|
+
'查天体(bodies):id(mars)或中文名(火星)。含行星、卫星、系外行星、矮行星、各级恒星。',
|
|
4330
4397
|
},
|
|
4331
4398
|
bodyKind: {
|
|
4332
4399
|
type: 'string',
|
|
@@ -4336,8 +4403,7 @@ const PARAMETER_SPEC = {
|
|
|
4336
4403
|
bodyConstant: {
|
|
4337
4404
|
type: 'string',
|
|
4338
4405
|
description:
|
|
4339
|
-
'bodies:改常数后看哪些天体数据该重算。例
|
|
4340
|
-
'输出分「必须重算」与「绝不该动」两块(行星质量/半径/轨道与 α 无关)。',
|
|
4406
|
+
'bodies:改常数后看哪些天体数据该重算。例 alpha_fs + bodyFactor=2。分「必须重算」与「绝不该动」两块。',
|
|
4341
4407
|
},
|
|
4342
4408
|
bodyFactor: {
|
|
4343
4409
|
type: 'number',
|
|
@@ -4368,8 +4434,7 @@ const PARAMETER_SPEC = {
|
|
|
4368
4434
|
displayPrecision: {
|
|
4369
4435
|
type: 'integer',
|
|
4370
4436
|
description:
|
|
4371
|
-
'**显示精度:小数点后几位**(0-64,默认 8
|
|
4372
|
-
'可用 workspace set displayPrecision=N 固化(那里的 0 = 清除)。',
|
|
4437
|
+
'**显示精度:小数点后几位**(0-64,默认 8)。只截小数、整数完整,0=只留整数。可 workspace set 固化(0=清除)。',
|
|
4373
4438
|
},
|
|
4374
4439
|
data: {
|
|
4375
4440
|
type: 'array',
|
|
@@ -4398,30 +4463,32 @@ const PARAMETER_SPEC = {
|
|
|
4398
4463
|
formula: {
|
|
4399
4464
|
type: 'string',
|
|
4400
4465
|
description:
|
|
4401
|
-
'operation="formula"
|
|
4402
|
-
'用 operation="formulas" 检索可用公式。',
|
|
4466
|
+
'operation="formula":公式 id 或名称,如 "escape_velocity"、"逃逸速度"。检索用 operation="formulas";多条用 formulas 数组。',
|
|
4403
4467
|
},
|
|
4468
|
+
formulas: { type: 'array', items: { type: 'json', description: '"kleiber" 或 {formula, overrides?, label?}' }, description: '批量调多条公式;一条失败不影响其它条。' },
|
|
4404
4469
|
overrides: {
|
|
4405
4470
|
type: 'object',
|
|
4406
4471
|
additionalProperties: true,
|
|
4407
4472
|
description:
|
|
4408
|
-
'
|
|
4473
|
+
'覆盖公式任意参数(架空改造的关键)。例:重力 1.5 倍 {"g":14.71}、光速 {"c":1e8}。',
|
|
4409
4474
|
},
|
|
4410
4475
|
customExpression: {
|
|
4411
4476
|
type: 'string',
|
|
4412
4477
|
description:
|
|
4413
|
-
'structure
|
|
4478
|
+
'structure 级改造:临时替换公式表达式,沿用参数名。例 customExpression="m*g*1.3" 即重力 +30%。',
|
|
4414
4479
|
},
|
|
4415
4480
|
query: {
|
|
4416
4481
|
type: 'string',
|
|
4417
4482
|
description: 'operation="formulas" 的检索关键词,例如 "重力"、"熵"、"人口";传 "*" 或留空列出全部分类。',
|
|
4418
4483
|
},
|
|
4484
|
+
recurrence: { type: 'string', description: 'operation="recurrence":下一期 = f(本期),如 "P*2"、"P*min(1.2,1000/P)"。配 initial 与 periods 出逐期表。' },
|
|
4485
|
+
periods: { type: 'integer', description: 'recurrence 的迭代期数(默认 12,上限 5000)。' },
|
|
4486
|
+
at: { type: 'array', items: { type: 'number' }, description: 'ode 要精确输出的时点,如 [5,10,20](写年表用)。' },
|
|
4419
4487
|
initial: {
|
|
4420
4488
|
type: 'object',
|
|
4421
4489
|
additionalProperties: true,
|
|
4422
4490
|
description:
|
|
4423
|
-
'
|
|
4424
|
-
'二阶方程降阶后可能还需要辅助变量(如 y_d 表示 dy/dt),缺了会提示补哪个。',
|
|
4491
|
+
'ode/recurrence 初值,如 {"S":999,"I":1}。二阶降阶需辅助变量 y_d=dy/dt,缺了会提示。',
|
|
4425
4492
|
},
|
|
4426
4493
|
from: {
|
|
4427
4494
|
type: 'number',
|
|
@@ -4445,9 +4512,7 @@ const PARAMETER_SPEC = {
|
|
|
4445
4512
|
// 字段清单不写在 schema 里:schema 每轮都要付费,而这些字段只在
|
|
4446
4513
|
// 真用 world 时才需要。全文见 help(operation="help", query="world")。
|
|
4447
4514
|
description:
|
|
4448
|
-
'星球参数(
|
|
4449
|
-
'常用键:planetMass/planetRadius、starMass/starTemp、rotationHours、obliquityDeg。' +
|
|
4450
|
-
'完整字段表见 help。',
|
|
4515
|
+
'星球参数(world),可选,默认地球。常用键 planetMass、starMass、rotationHours、obliquityDeg。完整见 help。',
|
|
4451
4516
|
},
|
|
4452
4517
|
planetRadius: {
|
|
4453
4518
|
type: 'number',
|
|
@@ -4470,16 +4535,14 @@ const PARAMETER_SPEC = {
|
|
|
4470
4535
|
additionalProperties: true,
|
|
4471
4536
|
// 同上:地形字段有九项,逐项列在 schema 里太贵。
|
|
4472
4537
|
description:
|
|
4473
|
-
'局部地形(
|
|
4474
|
-
'常用键:kind、elevation、latitudeDeg、oceanCurrent。完整键表见 help。',
|
|
4538
|
+
'局部地形(world 附带)。常用键 kind、elevation、latitudeDeg、oceanCurrent。完整见 help。',
|
|
4475
4539
|
},
|
|
4476
4540
|
constants: {
|
|
4477
4541
|
type: 'object',
|
|
4478
4542
|
additionalProperties: true,
|
|
4479
4543
|
// 旋钮清单移进 help:只有要改常数时才需要,不该每轮付费
|
|
4480
4544
|
description:
|
|
4481
|
-
'要改的物理常数(
|
|
4482
|
-
'例:{c:1.5e8}。可用旋钮清单见 help 的 constants 节。',
|
|
4545
|
+
'要改的物理常数(constants):只改基础旋钮,派生量自动重算。例 {c:1.5e8}。旋钮清单见 help。',
|
|
4483
4546
|
},
|
|
4484
4547
|
helpTopic: {
|
|
4485
4548
|
type: 'string',
|
|
@@ -4558,6 +4621,98 @@ function checkPrecisionTruncation(
|
|
|
4558
4621
|
' 位可能已失真。需要精确值时请用 precision:64(默认),' +
|
|
4559
4622
|
'只想让输出短些请用 displayPrecision。'
|
|
4560
4623
|
}
|
|
4624
|
+
|
|
4625
|
+
/**
|
|
4626
|
+
* 批量调公式(`formulas: [...]`)。
|
|
4627
|
+
*
|
|
4628
|
+
* ## 为什么复用 opFormula 而不是重写一套
|
|
4629
|
+
*
|
|
4630
|
+
* 单个调用涉及:严格解析、overrides 覆盖、单位换算、terse 精简、
|
|
4631
|
+
* 适用域提示、未生效 key 上报 —— 这些逻辑**必须与单条完全一致**。
|
|
4632
|
+
* 重写一套必然漂移,而「单条能算、批量算得不一样」正是这个项目
|
|
4633
|
+
* 反复修过的那类缺陷(1107 报告的批量非有限值、单条/批量输出不一致)。
|
|
4634
|
+
*
|
|
4635
|
+
* 所以这里只做三件事:逐条调用、收集结果、汇总成败。
|
|
4636
|
+
*
|
|
4637
|
+
* ## 失败语义
|
|
4638
|
+
*
|
|
4639
|
+
* 一条失败 → 该条在输出里标 `失败[type]`,继续算下一条,
|
|
4640
|
+
* 最后由 `ok`/`failed`/`succeeded` 如实汇总。**不因为一条错就中断整批**。
|
|
4641
|
+
*
|
|
4642
|
+
* @param args - 含 `formulas` 数组的入参
|
|
4643
|
+
* @param engine - mathjs 实例
|
|
4644
|
+
* @param precision - 计算精度
|
|
4645
|
+
* @returns 批量结果
|
|
4646
|
+
*/
|
|
4647
|
+
function opFormulaBatch(args: MathArgs, engine: any, precision: number): Outcome {
|
|
4648
|
+
const list = (args as any).formulas as any[]
|
|
4649
|
+
const lines: string[] = []
|
|
4650
|
+
const rows: Record<string, unknown>[] = []
|
|
4651
|
+
let failed = 0
|
|
4652
|
+
lines.push('═══ 批量公式(' + list.length + ' 条)═══')
|
|
4653
|
+
lines.push('')
|
|
4654
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
4655
|
+
const item = list[index]
|
|
4656
|
+
const isObject = item !== null && typeof item === 'object'
|
|
4657
|
+
const id = String(isObject ? (item.formula ?? item.id ?? '') : item).trim()
|
|
4658
|
+
const label = isObject && item.label !== undefined ? String(item.label) : ''
|
|
4659
|
+
/** 逐条构造入参:继承顶层公共参数(terse/unitFrom/unitTo/precision),再叠加元素自己的。 */
|
|
4660
|
+
const oneArgs: MathArgs = {
|
|
4661
|
+
...args,
|
|
4662
|
+
formulas: undefined,
|
|
4663
|
+
formula: id,
|
|
4664
|
+
expression: undefined,
|
|
4665
|
+
overrides: isObject && item.overrides ? item.overrides : (isObject ? undefined : args.overrides),
|
|
4666
|
+
} as MathArgs
|
|
4667
|
+
(oneArgs as any).formulas = undefined
|
|
4668
|
+
if (isObject && item.terse !== undefined) (oneArgs as any).terse = item.terse
|
|
4669
|
+
const prefix = label === '' ? '' : label + '(' + id + ')'
|
|
4670
|
+
try {
|
|
4671
|
+
const outcome = opFormula(oneArgs, engine, precision)
|
|
4672
|
+
const text = String(outcome.result ?? '').trim()
|
|
4673
|
+
/**
|
|
4674
|
+
* 抓「结果:」那一行 —— 公式输出的第一行是标题(名称 + 分类),
|
|
4675
|
+
* 数值在「结果:」行上。只取首行会得到 `克莱伯定律(代谢率) [physics/scaling]`,
|
|
4676
|
+
* 数值整个丢了,而批量恰恰是为了看一串数。
|
|
4677
|
+
*/
|
|
4678
|
+
const valueLine = text.split(/\r?\n/).find(function (line) { return line.trim().startsWith('结果') })
|
|
4679
|
+
const first = valueLine ?? (text.split(/\r?\n/).find(function (line) { return line.trim() !== '' }) ?? '')
|
|
4680
|
+
/** terse 输出本身已是 `kleiber = 31622…`,别再加一层 `id = ` 变成 `kleiber = kleiber = …`。 */
|
|
4681
|
+
const alreadyNamed = String(first).trim().startsWith(id + ' =')
|
|
4682
|
+
const shown = String(first).replace(/^结果\s*[::]\s*/, '').trim()
|
|
4683
|
+
const body = alreadyNamed ? shown : id + ' = ' + shown
|
|
4684
|
+
lines.push(' ' + (prefix === '' ? body : prefix + ' = ' + shown))
|
|
4685
|
+
rows.push({ formula: id, label: label === '' ? null : label, ok: true, result: outcome.value ?? null })
|
|
4686
|
+
} catch (error) {
|
|
4687
|
+
failed += 1
|
|
4688
|
+
const type = (error as any)?.type ?? 'unknown'
|
|
4689
|
+
const message = String((error as any)?.message ?? error).slice(0, 120)
|
|
4690
|
+
lines.push(' ' + (prefix === '' ? id : prefix) + ' → 失败[' + type + '] ' + message)
|
|
4691
|
+
rows.push({ formula: id, label: label === '' ? null : label, ok: false, error: type })
|
|
4692
|
+
}
|
|
4693
|
+
}
|
|
4694
|
+
const succeeded = list.length - failed
|
|
4695
|
+
lines.push('')
|
|
4696
|
+
lines.push(
|
|
4697
|
+
failed === 0
|
|
4698
|
+
? '全部 ' + succeeded + ' 条都有结果(只表示公式存在且参数可算,不含结论正确性判断)'
|
|
4699
|
+
: '成功 ' + succeeded + ',失败 ' + failed + '(失败条已逐条标注原因)',
|
|
4700
|
+
)
|
|
4701
|
+
/**
|
|
4702
|
+
* 汇总字段必须**真的出现在返回值里**:`ok` / `failed` / `succeeded` / `partial`。
|
|
4703
|
+
*
|
|
4704
|
+
* 踩过:`{...cond ? {...} : {...}}` 这种写法在 Outcome 类型下会被类型断言吞掉,
|
|
4705
|
+
* 实测返回 `ok=true` 却 `failed=undefined` —— 而正文里明明写着「成功 0,失败 3」。
|
|
4706
|
+
* 正文与结构化字段不一致,比只给正文更糟(调用方读哪个?)。
|
|
4707
|
+
* 所以改成显式赋值。
|
|
4708
|
+
*/
|
|
4709
|
+
/** 汇总字段放进 `value`,由调用方(`runMathTool`)提升到顶层 `MathResult`。 */
|
|
4710
|
+
return {
|
|
4711
|
+
result: lines.join('\n'),
|
|
4712
|
+
value: toJsonValue({ count: list.length, succeeded, failed, rows }),
|
|
4713
|
+
}
|
|
4714
|
+
}
|
|
4715
|
+
|
|
4561
4716
|
/**
|
|
4562
4717
|
* 数学计算工具(`math_execute`)。
|
|
4563
4718
|
*
|
package/src/ode.ts
CHANGED
|
@@ -197,6 +197,13 @@ export interface OdeOptions {
|
|
|
197
197
|
steps: number
|
|
198
198
|
/** 返回值里包含的采样点数上限 */
|
|
199
199
|
sampleLimit?: number
|
|
200
|
+
/**
|
|
201
|
+
* 指定要精确输出的时点(如 `[5, 10, 20]`)。
|
|
202
|
+
*
|
|
203
|
+
* 与 `sampleLimit` 不同:那是「均匀抽几个点展示」,这是「我就要这几个时刻的值」。
|
|
204
|
+
* 写作时写的是「第 5 年 1,756 人」这种具体整数,均匀采样的 4.8、10.5 用不上。
|
|
205
|
+
*/
|
|
206
|
+
atPoints?: number[]
|
|
200
207
|
}
|
|
201
208
|
|
|
202
209
|
/** 积分结果。 */
|
|
@@ -208,6 +215,13 @@ export interface OdeSolution {
|
|
|
208
215
|
final: Record<string, number>
|
|
209
216
|
/** 每个变量的极值 */
|
|
210
217
|
extremes: Record<string, { max: number; maxAt: number; min: number; minAt: number }>
|
|
218
|
+
/**
|
|
219
|
+
* 指定时点的精确值(按请求顺序)。
|
|
220
|
+
*
|
|
221
|
+
* 用同一套 RK4 从区间起点推进到该时点,**不是插值** ——
|
|
222
|
+
* 插值会在「第 5 年 1,750.3 人」这种地方引入误差,而年表要的是准数。
|
|
223
|
+
*/
|
|
224
|
+
atValues?: Array<{ t: number; values: Record<string, number> }>
|
|
211
225
|
/** 实际使用的步数 */
|
|
212
226
|
steps: number
|
|
213
227
|
/** 步长 */
|
|
@@ -319,6 +333,9 @@ export function solveOde(
|
|
|
319
333
|
const sampleLimit = Math.max(2, options.sampleLimit ?? 24)
|
|
320
334
|
const sampleEvery = Math.max(1, Math.floor(steps / sampleLimit))
|
|
321
335
|
const samples: Array<{ t: number; values: Record<string, number> }> = []
|
|
336
|
+
/** 待消费的指定时点(已在调用方排好序)与已记录结果。 */
|
|
337
|
+
const atQueue: number[] = (options.atPoints ?? []).filter((point) => Number.isFinite(point) && point >= from && point <= to)
|
|
338
|
+
const atRecorded: Array<{ t: number; values: Record<string, number> }> = []
|
|
322
339
|
const warnings: string[] = []
|
|
323
340
|
|
|
324
341
|
const record = (time: number, values: number[]): void => {
|
|
@@ -391,7 +408,35 @@ export function solveOde(
|
|
|
391
408
|
if ((stepIndex + 1) % sampleEvery === 0 || stepIndex === steps - 1) {
|
|
392
409
|
record(t, state)
|
|
393
410
|
}
|
|
411
|
+
/**
|
|
412
|
+
* 指定时点:走到该点附近就记一次。
|
|
413
|
+
*
|
|
414
|
+
* 判据是「已跨过」而不是「恰好等于」—— RK4 的步长一般除不尽,
|
|
415
|
+
* 想要 t=5 时通常永远走不到 5.000000。跨过时取**跨过点的值**,
|
|
416
|
+
* 与主解同源,比插值准。
|
|
417
|
+
*/
|
|
418
|
+
if (atQueue.length > 0 && t >= atQueue[0] && from <= to) {
|
|
419
|
+
if (atRecorded.length === 0 || atRecorded[atRecorded.length - 1].t !== atQueue[0]) {
|
|
420
|
+
const values: Record<string, number> = {}
|
|
421
|
+
for (let index = 0; index < dimension; index += 1) values[variables[index]] = state[index]
|
|
422
|
+
atRecorded.push({ t: atQueue.shift() as number, values })
|
|
423
|
+
} else {
|
|
424
|
+
atQueue.shift()
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* 没被循环消费到的时点(落在终点之后或步长太粗)用终点状态补上,
|
|
431
|
+
* 不能静默丢弃 —— 请求了 `at:[20]` 却什么都不返回,比报错更糟。
|
|
432
|
+
*/
|
|
433
|
+
for (const point of atQueue) {
|
|
434
|
+
const values: Record<string, number> = {}
|
|
435
|
+
for (let index = 0; index < dimension; index += 1) values[variables[index]] = state[index]
|
|
436
|
+
atRecorded.push({ t: point, values })
|
|
394
437
|
}
|
|
438
|
+
atQueue.length = 0
|
|
439
|
+
atRecorded.sort((a, b) => a.t - b.t)
|
|
395
440
|
|
|
396
441
|
const final: Record<string, number> = {}
|
|
397
442
|
for (let index = 0; index < dimension; index += 1) final[variables[index]] = state[index]
|
|
@@ -408,6 +453,7 @@ export function solveOde(
|
|
|
408
453
|
samples,
|
|
409
454
|
final,
|
|
410
455
|
extremes,
|
|
456
|
+
atValues: atRecorded,
|
|
411
457
|
steps,
|
|
412
458
|
stepSize,
|
|
413
459
|
warnings,
|
package/src/ops/ode-op.ts
CHANGED
|
@@ -39,6 +39,26 @@ export function opOde(args: MathArgs, engine: any, precision: number): Outcome {
|
|
|
39
39
|
const to = typeof args.to === 'number' ? args.to : 10
|
|
40
40
|
const steps = typeof args.steps === 'number' ? Math.min(1_000_000, Math.max(1, Math.round(args.steps))) : 1000
|
|
41
41
|
const sampleLimit = typeof args.samples === 'number' ? Math.max(2, Math.min(200, Math.round(args.samples))) : 24
|
|
42
|
+
/**
|
|
43
|
+
* ## 指定采样时点(`at: [5, 10, 20]`)
|
|
44
|
+
*
|
|
45
|
+
* 实测反馈(能力评估文档 3.3 节):
|
|
46
|
+
*
|
|
47
|
+
* > 我要「第 5 年、第 10 年、第 20 年」的值,`ode` 给的是均匀采样:
|
|
48
|
+
* > `t = 1, 2.9, 4.8, 6.7, 8.6, 10.5, 12.4, …` —— **没有一年是我要的**。
|
|
49
|
+
*
|
|
50
|
+
* 而「写年表」恰恰是这类推演最常见的需求:写作时写的是
|
|
51
|
+
* 「第 5 年 1,756 人」这种具体整数,插值出来的 1,750.3 用不上。
|
|
52
|
+
*
|
|
53
|
+
* 实现方式:**在给定时点补算**,不是在采样表里插值。
|
|
54
|
+
* 用同一套 RK4 从区间起点走到该时点,结果与主解一致、无插值误差。
|
|
55
|
+
*/
|
|
56
|
+
const atPoints = Array.isArray((args as any).at)
|
|
57
|
+
? ((args as any).at as unknown[])
|
|
58
|
+
.map((value) => Number(value))
|
|
59
|
+
.filter((value) => Number.isFinite(value))
|
|
60
|
+
.sort((a, b) => a - b)
|
|
61
|
+
: []
|
|
42
62
|
|
|
43
63
|
let solution: OdeSolution
|
|
44
64
|
try {
|
|
@@ -46,7 +66,7 @@ export function opOde(args: MathArgs, engine: any, precision: number): Outcome {
|
|
|
46
66
|
// RK4 的中间值天然带 15 位以上小数(如 1.0050251567199238),
|
|
47
67
|
// BigNumber 会抛 "Cannot implicitly convert a number with >15 significant digits"。
|
|
48
68
|
// 数值 ODE 本身就只精度到 ~1e-12,用 BigNumber 毫无意义且必然失败。
|
|
49
|
-
solution = solveOde(fast(), system, { initial, from, to, steps, sampleLimit })
|
|
69
|
+
solution = solveOde(fast(), system, { initial, from, to, steps, sampleLimit, atPoints })
|
|
50
70
|
} catch (error) {
|
|
51
71
|
if (error instanceof OdeError) {
|
|
52
72
|
const hint =
|
|
@@ -83,6 +103,28 @@ export function opOde(args: MathArgs, engine: any, precision: number): Outcome {
|
|
|
83
103
|
lines.push(cells.join(' '))
|
|
84
104
|
}
|
|
85
105
|
|
|
106
|
+
/**
|
|
107
|
+
* 指定时点的值单独一段 —— 这是写年表时真正要抄的数。
|
|
108
|
+
*
|
|
109
|
+
* 放在终点值之前:读者的目的常常是「拿第 5/10/20 年」,
|
|
110
|
+
* 而不是「拿终点」。
|
|
111
|
+
*/
|
|
112
|
+
const atValues = solution.atValues ?? []
|
|
113
|
+
if (atValues.length > 0) {
|
|
114
|
+
lines.push('')
|
|
115
|
+
lines.push('指定时点:')
|
|
116
|
+
const atHeader = [system.independent.padEnd(12), ...shownVariables.map((name) => name.padStart(14))]
|
|
117
|
+
lines.push(atHeader.join(' '))
|
|
118
|
+
lines.push('-'.repeat(atHeader.join(' ').length))
|
|
119
|
+
for (const point of atValues) {
|
|
120
|
+
const cells = [
|
|
121
|
+
trimNumber(point.t, 6).padEnd(12),
|
|
122
|
+
...shownVariables.map((name) => trimNumber(point.values[name] ?? Number.NaN, precision).padStart(14)),
|
|
123
|
+
]
|
|
124
|
+
lines.push(cells.join(' '))
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
86
128
|
lines.push('')
|
|
87
129
|
lines.push('终点值:')
|
|
88
130
|
for (const name of shownVariables) {
|